__init__.py 49.8 KB
Newer Older
jixx's avatar
jixx committed
1
2
3
# ruff: noqa: F821
# the above line disables the `undefined-name` rule for the model type variables

jixx's avatar
init  
jixx committed
4
5
6
7
8
9
10
11
import torch
import enum
import os

from loguru import logger
from transformers.configuration_utils import PretrainedConfig
from transformers.models.auto import modeling_auto
from huggingface_hub import hf_hub_download, HfApi
jixx's avatar
jixx committed
12
from typing import Optional, List, Dict
jixx's avatar
init  
jixx committed
13
14
15
16
from pathlib import Path

from text_generation_server.utils.speculate import get_speculate, set_speculate
from text_generation_server.models.model import Model
jixx's avatar
jixx committed
17
18
19
20
21
22
23
24
25
from text_generation_server.models.causal_lm import CausalLM, CausalLMBatchKeysLast
from text_generation_server.models.custom_modeling.opt_modeling import OPTForCausalLM
from text_generation_server.models.custom_modeling.mpt_modeling import (
    MPTForCausalLM,
)
from text_generation_server.models.bloom import BloomCausalLMBatch
from text_generation_server.models.custom_modeling.bloom_modeling import (
    BloomForCausalLM,
)
jixx's avatar
init  
jixx committed
26
from text_generation_server.models.seq2seq_lm import Seq2SeqLM
jixx's avatar
jixx committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from text_generation_server.models.galactica import GalacticaCausalLMBatch
from text_generation_server.models.custom_modeling.neox_modeling import (
    GPTNeoxForCausalLM,
)
from text_generation_server.models.custom_modeling.phi_modeling import (
    PhiConfig,
    PhiForCausalLM,
)
from text_generation_server.models.custom_modeling.flash_phi_moe_modeling import (
    PhiMoEConfig,
)
from text_generation_server.models.custom_modeling.t5_modeling import (
    T5ForConditionalGeneration,
)


from text_generation_server.utils.adapter import (
    AdapterParameters,
    build_layer_weight_lookup,
    load_and_merge_adapters,
    AdapterInfo,
)
from text_generation_server.adapters.lora import LoraWeights

jixx's avatar
init  
jixx committed
51
52

from text_generation_server.utils.import_utils import SYSTEM
jixx's avatar
jixx committed
53
from text_generation_server.utils.log import log_master
jixx's avatar
init  
jixx committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

# The flag below controls whether to allow TF32 on matmul. This flag defaults to False
# in PyTorch 1.12 and later.
torch.backends.cuda.matmul.allow_tf32 = True

# The flag below controls whether to allow TF32 on cuDNN. This flag defaults to True.
torch.backends.cudnn.allow_tf32 = True

# Disable gradients
torch.set_grad_enabled(False)

__all__ = [
    "Model",
    "CausalLM",
    "Seq2SeqLM",
jixx's avatar
jixx committed
69
    "get_model_with_lora_adapters",
jixx's avatar
init  
jixx committed
70
71
72
73
74
75
76
77
]

FLASH_ATT_ERROR_MESSAGE = "{} requires Flash Attention enabled models."

FLASH_ATTENTION = True

try:
    from text_generation_server.models.flash_causal_lm import FlashCausalLM
jixx's avatar
jixx committed
78
79
80
81
82
    from text_generation_server.models.vlm_causal_lm import VlmCausalLM
    from text_generation_server.models.mllama_causal_lm import MllamaCausalLM
    from text_generation_server.models.custom_modeling.flash_deepseek_v2_modeling import (
        FlashDeepseekV2ForCausalLM,
        DeepseekV2Config,
jixx's avatar
init  
jixx committed
83
    )
jixx's avatar
jixx committed
84
85
    from text_generation_server.models.custom_modeling.flash_llama_modeling import (
        FlashLlamaForCausalLM,
jixx's avatar
init  
jixx committed
86
    )
jixx's avatar
jixx committed
87
88
    from text_generation_server.models.custom_modeling.flash_cohere_modeling import (
        FlashCohereForCausalLM,
jixx's avatar
init  
jixx committed
89
    )
jixx's avatar
jixx committed
90
91
    from text_generation_server.models.custom_modeling.flash_gemma_modeling import (
        FlashGemmaForCausalLM,
jixx's avatar
init  
jixx committed
92
    )
jixx's avatar
jixx committed
93
94
95
96
97
98
99
100
101
102
103
104
105
    from text_generation_server.models.custom_modeling.flash_gemma2_modeling import (
        FlashGemma2ForCausalLM,
    )
    from text_generation_server.models.custom_modeling.flash_dbrx_modeling import (
        FlashDbrxForCausalLM,
        DbrxConfig,
    )
    from text_generation_server.models.custom_modeling.flash_rw_modeling import (
        RWConfig,
        FlashRWForCausalLM,
    )
    from text_generation_server.models.custom_modeling.flash_neox_modeling import (
        FlashGPTNeoXForCausalLM,
jixx's avatar
init  
jixx committed
106
107
    )
    from text_generation_server.models.pali_gemma import (
jixx's avatar
jixx committed
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
        PaliGemmaBatch,
    )
    from text_generation_server.models.custom_modeling.flash_pali_gemma_modeling import (
        PaliGemmaForConditionalGeneration,
    )
    from text_generation_server.models.custom_modeling.flash_phi_modeling import (
        FlashPhiForCausalLM,
    )
    from text_generation_server.models.idefics_causal_lm import IdeficsCausalLM
    from text_generation_server.models.mllama_causal_lm import MllamaCausalLMBatch
    from text_generation_server.models.custom_modeling.mllama import (
        MllamaForConditionalGeneration,
    )
    from text_generation_server.models.custom_modeling.llava_next import (
        LlavaNextForConditionalGeneration,
    )

    from text_generation_server.models.custom_modeling.flash_santacoder_modeling import (
        FlashSantacoderForCausalLM,
    )
    from text_generation_server.models.custom_modeling.flash_starcoder2_modeling import (
        FlashStarcoder2ForCausalLM,
    )
    from text_generation_server.models.custom_modeling.flash_qwen2_modeling import (
        Qwen2ForCausalLM,
    )
    from text_generation_server.models.custom_modeling.flash_mistral_modeling import (
        FlashMistralForCausalLM,
jixx's avatar
init  
jixx committed
136
    )
