mistralrs_core/toml_selector.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
use std::{fs::File, num::NonZeroUsize, path::PathBuf};
use serde::Deserialize;
use crate::{
amoe::AnyMoeConfig, pipeline::IsqOrganization, AnyMoeLoader, GGMLLoaderBuilder,
GGMLSpecificConfig, GGUFLoaderBuilder, GGUFSpecificConfig, Loader, ModelDType,
NormalLoaderBuilder, NormalLoaderType, NormalSpecificConfig, SpeculativeConfig,
SpeculativeLoader, Topology, VisionLoaderBuilder, VisionLoaderType, VisionSpecificConfig,
GGUF_MULTI_FILE_DELIMITER,
};
fn default_one() -> usize {
1
}
fn default_dtype() -> ModelDType {
ModelDType::Auto
}
fn default_empty_vec_usize() -> Vec<usize> {
Vec::new()
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum TomlModelSelected {
/// Select a plain model, without quantization or adapters
Plain {
/// Model ID to load from. This may be a HF hub repo or a local path.
model_id: String,
/// The architecture of the model.
arch: Option<NormalLoaderType>,
/// Model data type. Defaults to `auto`.
#[serde(default = "default_dtype")]
dtype: ModelDType,
/// Path to a topology YAML file.
topology: Option<String>,
/// ISQ organization: `default` or `moqe` (Mixture of Quantized Experts: https://arxiv.org/abs/2310.02410).
organization: Option<IsqOrganization>,
/// UQFF path to write to.
write_uqff: Option<PathBuf>,
/// UQFF path to load from. If provided, this takes precedence over applying ISQ.
from_uqff: Option<PathBuf>,
/// .imatrix file to enhance GGUF quantizations with.
/// Incompatible with `--imatrix/-i`
imatrix: Option<PathBuf>,
/// Generate and utilize an imatrix to enhance GGUF quantizations.
/// Incompatible with `--imatrix/-i`
calibration_file: Option<PathBuf>,
},
/// Select an X-LoRA architecture
XLora {
/// Force a base model ID to load from instead of using the ordering file. This may be a HF hub repo or a local path.
model_id: Option<String>,
/// Model ID to load X-LoRA from. This may be a HF hub repo or a local path.
xlora_model_id: String,
/// Ordering JSON file
order: String,
/// Index of completion tokens to generate scalings up until. If this is 1, then there will be one completion token generated before it is cached.
/// This makes the maximum running sequences 1.
tgt_non_granular_index: Option<usize>,
/// The architecture of the model.
arch: Option<NormalLoaderType>,
/// Model data type. Defaults to `auto`.
#[serde(default = "default_dtype")]
dtype: ModelDType,
/// Path to a topology YAML file.
topology: Option<String>,
/// UQFF path to write to.
write_uqff: Option<PathBuf>,
/// UQFF path to load from. If provided, this takes precedence over applying ISQ.
from_uqff: Option<PathBuf>,
},
/// Select a LoRA architecture
Lora {
/// Force a base model ID to load from instead of using the ordering file. This may be a HF hub repo or a local path.
model_id: Option<String>,
/// Model ID to load LoRA from. This may be a HF hub repo or a local path.
adapters_model_id: String,
/// Ordering JSON file
order: String,
/// The architecture of the model.
arch: Option<NormalLoaderType>,
/// Model data type. Defaults to `auto`.
#[serde(default = "default_dtype")]
dtype: ModelDType,
/// Path to a topology YAML file.
topology: Option<String>,
/// UQFF path to write to.
write_uqff: Option<PathBuf>,
/// UQFF path to load from. If provided, this takes precedence over applying ISQ.
from_uqff: Option<PathBuf>,
},
/// Select a GGUF model.
#[allow(clippy::upper_case_acronyms)]
GGUF {
/// `tok_model_id` is the local or remote model ID where you can find a `tokenizer_config.json` file.
/// If the `chat_template` is specified, then it will be treated as a path and used over remote files,
/// removing all remote accesses.
tok_model_id: String,
/// Quantized model ID to find the `quantized_filename`.
/// This may be a HF hub repo or a local path.
quantized_model_id: String,
/// Quantized filename(s).
/// May be a single filename, or use a delimiter of " " (a single space) for multiple files.
quantized_filename: String,
/// Path to a topology YAML file.
topology: Option<String>,
},
/// Select a GGUF model with X-LoRA.
XLoraGGUF {
/// `tok_model_id` is the local or remote model ID where you can find a `tokenizer_config.json` file.
/// If the `chat_template` is specified, then it will be treated as a path and used over remote files,
/// removing all remote accesses.
tok_model_id: Option<String>,
/// Quantized model ID to find the `quantized_filename`.
/// This may be a HF hub repo or a local path.
quantized_model_id: String,
/// Quantized filename(s).
/// May be a single filename, or use a delimiter of " " (a single space) for multiple files.
quantized_filename: String,
/// Model ID to load X-LoRA from. This may be a HF hub repo or a local path.
xlora_model_id: String,
/// Ordering JSON file
order: String,
/// Index of completion tokens to generate scalings up until. If this is 1, then there will be one completion token generated before it is cached.
/// This makes the maximum running sequences 1.
tgt_non_granular_index: Option<usize>,
/// Path to a topology YAML file.
topology: Option<String>,
},
/// Select a GGUF model with LoRA.
LoraGGUF {
/// `tok_model_id` is the local or remote model ID where you can find a `tokenizer_config.json` file.
/// If the `chat_template` is specified, then it will be treated as a path and used over remote files,
/// removing all remote accesses.
tok_model_id: Option<String>,
/// Quantized model ID to find the `quantized_filename`.
/// This may be a HF hub repo or a local path.
quantized_model_id: String,
/// Quantized filename(s).
/// May be a single filename, or use a delimiter of " " (a single space) for multiple files.
quantized_filename: String,
/// Model ID to load LoRA from. This may be a HF hub repo or a local path.
adapters_model_id: String,
/// Ordering JSON file
order: String,
/// Path to a topology YAML file.
topology: Option<String>,
},
/// Select a GGML model.
#[allow(clippy::upper_case_acronyms)]
GGML {
/// Model ID to load the tokenizer from. This may be a HF hub repo or a local path.
tok_model_id: String,
/// Quantized model ID to find the `quantized_filename`.
/// This may be a HF hub repo or a local path.
quantized_model_id: String,
/// Quantized filename.
quantized_filename: String,
/// GQA value
#[serde(default = "default_one")]
gqa: usize,
/// Path to a topology YAML file.
topology: Option<String>,
},
/// Select a GGML model with X-LoRA.
XLoraGGML {
/// Model ID to load the tokenizer from. This may be a HF hub repo or a local path.
tok_model_id: Option<String>,
/// Quantized model ID to find the `quantized_filename`.
/// This may be a HF hub repo or a local path.
quantized_model_id: String,
/// Quantized filename.
quantized_filename: String,
/// Model ID to load X-LoRA from. This may be a HF hub repo or a local path.
xlora_model_id: String,
/// Ordering JSON file
order: String,
/// Index of completion tokens to generate scalings up until. If this is 1, then there will be one completion token generated before it is cached.
/// This makes the maximum running sequences 1.
tgt_non_granular_index: Option<usize>,
/// GQA value
#[serde(default = "default_one")]
gqa: usize,
/// Path to a topology YAML file.
topology: Option<String>,
},
/// Select a GGML model with LoRA.
LoraGGML {
/// Model ID to load the tokenizer from. This may be a HF hub repo or a local path.
tok_model_id: Option<String>,
/// Quantized model ID to find the `quantized_filename`.
/// This may be a HF hub repo or a local path.
quantized_model_id: String,
/// Quantized filename.
quantized_filename: String,
/// Model ID to load LoRA from. This may be a HF hub repo or a local path.
adapters_model_id: String,
/// Ordering JSON file
order: String,
/// GQA value
#[serde(default = "default_one")]
gqa: usize,
/// Path to a topology YAML file.
topology: Option<String>,
},
/// Select a vision plain model, without quantization or adapters
VisionPlain {
/// Model ID to load from. This may be a HF hub repo or a local path.
model_id: String,
/// The architecture of the model.
arch: VisionLoaderType,
/// Model data type. Defaults to `auto`.
#[serde(default = "default_dtype")]
dtype: ModelDType,
/// Path to a topology YAML file.
topology: Option<String>,
/// UQFF path to write to.
write_uqff: Option<PathBuf>,
/// UQFF path to load from. If provided, this takes precedence over applying ISQ.
from_uqff: Option<PathBuf>,
/// Automatically resize and pad images to this maximum edge length. Aspect ratio is preserved.
/// This is only supported on the Qwen2-VL and Idefics 2 models. Others handle this internally.
max_edge: Option<u32>,
/// Generate and utilize an imatrix to enhance GGUF quantizations.
calibration_file: Option<PathBuf>,
},
}
#[derive(Deserialize)]
pub struct SpeculativeTomlModelSelected {
/// Gamma value for the model
gamma: usize,
/// Base model
draft_model: TomlModelSelected,
}
#[derive(Deserialize)]
pub struct AnyMoeTomlModelSelected {
/// Config
config: AnyMoeConfig,
/// Base model
dataset_json: String,
/// Prefix of the mlp key (the part before the layer number: "a.b.c" in "a.b.c.0.mlp")
prefix: String,
/// Name of the mlp key (the part before the layer number: "mlp" in "a.b.c.0.mlp")
mlp: String,
/// Expert model ids
model_ids: Vec<String>,
/// Layer ids (zero indexed) of layers to apply AnyMoE to, if empty will use all
#[serde(default = "default_empty_vec_usize")]
layers: Vec<usize>,
}
#[derive(Deserialize)]
pub struct TomlSelector {
/// Path to local tokenizer.json file. If this is specified it is used over any remote file.
tokenizer_json: Option<String>,
/// Selected model
model: TomlModelSelected,
/// Speculative model selector
speculative: Option<SpeculativeTomlModelSelected>,
/// AnyMoE config
anymoe: Option<AnyMoeTomlModelSelected>,
}
#[derive(Clone)]
struct TomlLoaderInnerParams {
use_flash_attn: bool,
chat_template: Option<String>,
no_kv_cache: bool,
tokenizer_json: Option<String>,
prompt_batchsize: Option<NonZeroUsize>,
}
pub struct TomlLoaderArgs {
pub use_flash_attn: bool,
pub chat_template: Option<String>,
pub no_kv_cache: bool,
pub prompt_batchsize: Option<NonZeroUsize>,
}
pub fn get_toml_selected_model_dtype(model: &TomlSelector) -> ModelDType {
match model.model {
TomlModelSelected::Plain { dtype, .. }
| TomlModelSelected::Lora { dtype, .. }
| TomlModelSelected::XLora { dtype, .. }
| TomlModelSelected::VisionPlain { dtype, .. } => dtype,
TomlModelSelected::GGUF { .. }
| TomlModelSelected::LoraGGUF { .. }
| TomlModelSelected::GGML { .. }
| TomlModelSelected::LoraGGML { .. }
| TomlModelSelected::XLoraGGUF { .. }
| TomlModelSelected::XLoraGGML { .. } => ModelDType::Auto,
}
}
fn loader_from_selected(
args: TomlLoaderInnerParams,
model: TomlModelSelected,
) -> anyhow::Result<Box<dyn Loader>> {
let use_flash_attn = args.use_flash_attn;
let loader: Box<dyn Loader> = match model {
TomlModelSelected::Plain {
model_id,
arch,
dtype: _,
topology,
organization,
write_uqff,
from_uqff,
imatrix,
calibration_file,
} => NormalLoaderBuilder::new(
NormalSpecificConfig {
use_flash_attn,
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
organization: organization.unwrap_or_default(),
write_uqff,
from_uqff,
imatrix,
calibration_file,
},
args.chat_template,
args.tokenizer_json,
Some(model_id),
)
.build(arch)?,
TomlModelSelected::XLora {
model_id,
xlora_model_id,
order,
tgt_non_granular_index,
arch,
dtype: _,
topology,
write_uqff,
from_uqff,
} => NormalLoaderBuilder::new(
NormalSpecificConfig {
use_flash_attn,
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
organization: Default::default(),
write_uqff,
from_uqff,
imatrix: None,
calibration_file: None,
},
args.chat_template,
args.tokenizer_json,
model_id,
)
.with_xlora(
xlora_model_id,
serde_json::from_reader(
File::open(order.clone())
.unwrap_or_else(|_| panic!("Could not load ordering file at {order}")),
)?,
args.no_kv_cache,
tgt_non_granular_index,
)
.build(arch)?,
TomlModelSelected::Lora {
model_id,
adapters_model_id,
order,
arch,
dtype: _,
topology,
write_uqff,
from_uqff,
} => NormalLoaderBuilder::new(
NormalSpecificConfig {
use_flash_attn,
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
organization: Default::default(),
write_uqff,
from_uqff,
imatrix: None,
calibration_file: None,
},
args.chat_template,
args.tokenizer_json,
model_id,
)
.with_lora(
adapters_model_id,
serde_json::from_reader(
File::open(order.clone())
.unwrap_or_else(|_| panic!("Could not load ordering file at {order}")),
)?,
)
.build(arch)?,
TomlModelSelected::GGUF {
tok_model_id,
quantized_model_id,
quantized_filename,
topology,
} => GGUFLoaderBuilder::new(
args.chat_template,
Some(tok_model_id),
quantized_model_id,
quantized_filename
.split(GGUF_MULTI_FILE_DELIMITER)
.map(ToOwned::to_owned)
.collect::<Vec<_>>(),
GGUFSpecificConfig {
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
},
)
.build(),
TomlModelSelected::XLoraGGUF {
tok_model_id,
quantized_model_id,
quantized_filename,
xlora_model_id,
order,
tgt_non_granular_index,
topology,
} => GGUFLoaderBuilder::new(
args.chat_template,
tok_model_id,
quantized_model_id,
quantized_filename
.split(GGUF_MULTI_FILE_DELIMITER)
.map(ToOwned::to_owned)
.collect::<Vec<_>>(),
GGUFSpecificConfig {
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
},
)
.with_xlora(
xlora_model_id,
serde_json::from_reader(
File::open(order.clone())
.unwrap_or_else(|_| panic!("Could not load ordering file at {order}")),
)?,
args.no_kv_cache,
tgt_non_granular_index,
)
.build(),
TomlModelSelected::LoraGGUF {
tok_model_id,
quantized_model_id,
quantized_filename,
adapters_model_id,
order,
topology,
} => GGUFLoaderBuilder::new(
args.chat_template,
tok_model_id,
quantized_model_id,
quantized_filename
.split(GGUF_MULTI_FILE_DELIMITER)
.map(ToOwned::to_owned)
.collect::<Vec<_>>(),
GGUFSpecificConfig {
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
},
)
.with_lora(
adapters_model_id,
serde_json::from_reader(
File::open(order.clone())
.unwrap_or_else(|_| panic!("Could not load ordering file at {order}")),
)?,
)
.build(),
TomlModelSelected::GGML {
tok_model_id,
quantized_model_id,
quantized_filename,
gqa,
topology,
} => GGMLLoaderBuilder::new(
GGMLSpecificConfig {
gqa,
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
},
args.chat_template,
args.tokenizer_json,
Some(tok_model_id),
quantized_model_id,
quantized_filename,
)
.build(),
TomlModelSelected::XLoraGGML {
tok_model_id,
quantized_model_id,
quantized_filename,
xlora_model_id,
order,
tgt_non_granular_index,
gqa,
topology,
} => GGMLLoaderBuilder::new(
GGMLSpecificConfig {
gqa,
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
},
args.chat_template,
args.tokenizer_json,
tok_model_id,
quantized_model_id,
quantized_filename,
)
.with_xlora(
xlora_model_id,
serde_json::from_reader(
File::open(order.clone())
.unwrap_or_else(|_| panic!("Could not load ordering file at {order}")),
)?,
args.no_kv_cache,
tgt_non_granular_index,
)
.build(),
TomlModelSelected::LoraGGML {
tok_model_id,
quantized_model_id,
quantized_filename,
adapters_model_id,
order,
gqa,
topology,
} => GGMLLoaderBuilder::new(
GGMLSpecificConfig {
gqa,
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
},
args.chat_template,
args.tokenizer_json,
tok_model_id,
quantized_model_id,
quantized_filename,
)
.with_lora(
adapters_model_id,
serde_json::from_reader(
File::open(order.clone())
.unwrap_or_else(|_| panic!("Could not load ordering file at {order}")),
)?,
)
.build(),
TomlModelSelected::VisionPlain {
model_id,
arch,
dtype: _,
topology,
write_uqff,
from_uqff,
max_edge,
calibration_file,
} => VisionLoaderBuilder::new(
VisionSpecificConfig {
use_flash_attn,
prompt_batchsize: args.prompt_batchsize,
topology: Topology::from_option_path(topology)?,
write_uqff,
from_uqff,
max_edge,
calibration_file,
},
args.chat_template,
args.tokenizer_json,
Some(model_id),
)
.build(arch),
};
Ok(loader)
}
impl TryInto<Box<dyn Loader>> for (TomlSelector, TomlLoaderArgs) {
type Error = anyhow::Error;
fn try_into(self) -> Result<Box<dyn Loader>, Self::Error> {
let (selector, args) = self;
let args = TomlLoaderInnerParams {
use_flash_attn: args.use_flash_attn,
chat_template: args.chat_template,
no_kv_cache: args.no_kv_cache,
tokenizer_json: selector.tokenizer_json,
prompt_batchsize: args.prompt_batchsize,
};
let loader = loader_from_selected(args.clone(), selector.model)?;
let loader = if let Some(speculative) = selector.speculative {
let draft_loader = loader_from_selected(args, speculative.draft_model)?;
Box::new(SpeculativeLoader {
target: loader,
draft: draft_loader,
config: SpeculativeConfig {
gamma: speculative.gamma,
},
})
} else {
loader
};
let loader = if let Some(AnyMoeTomlModelSelected {
config,
dataset_json,
prefix,
mlp,
model_ids,
layers,
}) = selector.anymoe
{
Box::new(AnyMoeLoader {
target: loader,
config,
path: dataset_json,
prefix,
mlp,
model_ids,
layers,
})
} else {
loader
};
Ok(loader)
}
}