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

from opentelemetry import trace
from transformers import AutoConfig
6
from transformers.models.llama import LlamaTokenizer, LlamaTokenizerFast
7
from typing import Optional
8
9
10
11
12
13
14
15

from text_generation_server.models import FlashCausalLM
from text_generation_server.models.custom_modeling.flash_llama_modeling import (
    FlashLlamaForCausalLM,
)
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 = AutoConfig.from_pretrained(
56
            model_id, revision=revision, trust_remote_code=trust_remote_code
57
58
59
        )

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

61
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
62
        weights = Weights(filenames, device, dtype, process_group=self.process_group)
63

64
65
        config.quantize = quantize
        model = FlashLlamaForCausalLM(config, weights)
66
67

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