jixx's avatar
jixx committed
137
138
139
140
141
142
143
144
145
146
147
    from text_generation_server.models.custom_modeling.flash_mixtral_modeling import (
        FlashMixtralForCausalLM,
    )
    from text_generation_server.models.custom_modeling.flash_gpt2_modeling import (
        FlashGPT2ForCausalLM,
    )
    from text_generation_server.models.custom_modeling.flash_gptj_modeling import (
        FlashGPTJForCausalLM,
    )
    from text_generation_server.models.custom_modeling.idefics2 import (
        Idefics2ForConditionalGeneration,
jixx's avatar
init  
jixx committed
148
149
150
    )
    from text_generation_server.layers.attention import SUPPORTS_WINDOWING
except ImportError as e:
jixx's avatar
jixx committed
151
    log_master(logger.warning, f"Could not import Flash Attention enabled models: {e}")
jixx's avatar
init  
jixx committed
152
153
154
155
156
    SUPPORTS_WINDOWING = False
    FLASH_ATTENTION = False

if FLASH_ATTENTION:
    __all__.append(FlashCausalLM)
jixx's avatar
jixx committed
157
    __all__.append(IdeficsCausalLM)
jixx's avatar
init  
jixx committed
158
159
160
161
162

MAMBA_AVAILABLE = True
try:
    from text_generation_server.models.mamba import Mamba
except ImportError as e:
jixx's avatar
jixx committed
163
    log_master(logger.warning, f"Could not import Mamba: {e}")
jixx's avatar
init  
jixx committed
164
165
166
167
168
169
170
    MAMBA_AVAILABLE = False

if MAMBA_AVAILABLE:
    __all__.append(Mamba)


class ModelType(enum.Enum):
jixx's avatar
jixx committed
171
172
173
174
175
    DEEPSEEK_V2 = {
        "type": "deepseek_v2",
        "name": "Deepseek V2",
        "url": "https://huggingface.co/deepseek-ai/DeepSeek-V2",
    }
jixx's avatar
init  
jixx committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    IDEFICS2 = {
        "type": "idefics2",
        "name": "Idefics 2",
        "url": "https://huggingface.co/HuggingFaceM4/idefics2-8b",
        "multimodal": True,
    }
    LLAVA_NEXT = {
        "type": "llava_next",
        "name": "Llava Next (1.6)",
        "url": "https://huggingface.co/llava-hf/llava-v1.6-vicuna-13b-hf",
        "multimodal": True,
    }
    LLAMA = {
        "type": "llama",
        "name": "Llama",
jixx's avatar
jixx committed
191
        "url": "https://huggingface.co/collections/meta-llama/llama-31-669fc079a0c406a149a5738f",
jixx's avatar
init  
jixx committed
192
193
194
195
196
197
    }
    PHI3 = {
        "type": "phi3",
        "name": "Phi 3",
        "url": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct",
    }
jixx's avatar
jixx committed
198
199
200
201
202
    GRANITE = {
        "type": "granite",
        "name": "Granite",
        "url": "https://huggingface.co/ibm-granite/granite-3.0-8b-instruct",
    }
jixx's avatar
init  
jixx committed
203
204
205
206
207
    GEMMA = {
        "type": "gemma",
        "name": "Gemma",
        "url": "https://huggingface.co/google/gemma-7b",
    }
jixx's avatar
jixx committed
208
209
210
211
212
    PALIGEMMA = {
        "type": "paligemma",
        "name": "PaliGemma",
        "url": "https://huggingface.co/google/paligemma-3b-pt-224",
    }
jixx's avatar
init  
jixx committed
213
214
215
    GEMMA2 = {
        "type": "gemma2",
        "name": "Gemma2",
jixx's avatar
jixx committed
216
        "url": "https://huggingface.co/collections/google/gemma-2-release-667d6600fd5220e7b967f315",
jixx's avatar
init  
jixx committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    }
    COHERE = {
        "type": "cohere",
        "name": "Cohere",
        "url": "https://huggingface.co/CohereForAI/c4ai-command-r-plus",
    }
    DBRX = {
        "type": "dbrx",
        "name": "Dbrx",
        "url": "https://huggingface.co/databricks/dbrx-instruct",
    }
    MAMBA = {
        "type": "ssm",
        "name": "Mamba",
        "url": "https://huggingface.co/state-spaces/mamba-2.8b-slimpj",
    }
    MISTRAL = {
        "type": "mistral",
        "name": "Mistral",
jixx's avatar
jixx committed
236
        "url": "https://huggingface.co/mistralai/Mistral-Nemo-Instruct-2407",
jixx's avatar
init  
jixx committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    }
    MIXTRAL = {
        "type": "mixtral",
        "name": "Mixtral",
        "url": "https://huggingface.co/mistralai/Mixtral-8x22B-Instruct-v0.1",
    }
    GPT_BIGCODE = {
        "type": "gpt_bigcode",
        "name": "Gpt Bigcode",
        "url": "https://huggingface.co/bigcode/gpt_bigcode-santacoder",
    }
    PHI = {
        "type": "phi",
        "name": "Phi",
        "url": "https://huggingface.co/microsoft/phi-1_5",
    }
jixx's avatar
jixx committed
253
254
255
256
257
    PHI_MOE = {
        "type": "phimoe",
        "name": "PhiMoe",
        "url": "https://huggingface.co/microsoft/Phi-3.5-MoE-instruct",
    }
