mistralrs_core/pipeline/loaders/
auto_device_map.rs

1use std::fmt::{self, Display};
2
3use crate::paged_attention::{
4    calculate_cache_config, ModelConfigLike, DEFAULT_PAGED_ATTENTION_BLOCK_SIZE,
5};
6use crate::utils::debug::DeviceRepr;
7use crate::{DeviceLayerMapMetadata, DeviceMapMetadata, MemoryUsage, PagedAttentionConfig};
8use anyhow::{Context, Result};
9use candle_core::{DType, Device};
10use itertools::Itertools;
11use tracing::{info, warn};
12
13use super::DeviceMappedModelLoader;
14
15#[derive(Clone, Debug)]
16pub(crate) enum NonMappedSubModel {
17    Vision,
18    Audio,
19}
20
21impl Display for NonMappedSubModel {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            NonMappedSubModel::Vision => write!(f, "vision"),
25            NonMappedSubModel::Audio => write!(f, "audio"),
26        }
27    }
28}
29
30#[derive(Debug, Clone)]
31pub enum AutoDeviceMapParams {
32    Text {
33        max_seq_len: usize,
34        max_batch_size: usize,
35    },
36    Vision {
37        max_seq_len: usize,
38        max_batch_size: usize,
39        max_image_shape: (usize, usize),
40        max_num_images: usize,
41    },
42}
43
44impl AutoDeviceMapParams {
45    pub fn maybe_promote_to_vision(&self) -> Self {
46        match *self {
47            Self::Text {
48                max_seq_len,
49                max_batch_size,
50            } => Self::Vision {
51                max_seq_len,
52                max_batch_size,
53                max_image_shape: (
54                    Self::DEFAULT_MAX_IMAGE_LENGTH,
55                    Self::DEFAULT_MAX_IMAGE_LENGTH,
56                ),
57                max_num_images: Self::DEFAULT_MAX_NUM_IMAGES,
58            },
59            Self::Vision {
60                max_seq_len,
61                max_batch_size,
62                max_image_shape,
63                max_num_images,
64            } => Self::Vision {
65                max_seq_len,
66                max_batch_size,
67                max_image_shape,
68                max_num_images,
69            },
70        }
71    }
72
73    pub fn max_seq_len(&self) -> usize {
74        match self {
75            Self::Text { max_seq_len, .. } | Self::Vision { max_seq_len, .. } => *max_seq_len,
76        }
77    }
78}
79
80impl Display for AutoDeviceMapParams {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        match self {
83            Self::Text {
84                max_seq_len,
85                max_batch_size,
86            } => write!(
87                f,
88                "text[max_seq_len: {max_seq_len}, max_batch_size: {max_batch_size}]"
89            ),
90            Self::Vision {
91                max_seq_len,
92                max_batch_size,
93                max_image_shape,
94                max_num_images,
95            } => write!(
96                f,
97                "vision[max_seq_len: {max_seq_len}, max_batch_size: {max_batch_size}, max_image_shape: {max_image_shape:?}, max_num_images: {max_num_images}]"
98            ),
99        }
100    }
101}
102
103impl AutoDeviceMapParams {
104    // Default max sequence length for memory estimation when not specified
105    pub const DEFAULT_MAX_SEQ_LEN: usize = 4 * 1024;
106    pub const DEFAULT_MAX_BATCH_SIZE: usize = 1;
107    pub const DEFAULT_MAX_NUM_IMAGES: usize = 1;
108    pub const DEFAULT_MAX_IMAGE_LENGTH: usize = 1024;
109
110    pub fn default_text() -> Self {
111        Self::Text {
112            max_seq_len: Self::DEFAULT_MAX_SEQ_LEN,
113            max_batch_size: Self::DEFAULT_MAX_BATCH_SIZE,
114        }
115    }
116
117    pub fn default_vision() -> Self {
118        Self::Vision {
119            max_seq_len: Self::DEFAULT_MAX_SEQ_LEN,
120            max_batch_size: Self::DEFAULT_MAX_BATCH_SIZE,
121            max_num_images: Self::DEFAULT_MAX_NUM_IMAGES,
122            max_image_shape: (
123                Self::DEFAULT_MAX_IMAGE_LENGTH,
124                Self::DEFAULT_MAX_IMAGE_LENGTH,
125            ),
126        }
127    }
128}
129
130fn calculate_key_block_shape(
131    model_config: &dyn ModelConfigLike,
132    dtype: DType,
133    block_size: usize,
134) -> (usize, usize, usize, usize) {
135    let element_size = dtype.size_in_bytes();
136    let x = 16 / element_size;
137    (
138        model_config.num_kv_heads(),
139        model_config.k_head_dim() / x,
140        block_size,
141        x,
142    )
143}
144
145fn calculate_value_block_shape(
146    model_config: &dyn ModelConfigLike,
147    block_size: usize,
148) -> (usize, usize, usize) {
149    (
150        model_config.num_kv_heads(),
151        model_config.v_head_dim(),
152        block_size,
153    )
154}
155
156macro_rules! b_to_mb {
157    ($x:expr) => {
158        $x / (1024 * 1024)
159    };
160}
161
162#[allow(clippy::too_many_arguments)]
163/// Core logic for automatic device mapping
164pub fn get_device_layers(
165    loader: &dyn DeviceMappedModelLoader,
166    config: &str,
167    num_layers: usize,
168    mut layer_sizes_in_bytes: Vec<usize>,
169    non_mapped_size_in_bytes: usize,
170    total_model_size_in_bytes: usize,
171    devices: &[Device],
172    dtype: DType,
173    params: &AutoDeviceMapParams,
174    paged_attn_config: Option<&PagedAttentionConfig>,
175) -> Result<DeviceMapMetadata> {
176    let mapped_max = loader.mapped_max_act_size_elems(config, params)? * dtype.size_in_bytes();
177    let non_mapped_max =
178        loader.non_mapped_max_act_size_elems(config, params)? * dtype.size_in_bytes();
179
180    let mut remaining = total_model_size_in_bytes;
181    let max_seq_len = match params {
182        AutoDeviceMapParams::Text { max_seq_len, .. }
183        | AutoDeviceMapParams::Vision { max_seq_len, .. } => *max_seq_len,
184    };
185    let max_batch_size = match params {
186        AutoDeviceMapParams::Text { max_batch_size, .. }
187        | AutoDeviceMapParams::Vision { max_batch_size, .. } => *max_batch_size,
188    };
189
190    let model_cfg = loader.model_config(config)?;
191    let kv_cache_elems = match paged_attn_config {
192        Some(cfg) => {
193            let cache = calculate_cache_config(
194                cfg.mem_gpu,
195                cfg.mem_cpu,
196                Some(cfg.block_size.unwrap_or(DEFAULT_PAGED_ATTENTION_BLOCK_SIZE)),
197                dtype,
198                paged_attn_config
199                    .map(|cfg| cfg.cache_type)
200                    .unwrap_or_default(),
201                &*model_cfg,
202                &devices[0],
203                &devices.iter().map(|d| Some(d.clone())).collect::<Vec<_>>(),
204                true,
205            )?;
206            let key_shape = calculate_key_block_shape(&*model_cfg, dtype, cache.block_size);
207            let key_sz =
208                cache.num_gpu_blocks * key_shape.0 * key_shape.1 * key_shape.2 * key_shape.3;
209            let val_shape = calculate_value_block_shape(&*model_cfg, cache.block_size);
210            let val_sz = cache.num_gpu_blocks * val_shape.0 * val_shape.1 * val_shape.2;
211            key_sz + val_sz
212        }
213        None => {
214            let key_shape = [
215                max_batch_size,
216                model_cfg.num_kv_heads(),
217                max_seq_len,
218                model_cfg.k_head_dim(),
219            ];
220            let val_shape = [
221                max_batch_size,
222                model_cfg.num_kv_heads(),
223                max_seq_len,
224                model_cfg.v_head_dim(),
225            ];
226            key_shape.iter().product::<usize>() + val_shape.iter().product::<usize>()
227        }
228    };
229    let kv_cache_bytes = kv_cache_elems * dtype.size_in_bytes();
230
231    // prepare available memory per device, CPU fallback last
232    let mut avail = Vec::new();
233    for dev in [devices, &[Device::Cpu]].concat() {
234        let a = MemoryUsage.get_memory_available(&dev)?;
235        avail.push((a, dev));
236    }
237    avail.reverse();
238    layer_sizes_in_bytes.reverse();
239
240    let mut mappings = Vec::new();
241    info!("Using automatic device mapping parameters: {params}.");
242    if let Some(subs) = loader.non_mapped_sub_models() {
243        let (_, last) = avail.last().unwrap();
244        info!(
245            "The following sub-models will not be device mapped and will be loaded on {}: {}",
246            last.device_pretty_repr(),
247            subs.iter().map(|x| x.to_string()).join(", ")
248        );
249    }
250
251    let mut ordinal = 0;
252    let mut layer = 0;
253    let avail_copy = avail.clone();
254    let mut includes_cpu = false;
255    while remaining > 0 && !avail.is_empty() {
256        let (cap, dev) = avail
257            .pop()
258            .context("No more devices to map to. The model does not fit on this system.")?;
259
260        // All usage of 90% of the memory as a maximum.
261        #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
262        let cap = (cap as f64 * 0.90) as usize;
263
264        // Algorithm is to check the following:
265        // 1) (no mapping) if *everything* fits on the first dev (non mapped and mapped)
266        // 2) if the mapped activations plus remaining fits on the nth device
267        // 3) common case, iteratively find the optimal amount of layers to put on the nth device
268        //   - if this is the first dev: must hold the non-mapped act and non-mapped model
269        //   - otherwise, must hold the mapped act
270        let required_whole_capacity = if ordinal == 0 {
271            remaining
272                + non_mapped_max.max(mapped_max)
273                + non_mapped_size_in_bytes
274                + kv_cache_bytes * (num_layers - layer)
275        } else {
276            remaining + mapped_max + kv_cache_bytes * (num_layers - layer)
277        };
278
279        let layers_on_dev = if cap >= required_whole_capacity {
280            remaining = 0;
281            num_layers - layer
282        } else {
283            let mut used = mapped_max;
284            let mut used_no_act = 0;
285            let mut count = 0;
286            if ordinal == 0 {
287                used = used.max(non_mapped_max) + non_mapped_size_in_bytes;
288                used_no_act += non_mapped_size_in_bytes;
289            }
290            while let Some(&sz) = layer_sizes_in_bytes.last() {
291                let delta = sz + kv_cache_bytes;
292                if used + delta > cap {
293                    break;
294                }
295                layer_sizes_in_bytes.pop();
296                used += delta;
297                used_no_act += delta;
298                count += 1;
299            }
300            if count > 0 {
301                remaining = remaining.saturating_sub(used_no_act);
302            } else {
303                warn!(
304                    "Device {} can fit 0 layers. Consider reducing auto map params from current: {params} (ex. reducing max seq len or max num images)",
305                    dev.device_pretty_repr(),
306                );
307                ordinal += 1;
308                continue;
309            }
310            count
311        };
312        if !dev.is_cpu() {
313            mappings.push(DeviceLayerMapMetadata {
314                ordinal,
315                layers: layers_on_dev,
316            });
317            ordinal += 1;
318        } else {
319            includes_cpu = true;
320        }
321        layer += layers_on_dev;
322    }
323    if remaining > 0 {
324        let over = b_to_mb!(remaining);
325        anyhow::bail!(
326            "This model does not fit on the devices {:?}, and exceeds total capacity by {}MB. Auto device mapping params: {params}",
327            avail_copy.iter().rev().map(|(a, d)| format!("{} (avail: {}MB)", d.device_pretty_repr(), b_to_mb!(a))).collect::<Vec<_>>(),
328            over
329        );
330    }
331    if paged_attn_config.is_some_and(|_| includes_cpu) {
332        return get_device_layers(
333            loader,
334            config,
335            num_layers,
336            layer_sizes_in_bytes,
337            non_mapped_size_in_bytes,
338            total_model_size_in_bytes,
339            devices,
340            dtype,
341            params,
342            None,
343        );
344    }
345    Ok(DeviceMapMetadata::from_num_device_layers(mappings))
346}