flash_llama.py 2.59 KB
Newer Older
1
2
3
4
import torch
import torch.distributed

from opentelemetry import trace
5
6
from transformers import AutoConfig, AutoTokenizer
from transformers.models.llama import LlamaTokenizer
7
from typing import Optional
8
9
10
11

from text_generation_server.models import FlashCausalLM
from text_generation_server.models.custom_modeling.flash_llama_modeling import (
    FlashLlamaForCausalLM,
12
    LlamaConfig,
13
14
15
16
)
from text_generation_server.utils import (
    initialize_torch_distributed,
    weight_files,
17
    Weights,
18
19
20
21
22
23
24
)

tracer = trace.get_tracer(__name__)


class FlashLlama(FlashCausalLM):
    def __init__(
25
26
27
28
        self,
        model_id: str,
        revision: Optional[str] = None,
        quantize: Optional[str] = None,
29
        dtype: Optional[torch.dtype] = None,
30
        trust_remote_code: bool = False,
31
    ):
32
        self.process_group, rank, world_size = initialize_torch_distributed()
33
        if torch.cuda.is_available():
34
            device = torch.device(f"cuda:{rank}")
35
            dtype = torch.float16 if dtype is None else dtype
36
37
38
        else:
            raise NotImplementedError("FlashLlama is only available on GPU")

39
40
41
42
43
44
45
46
47
        try:
            tokenizer = LlamaTokenizer.from_pretrained(
                model_id,
                revision=revision,
                padding_side="left",
                truncation_side="left",
                trust_remote_code=trust_remote_code,
            )
        except Exception:
48
            tokenizer = AutoTokenizer.from_pretrained(
49
50
51
52
53
54
                model_id,
                revision=revision,
                padding_side="left",
                truncation_side="left",
                trust_remote_code=trust_remote_code,
            )
55

56
        config = LlamaConfig.from_pretrained(
57
            model_id, revision=revision, trust_remote_code=trust_remote_code
58
        )
59
        config.quantize = quantize
60
61

        torch.distributed.barrier(group=self.process_group)
62

63
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
64
        weights = Weights(filenames, device, dtype, process_group=self.process_group)
65
66
        if config.quantize == "gptq":
            weights._set_gptq_params(model_id)
67

68
        model = FlashLlamaForCausalLM(config, weights)
69
70

        torch.distributed.barrier(group=self.process_group)
71
        super(FlashLlama, self).__init__(
72
            model=model,
73
            tokenizer=tokenizer,
74
            num_layers=len(model.model.layers),
75
            num_kv_heads=model.model.num_key_value_heads,
76
            head_size=model.model.head_size,
77
            dtype=dtype,
78
            device=device,
79
80
            rank=rank,
            world_size=world_size,
81
        )