jixx's avatar
init  
jixx committed
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
    BAICHUAN = {
        "type": "baichuan",
        "name": "Baichuan",
        "url": "https://huggingface.co/baichuan-inc/Baichuan2-7B-Chat",
    }
    FALCON = {
        "type": "falcon",
        "name": "Falcon",
        "url": "https://huggingface.co/tiiuae/falcon-7b-instruct",
    }
    STARCODER2 = {
        "type": "starcoder2",
        "name": "StarCoder 2",
        "url": "https://huggingface.co/bigcode/starcoder2-15b-instruct-v0.1",
    }
    QWEN2 = {
        "type": "qwen2",
        "name": "Qwen 2",
        "url": "https://huggingface.co/collections/Qwen/qwen2-6659360b33528ced941e557f",
    }
    OPT = {
        "type": "opt",
        "name": "Opt",
        "url": "https://huggingface.co/facebook/opt-6.7b",
    }
    T5 = {
        "type": "t5",
        "name": "T5",
        "url": "https://huggingface.co/google/flan-t5-xxl",
    }
    GALACTICA = {
        "type": "galactica",
        "name": "Galactica",
        "url": "https://huggingface.co/facebook/galactica-120b",
    }
    SANTACODER = {
        "type": "santacoder",
        "name": "SantaCoder",
        "url": "https://huggingface.co/bigcode/santacoder",
    }
    BLOOM = {
        "type": "bloom",
        "name": "Bloom",
        "url": "https://huggingface.co/bigscience/bloom-560m",
    }
    MPT = {
        "type": "mpt",
        "name": "Mpt",
        "url": "https://huggingface.co/mosaicml/mpt-7b-instruct",
    }
    GPT2 = {
        "type": "gpt2",
        "name": "Gpt2",
        "url": "https://huggingface.co/openai-community/gpt2",
    }
    GPT_NEOX = {
        "type": "gpt_neox",
        "name": "Gpt Neox",
        "url": "https://huggingface.co/EleutherAI/gpt-neox-20b",
    }
jixx's avatar
jixx committed
318
319
320
321
322
    GPTJ = {
        "type": "gptj",
        "name": "Gptj",
        "url": "https://huggingface.co/EleutherAI/gpt-j-6b",
    }
jixx's avatar
init  
jixx committed
323
324
325
326
327
328
    IDEFICS = {
        "type": "idefics",
        "name": "Idefics",
        "url": "https://huggingface.co/HuggingFaceM4/idefics-9b",
        "multimodal": True,
    }
jixx's avatar
jixx committed
329
330
331
332
333
334
    MLLAMA = {
        "type": "mllama",
        "name": "Mllama",
        "url": "https://huggingface.co/meta-llama/Llama-3.2-11B-Vision-Instruct",
        "multimodal": True,
    }
jixx's avatar
init  
jixx committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349


__GLOBALS = locals()
for data in ModelType:
    __GLOBALS[data.name] = data.value["type"]


def get_model(
    model_id: str,
    lora_adapter_ids: Optional[List[str]],
    revision: Optional[str],
    sharded: bool,
    quantize: Optional[str],
    speculate: Optional[int],
    dtype: Optional[str],
jixx's avatar
jixx committed
350
    kv_cache_dtype: Optional[str],
jixx's avatar
init  
jixx committed
351
352
353
354
    trust_remote_code: bool,
    max_input_tokens: int,
) -> Model:
    global FLASH_ATTENTION
jixx's avatar
jixx committed
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

    config_dict, _ = PretrainedConfig.get_config_dict(
        model_id, revision=revision, trust_remote_code=trust_remote_code
    )
    model_type = config_dict.get("model_type", None)

    quantization_config = config_dict.get("quantization_config", None)
    compression_config = config_dict.get("compression_config", None)
    if quantization_config is not None and quantize is None:
        method = quantization_config.get("quant_method", None)
        config_groups = quantization_config.get("config_groups", None)
        if method in {"gptq", "awq", "exl2"}:
            log_master(logger.info, f"Auto selecting quantization method {method}")
            quantize = method
        elif method == "fbgemm_fp8" or method == "fp8":
            log_master(logger.info, "Auto selecting quantization method fp8")
            quantize = "fp8"
        elif config_groups is not None:
            # TODO: at some point we should probably fully parse the compression
            # configuration to know which parameters are compressed.
            for _, group in config_groups.items():
                weights_config = group.get("weights")
                if weights_config is not None:
                    if (
                        weights_config["type"] == "float"
                        and weights_config["num_bits"] == 8
                    ):
                        log_master(
                            logger.info, "Auto selecting quantization method fp8"
                        )
                        quantize = "fp8"
                        break
        else:
            log_master(logger.warning, f"Unknown quantization method {method}")
    elif compression_config is not None:
        # `compression_config` renamed to `quantization_config`; support retained for backward compatibility.
        config_groups = compression_config.get("config_groups")
        if config_groups is not None:
            for _, group in config_groups.items():
                weights_config = group.get("weights")
                if weights_config is not None:
                    if (
                        weights_config["type"] == "float"
                        and weights_config["num_bits"] == 8
                    ):
                        log_master(
                            logger.info, "Auto selecting quantization method fp8"
                        )
                        quantize = "fp8"
                        break

jixx's avatar
init  
jixx committed
406
407
    if dtype is None:
        if quantize in ["awq", "exl2", "gptq", "marlin"]:
jixx's avatar
jixx committed
408
409
410
411
412
            if SYSTEM == "ipex" and not hasattr(torch, "xpu"):
                dtype = torch.bfloat16
            else:
                # These quantizers only work with float16 params.
                dtype = torch.float16
jixx's avatar
init  
jixx committed
413
414
415
416
417
418
419
420
421
422
423
        else:
            # Keep it as default for now and let
            # every model resolve their own default dtype.
            dtype = None
    elif dtype == "float16":
        dtype = torch.float16
    elif dtype == "bfloat16":
        dtype = torch.bfloat16
    else:
        raise RuntimeError(f"Unknown dtype {dtype}")

