mistralrs_core/pipeline/
vision.rs

1use super::isq::ImatrixDataSource;
2use super::isq::UqffFullSer;
3use super::{
4    get_model_paths, get_xlora_paths, AdapterKind, AnyMoePipelineMixin, AutoVisionLoader,
5    CacheManager, CacheManagerMixin, EitherCache, ForwardInputsResult, Gemma3Loader,
6    GeneralMetadata, IsqPipelineMixin, Loader, MetadataMixin, MiniCpmOLoader, ModelCategory,
7    ModelKind, ModelPaths, MultimodalPromptPrefixer, Phi4MMLoader, PreProcessingMixin, Processor,
8    Qwen2VLLoader, Qwen3VLLoader, Qwen3VLMoELoader, TokenSource, VLlama4Loader, VLlamaLoader,
9    VisionModel, VisionModelLoader,
10};
11use super::{
12    Gemma3nLoader, Idefics2Loader, Idefics3Loader, LLaVALoader, LLaVANextLoader, Mistral3Loader,
13    Phi3VLoader, Qwen2_5VLLoader, VisionLoaderType,
14};
15use crate::attention::ATTENTION_CHUNK_SIZE;
16use crate::device_map::{self, DeviceMapper};
17use crate::distributed::{self, WorkerTransferData};
18use crate::kv_cache::{FullCacheManager, NormalCacheManager};
19use crate::paged_attention::{calculate_cache_config, AttentionImplementation, CacheEngine};
20use crate::pipeline::chat_template::{calculate_eos_tokens, GenerationConfig};
21use crate::pipeline::llg::build_llg_factory;
22use crate::pipeline::loaders::auto_device_map;
23use crate::pipeline::loaders::QuantizationConfigShim;
24use crate::pipeline::sampling::sample_and_add_toks;
25use crate::pipeline::text_models_inputs_processor::make_prompt_chunk;
26use crate::pipeline::{get_chat_template, ChatTemplate, IsqOrganization, LocalModelPaths};
27use crate::prefix_cacher::PrefixCacheManagerV2;
28use crate::sequence::Sequence;
29use crate::utils::tokenizer::get_tokenizer;
30use crate::utils::varbuilder_utils::DeviceForLoadTensor;
31use crate::utils::{
32    progress::{new_multi_progress, ProgressScopeGuard},
33    tokens::get_token,
34    varbuilder_utils::from_mmaped_safetensors,
35};
36use crate::vision_models::preprocessor_config::PreProcessorConfig;
37use crate::vision_models::processor_config::ProcessorConfig;
38use crate::vision_models::ModelInputs;
39use crate::{
40    api_dir_list, api_get_file, get_paths, get_uqff_paths, vision_normal_model_loader,
41    vision_normal_model_loader_sharded, AnyMoeExpertType, DeviceMapSetting, Ordering,
42    PagedAttentionConfig, Pipeline, Topology, TryIntoDType, GLOBAL_HF_CACHE,
43};
44use anyhow::Result;
45use candle_core::{Device, Tensor, Var};
46use hf_hub::Cache;
47use hf_hub::{api::sync::ApiBuilder, Repo, RepoType};
48use mistralrs_quant::log::once_log_info;
49use mistralrs_quant::{
50    AfqLayer, GgufMatMul, HqqLayer, ImmediateIsqOverride, IsqType, QuantizedSerdeType,
51};
52use rand_isaac::Isaac64Rng;
53use regex_automata::meta::Regex;
54use std::any::Any;
55use std::borrow::Cow;
56use std::path::{Path, PathBuf};
57use std::str::FromStr;
58use std::sync::{Arc, RwLock};
59use std::time::Instant;
60use std::{env, fs};
61use tokenizers::Tokenizer;
62use tokio::sync::Mutex;
63use tracing::{info, warn};
64
65pub struct VisionPipeline {
66    model: Box<dyn VisionModel + Send + Sync>,
67    tokenizer: Arc<Tokenizer>,
68    chat_template: Arc<ChatTemplate>,
69    model_id: String,
70    metadata: Arc<GeneralMetadata>,
71    processor: Arc<dyn Processor + Send + Sync>,
72    preprocessor_config: Arc<PreProcessorConfig>,
73    topology: Option<Topology>,
74    silent: bool,
75    prefixer: Arc<dyn MultimodalPromptPrefixer>,
76    mapper: Box<dyn DeviceMapper + Send + Sync>,
77
78    // For full UQFF serialization
79    template_filename: Option<PathBuf>,
80    generation_config: Option<PathBuf>,
81    config: String,
82    processor_filename: Option<PathBuf>,
83    preprocessor_filename: Option<PathBuf>,
84    imatrix: Option<PathBuf>,
85}
86
87/// A loader for a vision (non-quantized) model.
88pub struct VisionLoader {
89    inner: Box<dyn VisionModelLoader>,
90    model_id: String,
91    config: VisionSpecificConfig,
92    kind: ModelKind,
93    chat_template: Option<String>,
94    tokenizer_json: Option<String>,
95    xlora_model_id: Option<String>,
96    xlora_order: Option<Ordering>,
97    token_source: RwLock<Option<TokenSource>>,
98    revision: RwLock<Option<String>>,
99    from_uqff: RwLock<Option<Vec<PathBuf>>>,
100    jinja_explicit: Option<String>,
101    hf_cache_path: Option<PathBuf>,
102    lora_adapter_ids: Option<Vec<String>>,
103}
104
105#[derive(Default)]
106/// A builder for a loader for a vision (non-quantized) model.
107pub struct VisionLoaderBuilder {
108    model_id: Option<String>,
109    config: VisionSpecificConfig,
110    kind: ModelKind,
111    chat_template: Option<String>,
112    tokenizer_json: Option<String>,
113    jinja_explicit: Option<String>,
114    hf_cache_path: Option<PathBuf>,
115    lora_adapter_ids: Option<Vec<String>>,
116}
117
118#[derive(Clone, Default)]
119/// Config specific to loading a vision model.
120pub struct VisionSpecificConfig {
121    pub topology: Option<Topology>,
122    pub write_uqff: Option<PathBuf>,
123    pub from_uqff: Option<Vec<PathBuf>>,
124    pub max_edge: Option<u32>,
125    pub imatrix: Option<PathBuf>,
126    pub calibration_file: Option<PathBuf>,
127    pub hf_cache_path: Option<PathBuf>,
128    pub matformer_config_path: Option<PathBuf>,
129    pub matformer_slice_name: Option<String>,
130}
131
132impl VisionLoaderBuilder {
133    pub fn new(
134        config: VisionSpecificConfig,
135        chat_template: Option<String>,
136        tokenizer_json: Option<String>,
137        model_id: Option<String>,
138        jinja_explicit: Option<String>,
139    ) -> Self {
140        Self {
141            config,
142            chat_template,
143            tokenizer_json,
144            model_id,
145            jinja_explicit,
146            kind: ModelKind::Normal,
147            hf_cache_path: None,
148            ..Default::default()
149        }
150    }
151
152    pub fn hf_cache_path(mut self, hf_cache_path: PathBuf) -> Self {
153        self.hf_cache_path = Some(hf_cache_path);
154        self
155    }
156
157    pub fn with_lora(mut self, lora_adapter_ids: Vec<String>) -> Self {
158        self.kind = ModelKind::Adapter {
159            adapter: AdapterKind::Lora,
160        };
161        self.lora_adapter_ids = Some(lora_adapter_ids);
162        self
163    }
164
165    pub fn build(self, loader: Option<VisionLoaderType>) -> Box<dyn Loader> {
166        let loader: Box<dyn VisionModelLoader> = match loader {
167            Some(VisionLoaderType::Phi3V) => Box::new(Phi3VLoader),
168            Some(VisionLoaderType::Idefics2) => Box::new(Idefics2Loader),
169            Some(VisionLoaderType::LLaVANext) => Box::new(LLaVANextLoader),
170            Some(VisionLoaderType::LLaVA) => Box::new(LLaVALoader),
171            Some(VisionLoaderType::VLlama) => Box::new(VLlamaLoader),
172            Some(VisionLoaderType::Qwen2VL) => Box::new(Qwen2VLLoader),
173            Some(VisionLoaderType::Idefics3) => Box::new(Idefics3Loader),
174            Some(VisionLoaderType::MiniCpmO) => Box::new(MiniCpmOLoader),
175            Some(VisionLoaderType::Phi4MM) => Box::new(Phi4MMLoader),
176            Some(VisionLoaderType::Qwen2_5VL) => Box::new(Qwen2_5VLLoader),
177            Some(VisionLoaderType::Gemma3) => Box::new(Gemma3Loader),
178            Some(VisionLoaderType::Mistral3) => Box::new(Mistral3Loader),
179            Some(VisionLoaderType::Llama4) => Box::new(VLlama4Loader),
180            Some(VisionLoaderType::Gemma3n) => Box::new(Gemma3nLoader),
181            Some(VisionLoaderType::Qwen3VL) => Box::new(Qwen3VLLoader),
182            Some(VisionLoaderType::Qwen3VLMoE) => Box::new(Qwen3VLMoELoader),
183            None => Box::new(AutoVisionLoader),
184        };
185        Box::new(VisionLoader {
186            inner: loader,
187            model_id: self.model_id.unwrap(),
188            config: self.config,
189            kind: self.kind,
190            chat_template: self.chat_template,
191            tokenizer_json: self.tokenizer_json,
192            xlora_model_id: None,
193            xlora_order: None,
194            jinja_explicit: self.jinja_explicit,
195            token_source: RwLock::new(None),
196            revision: RwLock::new(None),
197            from_uqff: RwLock::new(None),
198            hf_cache_path: self.hf_cache_path,
199            lora_adapter_ids: self.lora_adapter_ids,
200        })
201    }
202}
203
204impl Loader for VisionLoader {
205    #[allow(clippy::type_complexity, clippy::too_many_arguments)]
206    fn load_model_from_hf(
207        &self,
208        revision: Option<String>,
209        token_source: TokenSource,
210        dtype: &dyn TryIntoDType,
211        device: &Device,
212        silent: bool,
213        mapper: DeviceMapSetting,
214        in_situ_quant: Option<IsqType>,
215        paged_attn_config: Option<PagedAttentionConfig>,
216    ) -> Result<Arc<Mutex<dyn Pipeline + Send + Sync>>> {
217        let _progress_guard = ProgressScopeGuard::new(silent);
218        let cache = self
219            .hf_cache_path
220            .clone()
221            .map(Cache::new)
222            .unwrap_or_default();
223        GLOBAL_HF_CACHE.get_or_init(|| cache);
224
225        let paths: anyhow::Result<Box<dyn ModelPaths>> = get_paths!(
226            LocalModelPaths,
227            &token_source,
228            revision.clone(),
229            self,
230            None,
231            None,
232            silent,
233            self.config.from_uqff.is_some()
234        );
235        if let Some(from_uqff) = self.config.from_uqff.clone() {
236            *self.from_uqff.write().unwrap() = Some(get_uqff_paths!(&from_uqff, self, silent));
237        }
238        *self
239            .token_source
240            .write()
241            .expect("Failed to write to token source") = Some(token_source);
242        *self.revision.write().expect("Failed to write to revision") = revision;
243        self.load_model_from_path(
244            &paths?,
245            dtype,
246            device,
247            silent,
248            mapper,
249            in_situ_quant,
250            paged_attn_config,
251        )
252    }
253
254    #[allow(clippy::type_complexity, clippy::too_many_arguments)]
255    fn load_model_from_path(
256        &self,
257        paths: &Box<dyn ModelPaths>,
258        dtype: &dyn TryIntoDType,
259        device: &Device,
260        silent: bool,
261        mut mapper: DeviceMapSetting,
262        in_situ_quant: Option<IsqType>,
263        mut paged_attn_config: Option<PagedAttentionConfig>,
264    ) -> Result<Arc<Mutex<dyn Pipeline + Send + Sync>>> {
265        let _progress_guard = ProgressScopeGuard::new(silent);
266        let config = std::fs::read_to_string(paths.get_config_filename())?;
267
268        if !self.inner.supports_paged_attention(&config) {
269            paged_attn_config = None;
270        }
271
272        info!("Prompt chunk size is {ATTENTION_CHUNK_SIZE}.");
273
274        let use_nccl = mistralrs_quant::distributed::use_nccl();
275
276        let available_devices = if let Ok(payload) = env::var(distributed::IS_DAEMON_FLAG) {
277            let payload: WorkerTransferData = serde_json::from_str(&payload)?;
278            let WorkerTransferData::Init { id: _, worker_rank } = payload;
279            vec![candle_core::Device::new_cuda_with_stream(worker_rank + 1)?]
280        } else if use_nccl {
281            vec![candle_core::Device::new_cuda_with_stream(0)?]
282        } else {
283            device_map::get_all_similar_devices(device)?
284        };
285        #[cfg(feature = "cuda")]
286        for device in &available_devices {
287            if let Device::Cuda(dev) = device {
288                unsafe { dev.disable_event_tracking() };
289            }
290        }
291        let device = if use_nccl {
292            available_devices[0].clone()
293        } else {
294            device.clone()
295        };
296
297        // Load matformer slicing config if provided
298        let matformer_slicing_config = if let Some(matformer_path) =
299            &self.config.matformer_config_path
300        {
301            use crate::matformer::{MatformerConfig, MatformerSliceConfig};
302            info!("Loading Matformer config from {:?}", matformer_path);
303            let config = Arc::new(MatformerConfig::from_file(matformer_path)?);
304
305            if let Some(slice_name) = &self.config.matformer_slice_name {
306                info!("Using Matformer slice: {}", slice_name);
307                Some(MatformerSliceConfig::new(slice_name.clone(), config))
308            } else {
309                // If no slice name is provided but config exists, we'll need to handle this
310                // For now, return None and let the model handle the default slice selection
311                warn!("Matformer config loaded but no slice name specified. Models will use their default slice.");
312                None
313            }
314        } else {
315            None
316        };
317
318        // If auto, convert to Map if not using nccl
319        if use_nccl {
320            mapper = DeviceMapSetting::DummyNccl {
321                nm_device: available_devices[0].clone(),
322            };
323        } else if let DeviceMapSetting::Auto(mut params) = mapper.clone() {
324            // We can promote to vision params if we get text params
325            params = params.maybe_promote_to_vision();
326
327            // Initial dtype
328            let dtype = dtype.try_into_dtype(&available_devices.iter().collect::<Vec<_>>())?;
329
330            // ISQ or UQFF: quantized path
331            // Match logic below where UQFF has priority
332            let (layer_sizes_in_bytes, non_mapped_size_in_bytes, total_model_size_in_bytes) =
333                if let Some(serialized) = &*self.from_uqff.read().unwrap() {
334                    let weight_pack_factor = {
335                        let ser_artifacts = unsafe {
336                            candle_core::safetensors::MmapedSafetensors::multi(serialized)?
337                        };
338                        let mut total_pack_factors = 0;
339                        let total_tensors = ser_artifacts.tensors().len();
340                        for (_, artifact) in ser_artifacts.tensors() {
341                            let artifact = artifact.data();
342                            // NOTE(EricLBuehler): isq type is ALWAYS byte 4 (5th) of the tensor.
343                            let isq_type = artifact[mistralrs_quant::UQFF_QUANT_TYPE_OFFSET];
344                            let pack_factor = match QuantizedSerdeType::try_from(isq_type as usize)?
345                            {
346                                QuantizedSerdeType::Hqq => {
347                                    HqqLayer::get_isq_type_from_uqff(Cow::Borrowed(artifact))?
348                                        .pack_factor(dtype)
349                                }
350                                QuantizedSerdeType::Gguf => {
351                                    GgufMatMul::get_isq_type_from_uqff(Cow::Borrowed(artifact))?
352                                        .pack_factor(dtype)
353                                }
354                                QuantizedSerdeType::Fp8 => IsqType::F8E4M3.pack_factor(dtype),
355                                QuantizedSerdeType::Unquant => 1,
356                                QuantizedSerdeType::Afq => {
357                                    AfqLayer::get_isq_type_from_uqff(Cow::Borrowed(artifact))?
358                                        .pack_factor(dtype)
359                                }
360                            };
361                            total_pack_factors += pack_factor;
362                        }
363
364                        total_pack_factors / total_tensors
365                    };
366
367                    let layer_sizes_in_bytes = self.inner.layer_sizes_in_bytes(
368                        &config,
369                        dtype,
370                        weight_pack_factor,
371                        matformer_slicing_config.as_ref(),
372                    )?;
373                    let non_mapped_size_in_bytes = self.inner.non_mapped_size_in_bytes(
374                        &config,
375                        dtype,
376                        weight_pack_factor,
377                        matformer_slicing_config.as_ref(),
378                    )?;
379                    let layer_sizes_sum = layer_sizes_in_bytes.iter().sum::<usize>();
380                    (
381                        layer_sizes_in_bytes,
382                        non_mapped_size_in_bytes,
383                        layer_sizes_sum + non_mapped_size_in_bytes,
384                    )
385                } else if let Some(isq) = in_situ_quant {
386                    let weight_pack_factor = isq.pack_factor(dtype);
387                    let layer_sizes_in_bytes = self.inner.layer_sizes_in_bytes(
388                        &config,
389                        dtype,
390                        weight_pack_factor,
391                        matformer_slicing_config.as_ref(),
392                    )?;
393                    let non_mapped_size_in_bytes = self.inner.non_mapped_size_in_bytes(
394                        &config,
395                        dtype,
396                        weight_pack_factor,
397                        matformer_slicing_config.as_ref(),
398                    )?;
399                    let layer_sizes_sum = layer_sizes_in_bytes.iter().sum::<usize>();
400                    (
401                        layer_sizes_in_bytes,
402                        non_mapped_size_in_bytes,
403                        layer_sizes_sum + non_mapped_size_in_bytes,
404                    )
405                } else {
406                    // Be sure to get the weight pack factor here; we might be loading a prequantized model.
407                    let weight_pack_factor =
408                        QuantizationConfigShim::get_quant_config_pack_factor(&config, dtype)?;
409                    let layer_sizes_in_bytes = self.inner.layer_sizes_in_bytes(
410                        &config,
411                        dtype,
412                        weight_pack_factor,
413                        matformer_slicing_config.as_ref(),
414                    )?;
415                    let non_mapped_size_in_bytes = self.inner.non_mapped_size_in_bytes(
416                        &config,
417                        dtype,
418                        weight_pack_factor,
419                        matformer_slicing_config.as_ref(),
420                    )?;
421                    let layer_sizes_sum = layer_sizes_in_bytes.iter().sum::<usize>();
422                    (
423                        layer_sizes_in_bytes,
424                        non_mapped_size_in_bytes,
425                        layer_sizes_sum + non_mapped_size_in_bytes,
426                    )
427                };
428
429            let new = auto_device_map::get_device_layers(
430                &*self.inner,
431                &config,
432                self.inner.num_layers(&config)?,
433                layer_sizes_in_bytes,
434                non_mapped_size_in_bytes,
435                total_model_size_in_bytes,
436                &available_devices,
437                dtype,
438                &params,
439                paged_attn_config.as_ref(),
440            )?;
441            mapper = DeviceMapSetting::Map(new);
442        }
443
444        let pipeline_mapper = mapper.into_mapper(
445            self.inner.num_layers(&config)?,
446            &device,
447            self.config.topology.as_ref(),
448        )?;
449        let mapper = mapper.into_mapper(
450            self.inner.num_layers(&config)?,
451            &device,
452            self.config.topology.as_ref(),
453        )?;
454        let mut layer_devices = Vec::new();
455        for layer in 0..self.inner.num_layers(&config)? {
456            let device = mapper.device_for(layer, false).cloned();
457            layer_devices.push(device);
458        }
459        let dtype = mapper.get_min_dtype(dtype)?;
460
461        // TODO: PagedAttention is not supported with CPU for now.
462        // This check is not really necessary because `get_device_layers` should prevent it.
463        let mapping_uses_cpu = mapper.get_unique_devices().iter().any(Device::is_cpu);
464        if mapping_uses_cpu && paged_attn_config.is_some() {
465            warn!("Device mapping contains a mix of GPU and CPU. There is no CPU support for PagedAttention, disabling PagedAttention.");
466            paged_attn_config = None;
467        }
468
469        info!("Model config: {:?}", self.inner.get_config_repr(&config)?);
470        if crate::using_flash_attn() {
471            once_log_info("FlashAttention is enabled.");
472        }
473
474        let topology_overrides = self
475            .config
476            .topology
477            .as_ref()
478            .map(|topology| {
479                topology
480                    .pattern_overrides()
481                    .into_iter()
482                    .map(|(regex, layer)| ImmediateIsqOverride {
483                        predicate: regex,
484                        ty: layer.isq,
485                        device: layer.device.clone(),
486                    })
487                    .collect::<Vec<_>>()
488            })
489            .unwrap_or_default();
490        let has_override_isq = topology_overrides
491            .iter()
492            .any(|override_entry| override_entry.ty.is_some());
493        let topology_requires_post_quant = self
494            .config
495            .topology
496            .as_ref()
497            .is_some_and(|topology| topology.requires_post_quantization());
498
499        let allow_immediate_cli = self.config.imatrix.is_none()
500            && self.config.calibration_file.is_none()
501            && !device.is_cuda()
502            && in_situ_quant.is_some();
503
504        let mut immediate_ty = None;
505        let mut immediate_predicates = Vec::new();
506        if allow_immediate_cli {
507            immediate_ty = in_situ_quant;
508            immediate_predicates = self.inner.immediate_isq_predicates(&config)?;
509            info!("Applying ISQ to {in_situ_quant:?}");
510            if immediate_predicates.is_empty() {
511                warn!("No predicates for this model and ISQ setting detected. ISQ will not be applied to any weights!");
512            }
513        }
514
515        let use_immediate = allow_immediate_cli || has_override_isq;
516        if use_immediate {
517            mistralrs_quant::set_immediate_isq_with_overrides(
518                immediate_ty,
519                immediate_predicates.clone(),
520                topology_overrides.clone(),
521            );
522        }
523
524        // Logic for ISQ here: if no calibration (i.e imatrix), then allow immediate ISQ. Otherwise, back to normal.
525        let mut loading_isq = if use_immediate {
526            false
527        } else {
528            in_situ_quant.is_some()
529        };
530        if self.config.imatrix.is_some() || self.config.calibration_file.is_some() {
531            loading_isq = true;
532        }
533        loading_isq |= topology_requires_post_quant;
534
535        if self.config.imatrix.is_some() && self.config.calibration_file.is_some() {
536            anyhow::bail!(
537                "`imatrix` and `calibration_file` were both specified, this is not allowed."
538            );
539        }
540
541        // Load onto the regular device if not using isq or if the calibration file is specified
542        let load_device = if !loading_isq || self.config.calibration_file.is_some() {
543            loading_isq = false;
544            device.clone()
545        } else {
546            Device::Cpu
547        };
548
549        let attention_mechanism = if paged_attn_config.is_some() {
550            AttentionImplementation::PagedAttention
551        } else {
552            AttentionImplementation::Eager
553        };
554
555        let multi_progress = Arc::new(new_multi_progress());
556
557        let mut model = if use_nccl {
558            let (mapper, sharded_vb) = distributed::prepare_distributed_mapper(
559                dtype,
560                &device,
561                &available_devices,
562                silent,
563                &config,
564                loading_isq,
565                self.config.from_uqff.is_some(),
566                IsqOrganization::Default,
567                &*self.inner,
568                paths.as_ref(),
569            )?;
570
571            // Special case for where things can be more optimially loaded.
572            match self.kind {
573                ModelKind::Normal => vision_normal_model_loader_sharded!(
574                    sharded_vb,
575                    config,
576                    self.inner,
577                    mapper,
578                    loading_isq,
579                    device.clone(),
580                    attention_mechanism,
581                    multi_progress.clone(),
582                    matformer_slicing_config.clone(),
583                ),
584                _ => unreachable!(),
585            }
586        } else {
587            match self.kind {
588                ModelKind::Normal => vision_normal_model_loader!(
589                    paths,
590                    Some(dtype),
591                    &load_device,
592                    layer_devices.clone(),
593                    config,
594                    self.inner,
595                    silent,
596                    mapper,
597                    loading_isq,
598                    self.config.from_uqff.is_some(),
599                    device.clone(),
600                    attention_mechanism,
601                    multi_progress,
602                    matformer_slicing_config.clone(),
603                ),
604                _ => unreachable!(),
605            }
606        };
607
608        // Handle the Gemma 3 1b case here
609        let preprocessor_config: PreProcessorConfig = match paths.get_preprocessor_config().as_ref()
610        {
611            Some(preprocessor_config) => {
612                serde_json::from_str(&fs::read_to_string(preprocessor_config).unwrap()).unwrap()
613            }
614            None => PreProcessorConfig::default(),
615        };
616        let processor_config: Option<ProcessorConfig> = paths
617            .get_processor_config()
618            .as_ref()
619            .map(|f| serde_json::from_str(&fs::read_to_string(f).unwrap()).unwrap());
620
621        let processor = self.inner.get_processor(
622            &config,
623            processor_config,
624            preprocessor_config.clone(),
625            self.config.max_edge,
626        ); //There are always some repos that don't properly handle config position, for example... LLaVA
627
628        let tokenizer = get_tokenizer(
629            paths.get_tokenizer_filename(),
630            Some(processor.get_special_tokens()),
631        )?;
632
633        let gen_conf: Option<GenerationConfig> = paths
634            .get_gen_conf_filename()
635            .map(|f| serde_json::from_str(&fs::read_to_string(f).unwrap()).unwrap());
636        let chat_template_explicit = paths
637            .get_chat_template_explicit()
638            .as_ref()
639            .map(|x| x.to_string_lossy().to_string());
640        let chat_template = get_chat_template(
641            paths,
642            self.jinja_explicit.as_ref(),
643            chat_template_explicit.as_ref(),
644            self.chat_template.as_ref(),
645            None,
646        );
647
648        if let Some(calibration_file) = &self.config.calibration_file {
649            let calibration_data = std::fs::read_to_string(calibration_file)?;
650            // Tokenize, don't add bos yet
651            let tokens = tokenizer
652                .encode_fast(calibration_data, false)
653                .map_err(anyhow::Error::msg)?
654                .get_ids()
655                .to_vec();
656            info!(
657                "Collecting imatrix from calibration file `{}` of {} tokens.",
658                calibration_file.display(),
659                tokens.len()
660            );
661            let bos_toks = chat_template.bos_tok().map(|b| vec![b]).unwrap_or_default();
662            let bos_tok_id = tokenizer
663                .token_to_id(&bos_toks[0])
664                .expect("Somehow the bos token is not present.");
665
666            // NOTE: We ONLY calibrate the text bits of these models!!
667            // So only those should be tracked!
668            model.begin_track_stats()?;
669
670            const CHUNK_SIZE: usize = 1024;
671            let n_chunks: usize = tokens.len().div_ceil(CHUNK_SIZE);
672            let start = Instant::now();
673            for (i, chunk) in tokens.chunks(CHUNK_SIZE).enumerate() {
674                let chunk = [vec![bos_tok_id], chunk.to_vec()].concat();
675                let chunk_len = chunk.len();
676
677                let start = Instant::now();
678                let inputs = make_prompt_chunk(
679                    0,
680                    vec![&chunk],
681                    &[0],
682                    &load_device,
683                    None,
684                    false,
685                    None,
686                    None,
687                )?;
688                let _ = model.forward(
689                    &inputs.input,
690                    None, // NOTE: We ONLY calibrate the text bits of these models!!
691                    &inputs.positions,
692                    inputs.context_lens,
693                    inputs.position_ids,
694                    model.default_model_specific_args(&inputs.input),
695                    None,
696                    &inputs.flash_meta,
697                )?;
698                match model.cache_mut() {
699                    EitherCache::Full(full) => {
700                        for layer in &mut *full.lock() {
701                            *layer = None
702                        }
703                    }
704                    EitherCache::Normal(normal) => {
705                        for layer in &mut *normal.lock().unwrap().0 {
706                            layer.reset();
707                        }
708                    }
709                    EitherCache::Hybrid(hybrid) => {
710                        hybrid.lock().unwrap().reset();
711                    }
712                }
713                let end = Instant::now();
714                info!(
715                    "Processed chunk {}/{n_chunks} ({chunk_len} tokens), {:.2}s",
716                    i + 1,
717                    end.duration_since(start).as_secs_f32()
718                );
719            }
720            load_device.synchronize()?;
721            let end = Instant::now();
722            info!(
723                "Finished collecting imatrix in {:.2}s",
724                end.duration_since(start).as_secs_f32()
725            );
726        }
727
728        let should_serialize = self.config.write_uqff.is_some();
729        let should_quantize_pass = loading_isq;
730
731        if (should_quantize_pass || should_serialize) && self.config.from_uqff.is_none() {
732            let imatrix_source = if should_quantize_pass {
733                match (
734                    self.config.imatrix.as_ref(),
735                    self.config.calibration_file.is_some(),
736                ) {
737                    (None, false) => None,
738                    (Some(file), false) => Some(ImatrixDataSource::File(file)),
739                    (None, true) => Some(ImatrixDataSource::Collected),
740                    (Some(_), true) => unreachable!(),
741                }
742            } else {
743                None
744            };
745            if should_quantize_pass {
746                info!("Applying ISQ to all ranks.");
747            } else {
748                info!("Serializing existing ISQ tensors without additional quantization.");
749            }
750            model.quantize(
751                in_situ_quant,
752                device.clone(),
753                self.config.topology.as_ref(),
754                silent,
755                imatrix_source,
756                IsqOrganization::Default,
757                should_quantize_pass,
758                self.config.write_uqff.as_ref(),
759                UqffFullSer {
760                    tokenizer: &tokenizer,
761                    template_filename: paths.get_template_filename(),
762                    generation_config: paths.get_gen_conf_filename(),
763                    config: config.clone(),
764                    processor_filename: paths.get_processor_config(),
765                    preprocessor_filename: paths.get_preprocessor_config(),
766                    modules: None,
767                    module_paths: None,
768                },
769                Arc::new(new_multi_progress()),
770            )?;
771        } else if let Some(from_uqff) = &*self.from_uqff.read().unwrap() {
772            model.load_from_artifacts(
773                device.clone(),
774                self.config.topology.as_ref(),
775                silent,
776                from_uqff,
777            )?;
778        }
779
780        let (cache_config, cache_engine) = if let Some(paged_attn_config) = paged_attn_config {
781            anyhow::ensure!(
782                !matches!(self.kind, ModelKind::Adapter { .. }),
783                "PagedAttention does not support adapter models."
784            );
785            let cache_config = calculate_cache_config(
786                paged_attn_config.mem_gpu,
787                paged_attn_config.block_size,
788                dtype,
789                paged_attn_config.cache_type,
790                model.config(),
791                &device,
792                &layer_devices,
793                silent,
794            )?;
795            let cache_engine =
796                CacheEngine::new(model.config(), &cache_config, dtype, &device, layer_devices)?;
797            (Some(cache_config), Some(cache_engine))
798        } else {
799            (None, None)
800        };
801
802        let max_seq_len = model.max_seq_len();
803        let llg_factory = build_llg_factory(tokenizer.clone())?;
804        let num_hidden_layers = match model.cache() {
805            EitherCache::Full(full) => full.lock().len(),
806            EitherCache::Normal(normal) => normal.lock().unwrap().0.len(),
807            EitherCache::Hybrid(hybrid) => hybrid.lock().unwrap().num_layers(),
808        };
809        let eos = calculate_eos_tokens(&chat_template, gen_conf, &tokenizer);
810        let sliding_window = model.config().sliding_window;
811        let model_metadata = Arc::new(model.config().clone());
812        Ok(Arc::new(Mutex::new(VisionPipeline {
813            model,
814            tokenizer: tokenizer.into(),
815            chat_template: Arc::new(chat_template),
816            model_id: self.model_id.clone(),
817            metadata: Arc::new(GeneralMetadata {
818                max_seq_len,
819                llg_factory: Some(llg_factory),
820                is_xlora: false,
821                num_hidden_layers,
822                eos_tok: eos,
823                kind: self.kind.clone(),
824                no_kv_cache: false,
825                no_prefix_cache: !self.inner.supports_prefix_cacher(&config),
826                activation_dtype: dtype,
827                sliding_window,
828                cache_config,
829                cache_engine,
830                model_metadata: Some(model_metadata),
831                modalities: self.inner.modalities(&config)?,
832            }),
833            processor,
834            prefixer: self.inner.prefixer(&config),
835            preprocessor_config: Arc::new(preprocessor_config),
836            topology: self.config.topology.clone(),
837            silent,
838            template_filename: paths.get_template_filename().clone(),
839            generation_config: paths.get_gen_conf_filename().cloned(),
840            config,
841            processor_filename: paths.get_processor_config().clone(),
842            preprocessor_filename: paths.get_preprocessor_config().clone(),
843            mapper: pipeline_mapper,
844            imatrix: self.config.imatrix.clone(),
845        })))
846    }
847
848    fn get_id(&self) -> String {
849        self.model_id.to_string()
850    }
851
852    fn get_kind(&self) -> ModelKind {
853        self.kind.clone()
854    }
855}
856
857impl PreProcessingMixin for VisionPipeline {
858    fn get_chat_template(&self) -> Option<Arc<ChatTemplate>> {
859        Some(self.chat_template.clone())
860    }
861    fn get_input_processor_config(&self) -> Option<Arc<dyn Any>> {
862        Some(self.preprocessor_config.clone())
863    }
864    fn get_processor(&self) -> Arc<dyn super::Processor> {
865        self.processor.clone()
866    }
867}
868
869impl IsqPipelineMixin for VisionPipeline {
870    fn re_isq_model(&mut self, dtype: IsqType) -> Result<()> {
871        let device = self.device().clone();
872        self.model
873            .quantize(
874                Some(dtype),
875                device,
876                self.topology.as_ref(),
877                self.silent,
878                self.imatrix.as_ref().map(ImatrixDataSource::File),
879                IsqOrganization::Default,
880                true,
881                None,
882                UqffFullSer {
883                    tokenizer: &self.tokenizer,
884                    template_filename: &self.template_filename,
885                    generation_config: self.generation_config.as_ref(),
886                    config: self.config.clone(),
887                    processor_filename: &self.processor_filename,
888                    preprocessor_filename: &self.preprocessor_filename,
889                    modules: None,
890                    module_paths: None,
891                },
892                Arc::new(new_multi_progress()),
893            )
894            .map_err(anyhow::Error::msg)
895    }
896}
897
898impl CacheManagerMixin for VisionPipeline {
899    fn clone_in_cache(&self, seqs: &mut [&mut Sequence]) {
900        if matches!(self.model.cache(), EitherCache::Full(_)) {
901            FullCacheManager.clone_in_cache(self, seqs, false)
902        } else {
903            NormalCacheManager.clone_in_cache(self, seqs, false)
904        }
905    }
906    fn clone_out_cache(&self, seqs: &mut [&mut Sequence]) {
907        if matches!(self.model.cache(), EitherCache::Full(_)) {
908            FullCacheManager.clone_out_cache(self, seqs, false)
909        } else {
910            NormalCacheManager.clone_out_cache(self, seqs, false)
911        }
912    }
913    fn set_none_cache(
914        &self,
915        seqs: &mut [&mut Sequence],
916        reset_non_granular: bool,
917        modify_draft_cache: bool,
918
919        load_preallocated_cache: bool,
920    ) {
921        if matches!(self.model.cache(), EitherCache::Full(_)) {
922            FullCacheManager.set_none_cache(self, seqs, modify_draft_cache, false);
923        } else {
924            NormalCacheManager.set_none_cache(
925                self,
926                seqs,
927                modify_draft_cache,
928                load_preallocated_cache,
929            );
930        }
931        if reset_non_granular {
932            self.reset_non_granular_state()
933        }
934    }
935    fn cache(&self) -> &EitherCache {
936        self.model.cache()
937    }
938}
939
940impl MetadataMixin for VisionPipeline {
941    fn device(&self) -> Device {
942        self.model.device().clone()
943    }
944    fn get_metadata(&self) -> Arc<GeneralMetadata> {
945        self.metadata.clone()
946    }
947    fn name(&self) -> String {
948        self.model_id.clone()
949    }
950    fn reset_non_granular_state(&self) {}
951    fn tokenizer(&self) -> Option<Arc<Tokenizer>> {
952        Some(self.tokenizer.clone())
953    }
954    fn device_mapper(&self) -> Option<&dyn DeviceMapper> {
955        Some(&*self.mapper)
956    }
957}
958
959#[async_trait::async_trait]
960impl Pipeline for VisionPipeline {
961    fn forward_inputs(
962        &mut self,
963        inputs: Box<dyn Any>,
964        return_raw_logits: bool,
965    ) -> candle_core::Result<ForwardInputsResult> {
966        let ModelInputs {
967            input_ids,
968            seqlen_offsets,
969            context_lens,
970            position_ids,
971            pixel_values,
972            model_specific_args,
973            paged_attn_meta,
974            flash_meta,
975        } = *inputs.downcast::<ModelInputs>().expect("Downcast failed.");
976        let metadata = self.get_metadata();
977        let paged_attn_meta = match (&metadata.cache_engine, &paged_attn_meta) {
978            (Some(engine), Some(meta)) => Some((engine.get_kv_cache().clone(), meta)),
979            (Some(_), None) => {
980                // This can happen if Rust-side user code is wrong
981                candle_core::bail!("Forward step expected a PagedAttention input metadata. This was not provided, please ensure that the scheduler config is correctly configured for PagedAttention.")
982            }
983            (None, Some(_)) => {
984                // This should never happen but we handle it anyway
985                candle_core::bail!("Forward step got a PagedAttention input metadata but there is no cache engine. Please raise an issue.")
986            }
987            (None, None) => None,
988        };
989        let logits = self.model.forward(
990            &input_ids,
991            pixel_values,
992            &seqlen_offsets,
993            context_lens,
994            position_ids,
995            model_specific_args,
996            paged_attn_meta,
997            &flash_meta,
998        )?;
999        if return_raw_logits {
1000            Ok(ForwardInputsResult::RawLogits { logits })
1001        } else {
1002            Ok(ForwardInputsResult::CausalGeneration { logits })
1003        }
1004    }
1005    async fn sample_causal_gen(
1006        &self,
1007        seqs: &mut [&mut Sequence],
1008        logits: Vec<Tensor>,
1009        prefix_cacher: &mut PrefixCacheManagerV2,
1010        disable_eos_stop: bool,
1011        rng: Arc<std::sync::Mutex<Isaac64Rng>>,
1012    ) -> Result<(), candle_core::Error> {
1013        sample_and_add_toks(self, seqs, logits, prefix_cacher, disable_eos_stop, rng).await
1014    }
1015    fn category(&self) -> ModelCategory {
1016        ModelCategory::Vision {
1017            prefixer: self.prefixer.clone(),
1018        }
1019    }
1020}
1021
1022impl AnyMoePipelineMixin for VisionPipeline {
1023    fn amoe_finish_training(&mut self, gate_model_id: Option<String>) -> candle_core::Result<()> {
1024        self.model.finish_training(gate_model_id)
1025    }
1026    fn amoe_layer_vars(&self) -> Vec<Vec<Var>> {
1027        self.model.get_vars()
1028    }
1029    fn amoe_base_model_trainable_params(&self) -> usize {
1030        self.model.trainable_params()
1031    }
1032    fn amoe_take_cached_gating_outputs(&mut self) -> Vec<Tensor> {
1033        self.model.take_cached_gating_outputs()
1034    }
1035    fn amoe_create_layers(
1036        &mut self,
1037        model_ids: Vec<String>,
1038        token: &TokenSource,
1039        revision: Option<String>,
1040        match_regex: &str,
1041        config: crate::amoe::AnyMoeConfig,
1042        dtype: candle_core::DType,
1043        dev: &Device,
1044        (prefix, mlp): (String, String),
1045        layers: Vec<usize>,
1046        expert_type: AnyMoeExpertType,
1047        silent: bool,
1048        gate_model_id: Option<String>,
1049    ) -> candle_core::Result<()> {
1050        let mut vbs = Vec::new();
1051        // Precompile regex here
1052        let regex = Regex::new(match_regex).map_err(candle_core::Error::msg)?;
1053        for model_id in model_ids {
1054            let model_id_str = &model_id;
1055            let model_id = Path::new(&model_id);
1056
1057            let api = {
1058                let cache = GLOBAL_HF_CACHE.get().cloned().unwrap_or_default();
1059                let mut api = ApiBuilder::from_cache(cache)
1060                    .with_progress(!silent)
1061                    .with_token(get_token(token).map_err(candle_core::Error::msg)?);
1062                if let Ok(x) = std::env::var("HF_HUB_CACHE") {
1063                    api = api.with_cache_dir(x.into());
1064                }
1065                api.build().map_err(candle_core::Error::msg)?
1066            };
1067            let revision = revision.clone().unwrap_or("main".to_string());
1068            let api = api.repo(Repo::with_revision(
1069                model_id_str.clone(),
1070                RepoType::Model,
1071                revision.clone(),
1072            ));
1073
1074            let mut filenames = vec![];
1075            for rfilename in
1076                api_dir_list!(api, model_id, true).filter(|x| x.ends_with(".safetensors"))
1077            {
1078                filenames.push(api_get_file!(api, &rfilename, model_id));
1079            }
1080
1081            let regex = regex.clone();
1082            let match_regex_clone = match_regex.to_string();
1083            let layers_clone = layers.clone();
1084            let vb = from_mmaped_safetensors(
1085                filenames,
1086                vec![],
1087                Some(dtype),
1088                dev,
1089                vec![None],
1090                silent,
1091                None,
1092                move |key| {
1093                    if regex.is_match(&key) {
1094                        // Idx of the last char of the layer id, +1
1095                        // Assumes N.MLP
1096                        let last_layer_idx = key.find(&match_regex_clone).unwrap() - 1;
1097                        let first_layer_idx = key[..last_layer_idx].rfind('.').unwrap();
1098                        let layer_n = key[first_layer_idx + 1..last_layer_idx]
1099                            .parse::<usize>()
1100                            .unwrap();
1101                        layers_clone.contains(&layer_n) || layers_clone.is_empty()
1102                    } else {
1103                        false
1104                    }
1105                },
1106                Arc::new(|_| DeviceForLoadTensor::Base),
1107            )?;
1108            vbs.push(vb);
1109        }
1110
1111        let gate_vb = if let Some(gate_model_id) = gate_model_id {
1112            let model_id_str = &gate_model_id;
1113            let model_id = Path::new(&gate_model_id);
1114
1115            let api = {
1116                let cache = GLOBAL_HF_CACHE.get().cloned().unwrap_or_default();
1117                let mut api = ApiBuilder::from_cache(cache)
1118                    .with_progress(!silent)
1119                    .with_token(get_token(token).map_err(candle_core::Error::msg)?);
1120                if let Ok(x) = std::env::var("HF_HUB_CACHE") {
1121                    api = api.with_cache_dir(x.into());
1122                }
1123                api.build().map_err(candle_core::Error::msg)?
1124            };
1125            let revision = revision.clone().unwrap_or("main".to_string());
1126            let api = api.repo(Repo::with_revision(
1127                model_id_str.clone(),
1128                RepoType::Model,
1129                revision.clone(),
1130            ));
1131
1132            let mut gate_filenames = vec![];
1133            for rfilename in
1134                api_dir_list!(api, model_id, true).filter(|x| x.ends_with(".safetensors"))
1135            {
1136                gate_filenames.push(api_get_file!(api, &rfilename, model_id));
1137            }
1138            assert_eq!(
1139                gate_filenames.len(),
1140                1,
1141                "Gate model ID must contain only one .safetensors file"
1142            );
1143
1144            let vb = from_mmaped_safetensors(
1145                gate_filenames.clone(),
1146                vec![],
1147                Some(dtype),
1148                dev,
1149                vec![None],
1150                silent,
1151                None,
1152                |_| true,
1153                Arc::new(|_| DeviceForLoadTensor::Base),
1154            )?;
1155            info!(
1156                "Loaded gating layers from `{}`",
1157                gate_filenames[0].display()
1158            );
1159            Some(vb)
1160        } else {
1161            None
1162        };
1163
1164        self.model
1165            .create_anymoe_layers(vbs, config, (prefix, mlp), layers, expert_type, gate_vb)
1166    }
1167    fn amoe_supported(&self) -> bool {
1168        self.model.amoe_supported()
1169    }
1170}