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

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

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

tracer = trace.get_tracer(__name__)


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

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

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

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

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

67
        model = FlashLlamaForCausalLM(config, weights)
68
69

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