jixx's avatar
jixx committed
424
425
426
427
428
429
430
431
432
    if kv_cache_dtype is None:
        kv_cache_dtype = dtype
    elif kv_cache_dtype == "fp8_e4m3fn":
        kv_cache_dtype = torch.float8_e4m3fn
    elif kv_cache_dtype == "fp8_e5m2":
        kv_cache_dtype = torch.float8_e5m2
    else:
        raise RuntimeError(f"Unknown kv_cache_dtype: {kv_cache_dtype}")

jixx's avatar
init  
jixx committed
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
    if speculate is not None:
        set_speculate(speculate)
    else:
        set_speculate(0)

    speculator = None
    if "medusa_num_heads" in config_dict:
        medusa_model_id = model_id
        medusa_revision = revision
        model_id = config_dict["base_model_name_or_path"]
        revision = "main"
        speculate_medusa = config_dict["medusa_num_heads"]
        if speculate is not None:
            if speculate > speculate_medusa:
                raise RuntimeError(
                    f"Speculate is set to `{speculate}` but this medusa models only has `{speculate_medusa}` heads, please make them match"
                )
            else:
                set_speculate(speculate)
        else:
            set_speculate(speculate_medusa)

        config_dict, _ = PretrainedConfig.get_config_dict(
            model_id, revision=revision, trust_remote_code=trust_remote_code
        )
        # Reload model type from parent.
        model_type = config_dict.get("model_type", None)
        is_local = Path(medusa_model_id).exists()
        if not is_local:
            medusa_config = hf_hub_download(
                medusa_model_id, revision=medusa_revision, filename="config.json"
            )
            hf_hub_download(
                medusa_model_id,
                revision=medusa_revision,
                filename="medusa_lm_head.safetensors",
            )
            speculator = {
                "path": Path(medusa_config).parent,
                "model_paths": ["medusa_lm_head.safetensors"],
            }
        else:
            speculator = {
                "path": Path(medusa_model_id),
                "model_paths": ["medusa_lm_head.safetensors"],
            }

        method = "medusa"
    elif model_type == "mlp_speculator":
        mlp_model_id = model_id
        mlp_revision = revision
        model_id = config_dict["base_model_name_or_path"]
        revision = "main"
        speculate_mlp = config_dict["n_predict"]
        if speculate is not None:
            if speculate > speculate_mlp:
                raise RuntimeError(
                    f"Speculate is set to `{speculate}` but this mlp_speculator models only has `{speculate_mlp}` heads, please make them match"
                )
            else:
                set_speculate(speculate)
        else:
            set_speculate(speculate_mlp)

        config_dict, _ = PretrainedConfig.get_config_dict(
            model_id, revision=revision, trust_remote_code=trust_remote_code
        )
        # Reload model type from parent.
        model_type = config_dict.get("model_type", None)
        is_local = Path(mlp_model_id).exists()
        extension = ".safetensors"
        if not is_local:
            mlp_speculator_config = hf_hub_download(
                mlp_model_id, revision=mlp_revision, filename="config.json"
            )
            api = HfApi()
            info = api.model_info(mlp_model_id, revision=mlp_revision)
            filenames = [
                s.rfilename
                for s in info.siblings
                if s.rfilename.endswith(extension)
                and len(s.rfilename.split("/")) == 1
                and "arguments" not in s.rfilename
                and "args" not in s.rfilename
                and "training" not in s.rfilename
            ]
            for filename in filenames:
                hf_hub_download(
                    mlp_model_id,
                    revision=mlp_revision,
                    filename=filename,
                )
jixx's avatar
jixx committed
525
526
527
528
529
            speculator_dir_path = Path(mlp_speculator_config).parent
            # if these are downloaded, they get converted to safetensors
            filenames.extend(
                [p for p in os.listdir(speculator_dir_path) if p.endswith(extension)]
            )
jixx's avatar
init  
jixx committed
530
531
532
533
534
535
536
537
538
539
540
541
542
543
            speculator = {
                "path": Path(mlp_speculator_config).parent,
                "model_paths": filenames,
            }
        else:
            speculator = Path(mlp_model_id)
            filenames = [p for p in os.listdir(speculator) if p.endswith(extension)]
            speculator = {"path": speculator, "model_paths": filenames}
        method = "mlp_speculator"
    else:
        method = "n-gram"

    speculate = get_speculate()
    if speculate > 0:
jixx's avatar
jixx committed
544
545
546
        log_master(
            logger.info, f"Using speculation {method} with {speculate} input ids."
        )
jixx's avatar
init  
jixx committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562

    if model_type is None:
        # TODO: fix how we determine model type for Mamba
        if "ssm_cfg" in config_dict:
            # *only happens in Mamba case
            model_type = "ssm"
        else:
            raise RuntimeError(
                f"Could not determine model type for {model_id} revision {revision}"
            )

    if quantize == "exl2" and sharded:
        raise RuntimeError(
            "Sharding is currently not supported with `exl2` quantization"
        )

jixx's avatar
jixx committed
563
564
565
566
567
568
569
570
571
572
573
    sliding_window = (
        config_dict.get("sliding_window")
        if config_dict.get("sliding_window") is not None
        else -1
    )

    use_sliding_window = sliding_window is not None and sliding_window != -1
    needs_sliding_window = (
        max_input_tokens is not None and max_input_tokens > sliding_window
    )
    if use_sliding_window and needs_sliding_window and not SUPPORTS_WINDOWING:
jixx's avatar
init  
jixx committed
574
575
576
577
        raise ValueError(
            f"The backend {SYSTEM} does not support sliding window attention that is used by the model type {model_type}. To use this model nonetheless with the {SYSTEM} backend, please launch TGI with the argument `--max-input-tokens` smaller than sliding_window={sliding_window} (got here max_input_tokens={max_input_tokens})."
        )

