-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathmain.rs
1875 lines (1650 loc) · 64 KB
/
main.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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use clap::{Parser, ValueEnum};
use hf_hub::{
api::sync::{Api, ApiBuilder},
Repo, RepoType,
};
use nix::sys::signal::{self, Signal};
use nix::unistd::Pid;
use secrecy::{ExposeSecret, SecretBox};
use serde::Deserialize;
use std::env;
use std::ffi::OsString;
use std::io::{BufRead, BufReader, Lines};
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::Path;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::TryRecvError;
use std::sync::{mpsc, Arc};
use std::thread;
use std::thread::sleep;
use std::time::{Duration, Instant};
use std::{fs, io};
use tracing_subscriber::EnvFilter;
mod env_runtime;
fn get_config(
model_id: &str,
revision: &Option<String>,
) -> Result<Config, Box<dyn std::error::Error>> {
let mut path = std::path::Path::new(model_id).to_path_buf();
let model_id = model_id.to_string();
let filename = if !path.exists() {
// Assume it's a hub id
let api = if let Ok(token) = std::env::var("HF_TOKEN") {
// env variable has precedence over on file token.
ApiBuilder::new().with_token(Some(token)).build()?
} else {
Api::new()?
};
let repo = if let Some(ref revision) = revision {
api.repo(Repo::with_revision(
model_id,
RepoType::Model,
revision.to_string(),
))
} else {
api.model(model_id)
};
repo.get("config.json")?
} else {
path.push("config.json");
path
};
let content = std::fs::read_to_string(filename)?;
let config: RawConfig = serde_json::from_str(&content)?;
let config: Config = config.into();
Ok(config)
}
#[derive(Deserialize)]
struct RawConfig {
max_position_embeddings: Option<usize>,
n_positions: Option<usize>,
model_type: Option<String>,
max_seq_len: Option<usize>,
quantization_config: Option<QuantizationConfig>,
n_embd: Option<usize>,
hidden_size: Option<usize>,
num_attention_heads: Option<usize>,
head_dim: Option<usize>,
vision_config: Option<VisionConfig>,
is_encoder_decoder: Option<bool>,
}
#[derive(Deserialize)]
struct QuantizationConfig {
quant_method: Option<Quantization>,
}
#[derive(Deserialize)]
struct VisionConfig {}
#[derive(Deserialize)]
struct Config {
max_position_embeddings: Option<usize>,
quantize: Option<Quantization>,
head_dim: Option<usize>,
model_type: Option<String>,
vision_config: Option<VisionConfig>,
is_encoder_decoder: bool,
}
impl From<RawConfig> for Config {
fn from(other: RawConfig) -> Self {
let max_position_embeddings = other
.max_position_embeddings
.or(other.max_seq_len)
.or(other.n_positions);
let quantize = other.quantization_config.and_then(|q| q.quant_method);
let head_dim = other.head_dim.or_else(|| {
match (other.hidden_size, other.n_embd, other.num_attention_heads) {
(Some(hidden_size), _, Some(num_attention_heads))
if hidden_size % num_attention_heads == 0 =>
{
Some(hidden_size / num_attention_heads)
}
// Legacy
(_, Some(hidden_size), Some(num_attention_heads))
if hidden_size % num_attention_heads == 0 =>
{
Some(hidden_size / num_attention_heads)
}
_ => None,
}
});
let model_type = other.model_type;
let vision_config = other.vision_config;
let is_encoder_decoder = other.is_encoder_decoder.unwrap_or(false);
Config {
max_position_embeddings,
quantize,
head_dim,
model_type,
vision_config,
is_encoder_decoder,
}
}
}
#[derive(Clone, Copy, Debug, ValueEnum, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum Quantization {
/// 4 bit quantization. Requires a specific AWQ quantized model:
/// <https://hf.co/models?search=awq>.
/// Should replace GPTQ models wherever possible because of the better latency
Awq,
/// 8 bit quantization, doesn't require specific model.
/// Should be a drop-in replacement to bitsandbytes with much better performance.
/// Kernels are from <https://github.com/NetEase-FuXi/EETQ.git>
Eetq,
/// Variable bit quantization. Requires a specific EXL2 quantized model:
/// <https://hf.co/models?search=exl2>. Requires exllama2 kernels and does
/// not support tensor parallelism (num_shard > 1).
Exl2,
/// 4 bit quantization. Requires a specific GTPQ quantized model: <https://hf.co/models?search=gptq>.
/// text-generation-inference will use exllama (faster) kernels wherever possible, and use
/// triton kernel (wider support) when it's not.
/// AWQ has faster kernels.
Gptq,
/// Bitsandbytes 8bit. Can be applied on any model, will cut the memory requirement in half,
/// but it is known that the model will be much slower to run than the native f16.
// #[deprecated(
// since = "1.1.0",
// note = "Use `eetq` instead, which provides better latencies overall and is drop-in in most cases"
// )]
Bitsandbytes,
/// Bitsandbytes 4bit. Can be applied on any model, will cut the memory requirement by 4x,
/// but it is known that the model will be much slower to run than the native f16.
BitsandbytesNf4,
/// Bitsandbytes 4bit. nf4 should be preferred in most cases but maybe this one has better
/// perplexity performance for you model
BitsandbytesFp4,
/// [FP8](https://developer.nvidia.com/blog/nvidia-arm-and-intel-publish-fp8-specification-for-standardization-as-an-interchange-format-for-ai/) (e4m3) works on H100 and above
/// This dtype has native ops should be the fastest if available.
/// This is currently not the fastest because of local unpacking + padding to satisfy matrix
/// multiplication limitations.
Fp8,
/// FP8 with statically quantized KV cache
Fp8_KV,
/// 4 bit quantization. Requires a specific HQQ quantized model.
Hqq_4bit,
/// 3 bit quantization. Requires a specific HQQ quantized model.
Hqq_3bit,
/// 2 bit quantization. Requires a specific HQQ quantized model.
Hqq_2bit,
}
impl std::fmt::Display for Quantization {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// To keep in track with `server`.
match self {
#[allow(deprecated)]
// Use `eetq` instead, which provides better latencies overall and is drop-in in most cases
Quantization::Bitsandbytes => {
write!(f, "bitsandbytes")
}
Quantization::BitsandbytesNf4 => {
write!(f, "bitsandbytes-nf4")
}
Quantization::BitsandbytesFp4 => {
write!(f, "bitsandbytes-fp4")
}
Quantization::Exl2 => {
write!(f, "exl2")
}
Quantization::Gptq => {
write!(f, "gptq")
}
Quantization::Awq => {
write!(f, "awq")
}
Quantization::Eetq => {
write!(f, "eetq")
}
Quantization::Fp8 => {
write!(f, "fp8")
}
Quantization::Fp8_KV => {
write!(f, "fp8-kv")
}
Quantization::Hqq_4bit => {
write!(f, "hqq-4bit")
}
Quantization::Hqq_3bit => {
write!(f, "hqq-3bit")
}
Quantization::Hqq_2bit => {
write!(f, "hqq-2bit")
}
}
}
}
#[derive(Clone, Copy, Debug, ValueEnum)]
enum Dtype {
#[clap(name = "float16")]
Float16,
#[clap(name = "bfloat16")]
BFloat16,
}
impl std::fmt::Display for Dtype {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// To keep in track with `server`.
match self {
Dtype::Float16 => {
write!(f, "float16")
}
Dtype::BFloat16 => {
write!(f, "bfloat16")
}
}
}
}
#[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)]
enum Backend {
#[clap(name = "fa2")]
FA2,
#[clap(name = "flashinfer")]
FlashInfer,
}
impl std::fmt::Display for Backend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// To keep in sync with `server`.
match self {
Backend::FA2 => {
write!(f, "fa2")
}
Backend::FlashInfer => {
write!(f, "flashinfer")
}
}
}
}
/// App Configuration
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// The name of the model to load.
/// Can be a MODEL_ID as listed on <https://hf.co/models> like
/// `gpt2` or `mistralai/Mistral-7B-Instruct-v0.1`.
/// Or it can be a local directory containing the necessary files
/// as saved by `save_pretrained(...)` methods of transformers
/// Optionally you can specify a revision with `@` like
/// `<model_id>@main` - this is incompatible with the `--revision`
/// flag.
#[clap(default_value = "mistralai/Mistral-7B-Instruct-v0.1", long, env)]
model_id: String,
/// The name of the adapter to load.
/// Can be a MODEL_ID as listed on <https://hf.co/models>
/// or it can be a local directory containing the necessary files
/// as saved by `save_pretrained(...)` methods of transformers.
/// Should be compatible with the model specified in `model_id`.
#[clap(long, env)]
adapter_id: Option<String>,
/// The source of the model to load.
/// Can be `hub` or `s3`.
/// `hub` will load the model from the huggingface hub.
/// `s3` will load the model from the predibase S3 bucket.
#[clap(default_value = "hub", long, env)]
source: String,
/// The default source of the dynamic adapters to load.
/// If not defined, we fallback to the value from `adapter_source`
/// Can be `hub` or `s3` or `pbase`
/// `hub` will load the model from the huggingface hub.
/// `s3` will load the model from the predibase S3 bucket.
/// `pbase` will load an s3 model but resolve the metadata from a predibase server
#[clap(long, env)]
default_adapter_source: Option<String>,
/// The source of the static adapter to load.
/// Can be `hub` or `s3` or `pbase`
/// `hub` will load the model from the huggingface hub.
/// `s3` will load the model from the predibase S3 bucket.
/// `pbase` will load an s3 model but resolve the metadata from a predibase server
#[clap(default_value = "hub", long, env)]
adapter_source: String,
/// The actual revision of the model if you're referring to a model
/// on the hub. You can use a specific commit id or a branch like `refs/pr/2`.
#[clap(long, env)]
revision: Option<String>,
/// The number of tokenizer workers used for payload validation and truncation inside the
/// router.
#[clap(default_value = "2", long, env)]
validation_workers: usize,
/// Whether to shard the model across multiple GPUs
/// By default LoRAX will use all available GPUs to run
/// the model. Setting it to `false` deactivates `num_shard`.
#[clap(long, env)]
sharded: Option<bool>,
/// The number of shards to use if you don't want to use all GPUs on a given machine.
/// You can use `CUDA_VISIBLE_DEVICES=0,1 lorax-launcher... --num_shard 2`
/// and `CUDA_VISIBLE_DEVICES=2,3 lorax-launcher... --num_shard 2` to
/// launch 2 copies with 2 shard each on a given machine with 4 GPUs for instance.
#[clap(long, env)]
num_shard: Option<usize>,
/// Whether you want the model to be quantized. This will use `bitsandbytes` for
/// quantization on the fly, or `gptq`.
#[clap(long, env, value_enum)]
quantize: Option<Quantization>,
/// Whether you want to compile the model into a CUDA graph.
/// This will speed up decoding but increase GPU memory usage.
/// Only use either `--compile` or `--eager`. Using both at the same time will
/// result in an error.
#[clap(long, env, value_enum)]
compile: bool,
/// Whether you want to run the model in eager mode, without
/// CUDA mode compilation, or run it with compilation.
/// Only use either `--compile` or `--eager`. Using both at the same time will
/// result in an error.
#[clap(long, env, value_enum)]
eager: bool,
// The maximum batch size past which CUDA graphs are disabled.
#[clap(default_value = "128", long, env)]
compile_max_batch_size: usize,
// The maximum adapter rank (LoRA) past which CUDA graphs are disabled.
#[clap(default_value = "64", long, env)]
compile_max_rank: usize,
// The initial batch size for model CUDA compilations
#[clap(default_value = "32", long, env)]
compile_batch_size: usize,
/// The number of speculative tokens to generate in the model per step.
/// Defaults to 0, meaning no speculative decoding.
#[clap(long, env)]
speculative_tokens: Option<usize>,
// The maximum batch size past which speculative decoding is disabled.
#[clap(default_value = "32", long, env)]
speculation_max_batch_size: usize,
/// The list of adapter ids to preload during initialization (to avoid cold start times).
#[clap(long, env)]
preloaded_adapter_ids: Vec<String>,
/// The source to use for the preloaded adapters.
/// If unset, will default to using the `adapter_source` value.
/// Can be `hub` or `s3` or `pbase`
/// `hub` will load the model from the huggingface hub.
/// `s3` will load the model from the predibase S3 bucket.
/// `pbase` will load an s3 model but resolve the metadata from a predibase server
#[clap(long, env)]
preloaded_adapter_source: Option<String>,
/// The API token to use when fetching adapters from pbase.
/// If specified, will set the environment variable PREDIBASE_API_TOKEN.
#[clap(long, env)]
predibase_api_token: Option<SecretBox<str>>,
/// The dtype to be forced upon the model. This option cannot be used with `--quantize`.
#[clap(long, env, value_enum)]
dtype: Option<Dtype>,
/// Whether you want to execute hub modelling code. Explicitly passing a `revision` is
/// encouraged when loading a model with custom code to ensure no malicious code has been
/// contributed in a newer revision.
#[clap(long, env, value_enum)]
trust_remote_code: bool,
/// The maximum amount of concurrent requests for this particular deployment.
/// Having a low limit will refuse clients requests instead of having them
/// wait for too long and is usually good to handle backpressure correctly.
#[clap(default_value = "1024", long, env)]
max_concurrent_requests: usize,
/// This is the maximum allowed value for clients to set `best_of`.
/// Best of makes `n` generations at the same time, and return the best
/// in terms of overall log probability over the entire generated sequence
#[clap(default_value = "2", long, env)]
max_best_of: usize,
/// This is the maximum allowed value for clients to set `stop_sequences`.
/// Stop sequences are used to allow the model to stop on more than just
/// the EOS token, and enable more complex "prompting" where users can preprompt
/// the model in a specific way and define their "own" stop token aligned with
/// their prompt.
#[clap(default_value = "4", long, env)]
max_stop_sequences: usize,
/// This is the maximum allowed input length (expressed in number of tokens)
/// for users. The larger this value, the longer prompt users can send which
/// can impact the overall memory required to handle the load.
/// Please note that some models have a finite range of sequence they can handle.
/// Default to min(max_position_embeddings - 1, 4095)
#[clap(long, env)]
max_input_length: Option<usize>,
/// This is the most important value to set as it defines the "memory budget"
/// of running clients requests.
/// Clients will send input sequences and ask to generate `max_new_tokens`
/// on top. with a value of `1512` users can send either a prompt of
/// `1000` and ask for `512` new tokens, or send a prompt of `1` and ask for
/// `1511` max_new_tokens.
/// The larger this value, the larger amount each request will be in your RAM
/// and the less effective batching can be.
/// Default to min(max_position_embeddings, 4096)
#[clap(long, env)]
max_total_tokens: Option<usize>,
/// This represents the ratio of waiting queries vs running queries where
/// you want to start considering pausing the running queries to include the waiting
/// ones into the same batch.
/// `waiting_served_ratio=1.2` Means when 12 queries are waiting and there's
/// only 10 queries left in the current batch we check if we can fit those 12
/// waiting queries into the batching strategy, and if yes, then batching happens
/// delaying the 10 running queries by a `prefill` run.
///
/// This setting is only applied if there is room in the batch
/// as defined by `max_batch_total_tokens`.
#[clap(default_value = "1.2", long, env)]
waiting_served_ratio: f32,
/// Limits the number of tokens for the prefill operation.
/// Since this operation take the most memory and is compute bound, it is interesting
/// to limit the number of requests that can be sent.
/// Default to `max_input_tokens + 50` to give a bit of room.
#[clap(long, env)]
max_batch_prefill_tokens: Option<u32>,
/// **IMPORTANT** This is one critical control to allow maximum usage
/// of the available hardware.
///
/// This represents the total amount of potential tokens within a batch.
/// When using padding (not recommended) this would be equivalent of
/// `batch_size` * `max_total_tokens`.
///
/// However in the non-padded (flash attention) version this can be much finer.
///
/// For `max_batch_total_tokens=1000`, you could fit `10` queries of `total_tokens=100`
/// or a single query of `1000` tokens.
///
/// Overall this number should be the largest possible amount that fits the
/// remaining memory (after the model is loaded). Since the actual memory overhead
/// depends on other parameters like if you're using quantization, flash attention
/// or the model implementation, LoRAX cannot infer this number
/// automatically.
#[clap(long, env)]
max_batch_total_tokens: Option<u32>,
/// This setting defines how many tokens can be passed before forcing the waiting
/// queries to be put on the batch (if the size of the batch allows for it).
/// New queries require 1 `prefill` forward, which is different from `decode`
/// and therefore you need to pause the running batch in order to run `prefill`
/// to create the correct values for the waiting queries to be able to join the batch.
///
/// With a value too small, queries will always "steal" the compute to run `prefill`
/// and running queries will be delayed by a lot.
///
/// With a value too big, waiting queries could wait for a very long time
/// before being allowed a slot in the running batch. If your server is busy
/// that means that requests that could run in ~2s on an empty server could
/// end up running in ~20s because the query had to wait for 18s.
///
/// This number is expressed in number of tokens to make it a bit more
/// "model" agnostic, but what should really matter is the overall latency
/// for end users.
#[clap(default_value = "20", long, env)]
max_waiting_tokens: usize,
/// Whether to prioritize running prefill before decode to increase batch size during decode (throughput) over
/// liveness in earlier requests (latency). For batch use cases that are not latnecy sensitive, this should be set
/// to true.
#[clap(default_value = "true", long, env)]
eager_prefill: Option<bool>,
/// Split prefill requests into multiple chunks and batch them with decode requests. For high QPS scenarios, this
/// can greatly improve throughput by overlapping request types. See: https://arxiv.org/pdf/2308.16369.
#[clap(long, env)]
chunked_prefill: Option<bool>,
/// Whether to use the prefix caching mechanism. This will skip computing attention on previously cached prefixes
/// in the prompt. Useful in cases where many queries need to be run over a shared context, or for long multi-turn
/// chats conversations.
#[clap(long, env)]
prefix_caching: Option<bool>,
/// Whether to merge the weights of the adapter with the base model weights. This will disable dynamic adapter
/// loading.
#[clap(long, env, value_enum)]
merge_adapter_weights: bool,
/// Maximum number of adapters that can be placed on the GPU and accept requests at a time.
#[clap(default_value = "1024", long, env)]
max_active_adapters: usize,
/// The time in seconds between adapter exchanges.
#[clap(default_value = "2", long, env)]
adapter_cycle_time_s: u64,
/// Reservation of memory set aside for loading adapters onto the GPU.
/// Increasing this value will reduce the size of the KV cache in exchange for allowing more
/// adapters to be loaded onto the GPU at once.
/// This value is NOT scaled relative to `cuda_memory_fraction`, but is expressed in absolute terms.
#[clap(default_value = "0.1", long, env)]
adapter_memory_fraction: f32,
/// The IP address to listen on
#[clap(default_value = "0.0.0.0", long, env)]
hostname: String,
/// The port to listen on.
#[clap(default_value = "3000", long, short, env)]
port: u16,
/// The name of the socket for gRPC communication between the webserver
/// and the shards.
#[clap(default_value = "/tmp/lorax-server", long, env)]
shard_uds_path: String,
/// The address the master shard will listen on. (setting used by torch distributed)
#[clap(default_value = "localhost", long, env)]
master_addr: String,
/// The address the master port will listen on. (setting used by torch distributed)
#[clap(default_value = "29500", long, env)]
master_port: usize,
/// The location of the huggingface hub cache.
/// Used to override the location if you want to provide a mounted disk for instance
#[clap(long, env)]
huggingface_hub_cache: Option<String>,
/// The location of the huggingface hub cache.
/// Used to override the location if you want to provide a mounted disk for instance
#[clap(long, env)]
weights_cache_override: Option<String>,
/// For some models (like llama), LoRAX implemented custom
/// cuda kernels to speed up inference. Those kernels were only tested on A100.
/// Use this flag to disable them if you're running on different hardware and
/// encounter issues.
#[clap(long, env)]
disable_custom_kernels: bool,
/// Limit the CUDA available memory.
/// The allowed value equals the total visible memory multiplied by cuda-memory-fraction.
#[clap(default_value = "1.0", long, env)]
cuda_memory_fraction: f32,
/// Outputs the logs in JSON format (useful for telemetry)
#[clap(long, env)]
json_output: bool,
#[clap(long, env)]
otlp_endpoint: Option<String>,
#[clap(long, env)]
cors_allow_origin: Vec<String>,
#[clap(long, env)]
cors_allow_header: Vec<String>,
#[clap(long, env)]
cors_expose_header: Vec<String>,
#[clap(long, env)]
cors_allow_method: Vec<String>,
#[clap(long, env)]
cors_allow_credentials: Option<bool>,
#[clap(long, env)]
watermark_gamma: Option<f32>,
#[clap(long, env)]
watermark_delta: Option<f32>,
/// Enable ngrok tunneling
#[clap(long, env)]
ngrok: bool,
/// ngrok authentication token
#[clap(long, env)]
ngrok_authtoken: Option<String>,
/// ngrok edge
#[clap(long, env)]
ngrok_edge: Option<String>,
/// Display a lot of information about your runtime environment
#[clap(long, short, action)]
env: bool,
/// Download model weights only
#[clap(long, env)]
download_only: bool,
/// The path to the tokenizer config file. This path is used to load the tokenizer configuration which may
/// include a `chat_template`. If not provided, the default config will be used from the model hub.
#[clap(long, env)]
tokenizer_config_path: Option<String>,
/// The backend to use for the model. Can be `fa2` or `flashinfer`.
#[clap(default_value = "fa2", long, env, value_enum)]
backend: Backend,
/// The embedding dimension to use for the model.
#[clap(long, env)]
embedding_dim: Option<usize>,
#[clap(long, env)]
disable_sgmv: bool,
#[clap(default_value = "0.9", long, env)]
memory_wiggle_room: f32,
}
#[derive(Debug)]
enum ShardStatus {
Ready,
Failed(usize),
}
#[allow(clippy::too_many_arguments)]
fn shard_manager(
model_id: String,
adapter_id: String,
revision: Option<String>,
source: String,
adapter_source: String,
quantize: Option<Quantization>,
compile: bool,
eager: bool,
compile_max_batch_size: usize,
compile_max_rank: usize,
compile_batch_size: usize,
speculative_tokens: Option<usize>,
speculation_max_batch_size: usize,
preloaded_adapter_ids: Vec<String>,
preloaded_adapter_source: Option<String>,
predibase_api_token: Option<String>,
dtype: Option<Dtype>,
trust_remote_code: bool,
uds_path: String,
rank: usize,
world_size: usize,
master_addr: String,
master_port: usize,
huggingface_hub_cache: Option<String>,
weights_cache_override: Option<String>,
disable_custom_kernels: bool,
watermark_gamma: Option<f32>,
watermark_delta: Option<f32>,
cuda_memory_fraction: f32,
adapter_memory_fraction: f32,
prefix_caching: Option<bool>,
chunked_prefill: Option<bool>,
merge_adapter_weights: bool,
backend: Backend,
otlp_endpoint: Option<String>,
status_sender: mpsc::Sender<ShardStatus>,
shutdown: Arc<AtomicBool>,
_shutdown_sender: mpsc::Sender<()>,
embedding_dim: Option<usize>,
disable_sgmv: bool,
memory_wiggle_room: f32,
) {
// Enter shard-manager tracing span
let _span = tracing::span!(tracing::Level::INFO, "shard-manager", rank = rank).entered();
// Get UDS path
let uds_string = format!("{uds_path}-{rank}");
let uds = Path::new(&uds_string);
// Clean previous runs
if uds.exists() {
fs::remove_file(uds).unwrap();
}
// Process args
let mut shard_args = vec![
"serve".to_string(),
model_id,
"--uds-path".to_string(),
uds_path,
"--logger-level".to_string(),
"INFO".to_string(),
"--json-output".to_string(),
"--source".to_string(),
source,
"--adapter-source".to_string(),
adapter_source,
];
// Check if adapter id is non-empty string
if !adapter_id.is_empty() {
shard_args.push("--adapter-id".to_string());
shard_args.push(adapter_id);
}
// Activate trust remote code
if trust_remote_code {
shard_args.push("--trust-remote-code".to_string());
}
// Activate tensor parallelism
if world_size > 1 {
shard_args.push("--sharded".to_string());
}
if let Some(quantize) = quantize {
shard_args.push("--quantize".to_string());
shard_args.push(quantize.to_string())
}
// CUDA graph compilation
if !eager {
shard_args.push("--compile".to_string());
}
if compile && eager {
panic!("Cannot use both --compile and --eager at the same time.");
}
// Speculative decoding
if let Some(speculative_tokens) = speculative_tokens {
shard_args.push("--speculative-tokens".to_string());
shard_args.push(speculative_tokens.to_string())
}
// Preloaded adapters
let has_preloaded_adapters = !preloaded_adapter_ids.is_empty();
for adapter_id in preloaded_adapter_ids {
shard_args.push("--preloaded-adapter-ids".to_string());
shard_args.push(adapter_id);
}
// Merge adapter weights
if merge_adapter_weights {
shard_args.push("--merge-adapter-weights".to_string());
}
// Preloaded adapter source
if let Some(preloaded_adapter_source) = preloaded_adapter_source {
shard_args.push("--preloaded-adapter-source".to_string());
shard_args.push(preloaded_adapter_source);
}
if let Some(dtype) = dtype {
shard_args.push("--dtype".to_string());
shard_args.push(dtype.to_string())
}
// Model optional revision
if let Some(revision) = revision {
shard_args.push("--revision".to_string());
shard_args.push(revision)
}
// OpenTelemetry
if let Some(otlp_endpoint) = otlp_endpoint {
shard_args.push("--otlp-endpoint".to_string());
shard_args.push(otlp_endpoint);
}
// Embedding dimension
if let Some(embedding_dim) = embedding_dim {
shard_args.push("--embedding-dim".to_string());
shard_args.push(embedding_dim.to_string())
}
// Copy current process env
let mut envs: Vec<(OsString, OsString)> = env::vars_os().collect();
if let Some(predibase_api_token) = predibase_api_token {
envs.push((
"PREDIBASE_API_TOKEN".into(),
predibase_api_token.to_string().into(),
));
}
// Torch Distributed Env vars
envs.push(("RANK".into(), rank.to_string().into()));
envs.push(("WORLD_SIZE".into(), world_size.to_string().into()));
envs.push(("MASTER_ADDR".into(), master_addr.into()));
envs.push(("MASTER_PORT".into(), master_port.to_string().into()));
envs.push(("NCCL_ASYNC_ERROR_HANDLING".into(), "1".into()));
// CUDA memory fraction
envs.push((
"CUDA_MEMORY_FRACTION".into(),
cuda_memory_fraction.to_string().into(),
));
// Adapter memory fraction
if has_preloaded_adapters {
envs.push(("ADAPTER_MEMORY_FRACTION".into(), "0".into()));
} else {
envs.push((
"ADAPTER_MEMORY_FRACTION".into(),
adapter_memory_fraction.to_string().into(),
));
}
// Prefix caching
if let Some(prefix_caching) = prefix_caching {
let prefix_caching = if prefix_caching { "1" } else { "0" };
envs.push(("PREFIX_CACHING".into(), prefix_caching.into()));
}
// Chunked prefill
if let Some(chunked_prefill) = chunked_prefill {
let chunked_prefill = if chunked_prefill { "1" } else { "0" };
envs.push(("CHUNKED_PREFILL".into(), chunked_prefill.into()));
}
// Compile max batch size and rank
envs.push((
"LORAX_COMPILE_MAX_BATCH_SIZE".into(),
compile_max_batch_size.to_string().into(),
));
envs.push((
"LORAX_COMPILE_MAX_RANK".into(),
compile_max_rank.to_string().into(),
));
// Compile initial batch size
envs.push((
"LORAX_COMPILE_BATCH_SIZE".into(),
compile_batch_size.to_string().into(),
));
// Speculative decoding max batch size
envs.push((
"LORAX_SPECULATION_MAX_BATCH_SIZE".into(),
speculation_max_batch_size.to_string().into(),
));
// Backend
if backend == Backend::FlashInfer {
envs.push(("FLASH_INFER".into(), "1".into()));
}
if disable_sgmv {
envs.push(("DISABLE_SGMV".into(), "1".into()))
}
// Memory wiggle room
envs.push((
"MEMORY_WIGGLE_ROOM".into(),
memory_wiggle_room.to_string().into(),
));
// Safetensors load fast
envs.push(("SAFETENSORS_FAST_GPU".into(), "1".into()));
// Disable progress bars to prevent hanging in containers
envs.push(("HF_HUB_DISABLE_PROGRESS_BARS".into(), "1".into()));
// Enable hf transfer for insane download speeds
let enable_hf_transfer = env::var("HF_HUB_ENABLE_HF_TRANSFER").unwrap_or("1".to_string());
envs.push((
"HF_HUB_ENABLE_HF_TRANSFER".into(),
enable_hf_transfer.into(),
));
// Parse Inference API token
if let Ok(api_token) = env::var("HF_API_TOKEN") {
envs.push(("HUGGING_FACE_HUB_TOKEN".into(), api_token.into()))
};
// If huggingface_hub_cache is some, pass it to the shard
// Useful when running inside a docker container
if let Some(huggingface_hub_cache) = huggingface_hub_cache {
envs.push(("HUGGINGFACE_HUB_CACHE".into(), huggingface_hub_cache.into()));
};
// If weights_cache_override is some, pass it to the shard
// Useful when running inside a HuggingFace Inference Endpoint
if let Some(weights_cache_override) = weights_cache_override {
envs.push((
"WEIGHTS_CACHE_OVERRIDE".into(),
weights_cache_override.into(),
));
};
// If disable_custom_kernels is true, pass it to the shard as an env var
if disable_custom_kernels {
envs.push(("DISABLE_CUSTOM_KERNELS".into(), "True".into()))
}
// Watermark Gamma
if let Some(watermark_gamma) = watermark_gamma {
envs.push(("WATERMARK_GAMMA".into(), watermark_gamma.to_string().into()))
}
// Watermark Delta
if let Some(watermark_delta) = watermark_delta {
envs.push(("WATERMARK_DELTA".into(), watermark_delta.to_string().into()))
}
// Start process
tracing::info!("Starting shard");
let mut p = match Command::new("lorax-server")
.args(shard_args)
.envs(envs)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0)
.spawn()
{
Ok(p) => p,
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
tracing::error!("lorax-server not found in PATH");
tracing::error!("Please install it with `make install-server`")
}
{
tracing::error!("{}", err);
}
status_sender.send(ShardStatus::Failed(rank)).unwrap();
return;
}
};
let shard_stdout = BufReader::new(p.stdout.take().unwrap());
thread::spawn(move || {
log_lines(shard_stdout.lines());
});
let shard_stderr = BufReader::new(p.stderr.take().unwrap());
// We read stderr in another thread as it seems that lines() can block in some cases
let (err_sender, err_receiver) = mpsc::channel();
thread::spawn(move || {
for line in shard_stderr.lines().flatten() {
err_sender.send(line).unwrap_or(());
}
});
let mut ready = false;
let start_time = Instant::now();
let mut wait_time = Instant::now();
loop {
// Process exited
if let Some(exit_status) = p.try_wait().unwrap() {
let mut err = String::new();
while let Ok(line) = err_receiver.recv_timeout(Duration::from_millis(10)) {
err = err + "\n" + &line;
}
tracing::error!("Shard complete standard error output:\n{err}");
if let Some(signal) = exit_status.signal() {
tracing::error!("Shard process was signaled to shutdown with signal {signal}");
}
status_sender.send(ShardStatus::Failed(rank)).unwrap();
return;
}