jixx's avatar
jixx committed
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
    if model_type == DEEPSEEK_V2:
        if FLASH_ATTENTION:
            head_size = max(
                config_dict.get("qk_nope_dim", 128)
                + config_dict.get("qk_rope_dim", 64),
                config_dict.get("v_head_dim", 128),
            )
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashDeepseekV2ForCausalLM,
                revision=revision,
                quantize=quantize,
                speculator=speculator,
                default_dtype=torch.bfloat16,
                dtype=dtype,
                kv_cache_dtype=kv_cache_dtype,
                trust_remote_code=trust_remote_code,
                lora_adapter_ids=lora_adapter_ids,
                config_class=DeepseekV2Config,
                head_size=head_size,
            )
        elif sharded:
            raise NotImplementedError(
                FLASH_ATT_ERROR_MESSAGE.format("Sharded Deepseek V2")
            )
        else:
            return CausalLM.fallback(
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
    elif model_type == MAMBA:
jixx's avatar
init  
jixx committed
613
614
615
616
617
618
619
620
621
622
        return Mamba(
            model_id,
            revision,
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
        )

    if model_id.startswith("facebook/galactica"):
jixx's avatar
jixx committed
623
624
625
626
627
        return CausalLM(
            model_id=model_id,
            # Yes galactica is just an OPT model.
            model_class=OPTForCausalLM,
            revision=revision,
jixx's avatar
init  
jixx committed
628
629
630
631
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
632
            batch_class=GalacticaCausalLMBatch,
jixx's avatar
init  
jixx committed
633
634
635
636
637
638
639
640
        )

    if (
        model_type == GPT_BIGCODE
        or model_type == GPT2
        and model_id.startswith("bigcode/")
    ):
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
641
642
643
644
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashSantacoderForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
645
646
647
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
648
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
649
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
650
651
652
                lora_adapter_ids=lora_adapter_ids,
                aliases={"transformer.wte.weight": ["lm_head.weight"]},
                num_kv_heads=1,
jixx's avatar
init  
jixx committed
653
654
655
656
657
658
            )
        elif sharded:
            raise NotImplementedError(
                FLASH_ATT_ERROR_MESSAGE.format("Sharded Santacoder")
            )
        else:
jixx's avatar
jixx committed
659
660
661
            return CausalLM.fallback(
                model_id=model_id,
                revision=revision,
jixx's avatar
init  
jixx committed
662
663
664
665
666
667
668
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type == BLOOM:
jixx's avatar
jixx committed
669
670
671
672
        return CausalLM(
            model_id=model_id,
            model_class=BloomForCausalLM,
            revision=revision,
jixx's avatar
init  
jixx committed
673
674
675
676
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
677
            batch_class=BloomCausalLMBatch,
jixx's avatar
init  
jixx committed
678
679
        )
    elif model_type == MPT:
jixx's avatar
jixx committed
680
681
682
683
        return CausalLM(
            model_id=model_id,
            model_class=MPTForCausalLM,
            revision=revision,
jixx's avatar
init  
jixx committed
684
685
686
687
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
688
            batch_class=CausalLMBatchKeysLast,
jixx's avatar
init  
jixx committed
689
690
691
692
        )
    elif model_type == GPT2:
        if FLASH_ATTENTION:
            try:
jixx's avatar
jixx committed
693
694
695
696
                return FlashCausalLM(
                    model_id=model_id,
                    model_class=FlashGPT2ForCausalLM,
                    revision=revision,
jixx's avatar
init  
jixx committed
697
698
699
                    quantize=quantize,
                    speculator=speculator,
                    dtype=dtype,
jixx's avatar
jixx committed
700
                    kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
701
                    trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
702
                    lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
703
704
705
                )
            except RuntimeError as e:
                # Lots of legacy models with various weight names.
jixx's avatar
jixx committed
706
707
                log_master(logger.warning, f"Couldn't load flash gpt2 variant: {e}")
                return CausalLM.fallback(
jixx's avatar
init  
jixx committed
708
709
710
711
712
713
714
715
716
717
                    model_id,
                    revision,
                    quantize=quantize,
                    speculator=speculator,
                    dtype=dtype,
                    trust_remote_code=trust_remote_code,
                )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded GPT-2"))
        else:
jixx's avatar
jixx committed
718
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
719
720
721
722
723
724
725
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
jixx's avatar
jixx committed
726
    elif model_type == GPTJ:
jixx's avatar
init  
jixx committed
727
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
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
            try:
                return FlashCausalLM(
                    model_id=model_id,
                    model_class=FlashGPTJForCausalLM,
                    revision=revision,
                    quantize=quantize,
                    speculator=speculator,
                    dtype=dtype,
                    kv_cache_dtype=kv_cache_dtype,
                    trust_remote_code=trust_remote_code,
                    lora_adapter_ids=lora_adapter_ids,
                )
            except RuntimeError as e:
                # Lots of legacy models with various weight names.
                log_master(logger.warning, f"Couldn't load flash gptj variant: {e}")
                return CausalLM.fallback(
                    model_id,
                    revision,
                    quantize=quantize,
                    speculator=speculator,
                    dtype=dtype,
                    trust_remote_code=trust_remote_code,
                )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded GPT-J"))
        else:
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
755
756
757
758
759
760
761
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
jixx's avatar
jixx committed
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    elif model_type == GPT_NEOX:
        if FLASH_ATTENTION:
            from text_generation_server.models.custom_modeling.flash_neox_modeling import (
                GPTNeoXConfig,
            )

            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashGPTNeoXForCausalLM,
                revision=revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                kv_cache_dtype=kv_cache_dtype,
                trust_remote_code=trust_remote_code,
                lora_adapter_ids=lora_adapter_ids,
                config_class=GPTNeoXConfig,
            )
jixx's avatar
init  
jixx committed
780
        elif sharded:
jixx's avatar
jixx committed
781
782
783
784
            return CausalLM(
                model_id=model_id,
                model_class=GPTNeoxForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
785
786
787
788
789
790
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
        else:
jixx's avatar
jixx committed
791
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
792
793
794
795
796
797
798
799
800
801
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    elif model_type == PHI:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
802
803
804
805
806
807
808
809
810
811
812
813
814
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashPhiForCausalLM,
                revision=revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                kv_cache_dtype=kv_cache_dtype,
                trust_remote_code=trust_remote_code,
                lora_adapter_ids=lora_adapter_ids,
            )
        else:
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
815
816
817
818
819
820
821
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
jixx's avatar
jixx committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836

    elif model_type == PHI_MOE:
        if FLASH_ATTENTION:
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashLlamaForCausalLM,
                config_class=PhiMoEConfig,
                revision=revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                kv_cache_dtype=kv_cache_dtype,
                trust_remote_code=trust_remote_code,
                lora_adapter_ids=lora_adapter_ids,
            )
jixx's avatar
init  
jixx committed
837
        else:
jixx's avatar
jixx committed
838
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
839
840
841
842
843
844
845
846
847
848
849
850
851
852
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    elif model_type == "phi-msft":
        if FLASH_ATTENTION:
            raise NotImplementedError(
                "Legacy phi-msft is not supported with Flash Attention"
            )
        else:
jixx's avatar
jixx committed
853
854
855
856
857
            return CausalLM(
                model_id=model_id,
                model_class=PhiForCausalLM,
                config_class=PhiConfig,
                revision=revision,
jixx's avatar
init  
jixx committed
858
859
860
861
862
863
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

jixx's avatar
jixx committed
864
865
866
867
868
869
    elif (
        model_type == LLAMA
        or model_type == BAICHUAN
        or model_type == PHI3
        or model_type == GRANITE
    ):
jixx's avatar
init  
jixx committed
870
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
871
872
873
874
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashLlamaForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
875
876
877
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
878
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
879
880
881
882
                trust_remote_code=trust_remote_code,
                lora_adapter_ids=lora_adapter_ids,
            )
        elif sharded:
jixx's avatar
jixx committed
883
884
885
            raise NotImplementedError(
                FLASH_ATT_ERROR_MESSAGE.format(f"Sharded {model_type}")
            )
jixx's avatar
init  
jixx committed
886
        else:
jixx's avatar
jixx committed
887
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
888
889
890
891
892
893
894
895
896
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
    if model_type == GEMMA:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
897
898
899
900
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashGemmaForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
901
902
903
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
904
905
906
                kv_cache_dtype=kv_cache_dtype,
                # Works better for these models
                default_dtype=torch.bfloat16,
jixx's avatar
init  
jixx committed
907
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
908
                lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
909
910
911
912
            )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded Gemma"))
        else:
jixx's avatar
jixx committed
913
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
914
915
916
917
918
919
920
921
922
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
    elif model_type == GEMMA2:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
923
924
925
926
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashGemma2ForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
927
928
929
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
930
931
932
                kv_cache_dtype=kv_cache_dtype,
                # Works better for these models
                default_dtype=torch.bfloat16,
jixx's avatar
init  
jixx committed
933
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
934
                lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
935
936
937
938
            )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded Gemma2"))
        else:
jixx's avatar
jixx committed
939
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
940
941
942
943
944
945
946
947
948
949
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type == COHERE:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
950
951
952
953
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashCohereForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
954
955
956
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
957
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
958
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
959
                lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
960
961
962
963
            )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded Cohere"))
        else:
jixx's avatar
jixx committed
964
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
965
966
967
968
969
970
971
972
973
974
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type == DBRX:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
975
976
977
978
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashDbrxForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
979
980
981
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
982
983
984
                kv_cache_dtype=kv_cache_dtype,
                # Dbrx works better in bfloat16.
                default_dtype=torch.bfloat16,
jixx's avatar
init  
jixx committed
985
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
986
987
                lora_adapter_ids=lora_adapter_ids,
                config_class=DbrxConfig,
jixx's avatar
init  
jixx committed
988
989
990
991
            )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded DBRX"))
        else:
jixx's avatar
jixx committed
992
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type in ["RefinedWeb", "RefinedWebModel", FALCON]:
        if sharded:
            if FLASH_ATTENTION:
                if config_dict.get("alibi", False):
                    raise NotImplementedError("sharded is not supported for this model")
jixx's avatar
jixx committed
1006
1007
1008
1009
                return FlashCausalLM(
                    model_id=model_id,
                    model_class=FlashRWForCausalLM,
                    revision=revision,
jixx's avatar
init  
jixx committed
1010
1011
1012
                    quantize=quantize,
                    speculator=speculator,
                    dtype=dtype,
jixx's avatar
jixx committed
1013
1014
1015
1016
1017
                    kv_cache_dtype=kv_cache_dtype,
                    aliases={
                        "lm_head.weight": ["transformer.word_embeddings.weight"],
                        "transformer.word_embeddings.weight": ["lm_head.weight"],
                    },
jixx's avatar
init  
jixx committed
1018
                    trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1019
1020
                    lora_adapter_ids=lora_adapter_ids,
                    config_class=RWConfig,
jixx's avatar
init  
jixx committed
1021
                )
jixx's avatar
jixx committed
1022
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded Falcon"))
jixx's avatar
init  
jixx committed
1023
1024
        else:
            if FLASH_ATTENTION and not config_dict.get("alibi", False):
jixx's avatar
jixx committed
1025
1026
1027
1028
                return FlashCausalLM(
                    model_id=model_id,
                    model_class=FlashRWForCausalLM,
                    revision=revision,
jixx's avatar
init  
jixx committed
1029
1030
1031
                    quantize=quantize,
                    speculator=speculator,
                    dtype=dtype,
jixx's avatar
jixx committed
1032
1033
1034
1035
1036
                    kv_cache_dtype=kv_cache_dtype,
                    aliases={
                        "lm_head.weight": ["transformer.word_embeddings.weight"],
                        "transformer.word_embeddings.weight": ["lm_head.weight"],
                    },
jixx's avatar
init  
jixx committed
1037
                    trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1038
1039
                    lora_adapter_ids=lora_adapter_ids,
                    config_class=RWConfig,
jixx's avatar
init  
jixx committed
1040
1041
                )
            else:
jixx's avatar
jixx committed
1042
                return CausalLM.fallback(
jixx's avatar
init  
jixx committed
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
                    model_id,
                    revision,
                    quantize=quantize,
                    speculator=speculator,
                    dtype=dtype,
                    trust_remote_code=trust_remote_code,
                )

    if model_type == MISTRAL:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1053
1054
1055
1056
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashMistralForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
1057
1058
1059
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
1060
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
1061
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1062
                lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
1063
1064
1065
1066
            )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded Mistral"))
        else:
jixx's avatar
jixx committed
1067
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type == MIXTRAL:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1078
1079
1080
1081
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashMixtralForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
1082
1083
1084
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
1085
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
1086
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1087
                lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
1088
1089
1090
1091
            )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded Mixtral"))
        else:
jixx's avatar
jixx committed
1092
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type == STARCODER2:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1103
1104
1105
1106
            return FlashCausalLM(
                model_id=model_id,
                model_class=FlashStarcoder2ForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
1107
                quantize=quantize,
jixx's avatar
jixx committed
1108
                speculator=speculator,
jixx's avatar
init  
jixx committed
1109
                dtype=dtype,
jixx's avatar
jixx committed
1110
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
1111
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1112
                lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
1113
1114
1115
1116
1117
1118
            )
        elif sharded:
            raise NotImplementedError(
                FLASH_ATT_ERROR_MESSAGE.format("Sharded Starcoder2")
            )
        else:
jixx's avatar
jixx committed
1119
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type == QWEN2:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1130
1131
1132
1133
            return FlashCausalLM(
                model_id=model_id,
                model_class=Qwen2ForCausalLM,
                revision=revision,
jixx's avatar
init  
jixx committed
1134
                quantize=quantize,
jixx's avatar
jixx committed
1135
                speculator=speculator,
jixx's avatar
init  
jixx committed
1136
                dtype=dtype,
jixx's avatar
jixx committed
1137
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
1138
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1139
                lora_adapter_ids=lora_adapter_ids,
jixx's avatar
init  
jixx committed
1140
1141
1142
1143
            )
        elif sharded:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Sharded Qwen2"))
        else:
jixx's avatar
jixx committed
1144
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
1145
1146
1147
1148
1149
1150
1151
1152
1153
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    if model_type == OPT:
jixx's avatar
jixx committed
1154
1155
1156
1157
        return CausalLM(
            model_id=model_id,
            model_class=OPTForCausalLM,
            revision=revision,
jixx's avatar
init  
jixx committed
1158
1159
1160
1161
1162
1163
1164
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
        )

    if model_type == T5:
jixx's avatar
jixx committed
1165
1166
1167
1168
        return Seq2SeqLM(
            model_id=model_id,
            model_class=T5ForConditionalGeneration,
            revision=revision,
jixx's avatar
init  
jixx committed
1169
1170
1171
1172
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1173
1174
1175
1176
1177
1178
            aliases={
                "shared.weight": [
                    "encoder.embed_tokens.weight",
                    "decoder.embed_tokens.weight",
                ]
            },
jixx's avatar
init  
jixx committed
1179
1180
1181
        )
    if model_type == IDEFICS:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1182
            return IdeficsCausalLM(
jixx's avatar
init  
jixx committed
1183
1184
1185
1186
1187
1188
1189
1190
1191
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
        else:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Idefics"))
jixx's avatar
jixx committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
    if model_type == MLLAMA:
        if FLASH_ATTENTION:
            return MllamaCausalLM(
                model_id=model_id,
                model_class=MllamaForConditionalGeneration,
                batch_class=MllamaCausalLMBatch,
                revision=revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                default_dtype=torch.bfloat16,
                trust_remote_code=trust_remote_code,
                lora_adapter_ids=lora_adapter_ids,
            )
        else:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Mllama"))
jixx's avatar
init  
jixx committed
1208
1209
    if model_type == IDEFICS2:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1210
1211
1212
1213
            return VlmCausalLM(
                model_id=model_id,
                model_class=Idefics2ForConditionalGeneration,
                revision=revision,
jixx's avatar
init  
jixx committed
1214
1215
1216
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
1217
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
1218
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1219
1220
1221
1222
                lora_adapter_ids=lora_adapter_ids,
                # XXX: Extremely important to cap resolution in order to limit
                # VRAM usage.
                processor_kwargs={"size": {"longest_edge": 448, "shortest_edge": 378}},
jixx's avatar
init  
jixx committed
1223
1224
1225
            )
        else:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Idefics"))
jixx's avatar
jixx committed
1226
    if model_type == PALIGEMMA:
jixx's avatar
init  
jixx committed
1227
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1228
1229
1230
1231
            return VlmCausalLM(
                model_id=model_id,
                model_class=PaliGemmaForConditionalGeneration,
                revision=revision,
jixx's avatar
init  
jixx committed
1232
1233
1234
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
1235
1236
1237
                kv_cache_dtype=kv_cache_dtype,
                # Works better for these models
                default_dtype=torch.bfloat16,
jixx's avatar
init  
jixx committed
1238
                trust_remote_code=trust_remote_code,
jixx's avatar
jixx committed
1239
1240
                lora_adapter_ids=lora_adapter_ids,
                batch_class=PaliGemmaBatch,
jixx's avatar
init  
jixx committed
1241
1242
1243
1244
1245
1246
            )
        else:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("Idefics"))

    if model_type == LLAVA_NEXT:
        if FLASH_ATTENTION:
jixx's avatar
jixx committed
1247
1248
1249
1250
            return VlmCausalLM(
                model_class=LlavaNextForConditionalGeneration,
                model_id=model_id,
                revision=revision,
jixx's avatar
init  
jixx committed
1251
1252
1253
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
jixx's avatar
jixx committed
1254
                kv_cache_dtype=kv_cache_dtype,
jixx's avatar
init  
jixx committed
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
                trust_remote_code=trust_remote_code,
            )
        else:
            raise NotImplementedError(FLASH_ATT_ERROR_MESSAGE.format("LlavaNext"))

    if sharded:
        raise NotImplementedError("sharded is not supported for AutoModel")
    if quantize == "gptq":
        raise NotImplementedError(
            "gptq quantization is not supported for AutoModel, you can try to quantize it with `text-generation-server quantize ORIGINAL_MODEL_ID NEW_MODEL_ID`"
        )
    if quantize == "awq":
        raise NotImplementedError("awq quantization is not supported for AutoModel")
    elif (quantize == "bitsandbytes-fp4") or (quantize == "bitsandbytes-nf4"):
        raise NotImplementedError("4bit quantization is not supported for AutoModel")
    elif quantize == "eetq":
        raise NotImplementedError("Eetq quantization is not supported for AutoModel")
    elif quantize == "exl2":
        raise NotImplementedError("exl2 quantization is not supported for AutoModel")
    if model_type in modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:
jixx's avatar
jixx committed
1275
        return CausalLM.fallback(
jixx's avatar
init  
jixx committed
1276
1277
1278
1279
1280
1281
1282
1283
            model_id,
            revision,
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
        )
    if model_type in modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:
jixx's avatar
jixx committed
1284
        return Seq2SeqLM.fallback(
jixx's avatar
init  
jixx committed
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
            model_id,
            revision,
            quantize=quantize,
            speculator=speculator,
            dtype=dtype,
            trust_remote_code=trust_remote_code,
        )

    auto_map = config_dict.get("auto_map", None)
    if trust_remote_code and auto_map is not None:
        if "AutoModelForCausalLM" in auto_map.keys():
jixx's avatar
jixx committed
1296
            return CausalLM.fallback(
jixx's avatar
init  
jixx committed
1297
1298
1299
1300
1301
1302
1303
1304
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )
        if "AutoModelForSeq2SeqLM" in auto_map.keys():
jixx's avatar
jixx committed
1305
            return Seq2SeqLM.fallback(
jixx's avatar
init  
jixx committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
                model_id,
                revision,
                quantize=quantize,
                speculator=speculator,
                dtype=dtype,
                trust_remote_code=trust_remote_code,
            )

    raise ValueError(f"Unsupported model type {model_type}")
jixx's avatar
jixx committed
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430


# get_model_with_lora_adapters wraps the internal get_model function and adds support for loading adapters
# this provides a post model loading hook to load adapters into the model after the model has been loaded
def get_model_with_lora_adapters(
    model_id: str,
    lora_adapters: Optional[List[AdapterInfo]],
    revision: Optional[str],
    sharded: bool,
    quantize: Optional[str],
    speculate: Optional[int],
    dtype: Optional[str],
    kv_cache_dtype: Optional[str],
    trust_remote_code: bool,
    max_input_tokens: int,
    adapter_to_index: Dict[str, int],
):
    lora_adapter_ids = [adapter.id for adapter in lora_adapters]
    model = get_model(
        model_id,
        lora_adapter_ids,
        revision,
        sharded,
        quantize,
        speculate,
        dtype,
        kv_cache_dtype,
        trust_remote_code,
        max_input_tokens,
    )

    if len(lora_adapters) > 0:
        target_to_layer = build_layer_weight_lookup(model.model)

        for index, adapter in enumerate(lora_adapters):
            # The AdapterParameters object allows for merging multiple adapters into a single adapter.
            # At the moment, we only support loading a single adapter into the model, but we keep the
            # AdapterParameters object for easier extension in the future.
            adapter_parameters = AdapterParameters(
                adapter_info=[adapter],
                # when merging multiple adapters we can weight them differently
                # if this is not set, all adapters will be weighted equally
                # see: text_generation_server.utils.merges.strategies for impl
                weights=None,
                merge_strategy=0,
                density=1.0,
                majority_sign_method=0,
            )

            adapter_index = index + 1
            adapter_to_index[adapter.id] = adapter_index

            logger.info(
                f"Loading adapter weights into model: {','.join([adapter.id for adapter in adapter_parameters.adapter_info])}"
            )
            weight_names = tuple([v[0] for v in target_to_layer.values()])
            (
                module_map,
                adapter_config,
                adapter_weight_names,
                adapter_tokenizer,
            ) = load_and_merge_adapters(
                model.model_id,
                adapter_parameters,
                adapter_index,
                weight_names,
                False,
            )

            unused_weight_names = adapter_weight_names.copy()

            adapter_layers = [
                "q_proj",
                "k_proj",
                "v_proj",
                "o_proj",
                "gate_proj",
                "up_proj",
                "down_proj",
                "qkv_proj",
            ]

            for layer_name in adapter_layers:
                nlayers = (
                    1 if layer_name == "lm_head" else len(model.model.model.layers)
                )
                adapter_weights = LoraWeights.prepare_weights(
                    config=adapter_config,
                    module_map=module_map,
                    layer_type=layer_name,
                    unused_weight_names=unused_weight_names,
                    nlayers=nlayers,
                    dtype=model.dtype,
                    world_size=model.world_size,
                    process_group=model.process_group,
                    target_to_layer=target_to_layer,
                )

                if adapter_weights is None:
                    continue

                model.layer_to_adapter_weights[layer_name].add_adapter(
                    adapter_index, adapter_weights
                )

            if len(unused_weight_names) > 0:
                logger.warning(
                    f"{','.join([a.id for a in lora_adapters])} unused adapter weights: {unused_weight_names}"
                )

            if adapter_tokenizer is not None:
                model.tokenizers.add_tokenizer(adapter_index, adapter_tokenizer)

            model.loaded_adapters.add(adapter_index)

    return model