utils.py 6.53 KB
Newer Older
1
import concurrent
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
2
3
4
import os
import torch
import torch.distributed
Olivier Dehaene's avatar
Olivier Dehaene committed
5
6

from datetime import timedelta
Nicolas Patry's avatar
Nicolas Patry committed
7

8
from concurrent.futures import ThreadPoolExecutor
Nicolas Patry's avatar
Nicolas Patry committed
9
10
11
12
from functools import partial
from huggingface_hub import HfApi, hf_hub_download, try_to_load_from_cache
from huggingface_hub.utils import LocalEntryNotFoundError
from tqdm import tqdm
13
14
from typing import List, Optional, Tuple
from transformers import AutoTokenizer
15
from transformers.generation.logits_process import (
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
16
17
18
19
20
21
    LogitsProcessorList,
    TemperatureLogitsWarper,
    TopPLogitsWarper,
    TopKLogitsWarper,
)

22
23
from text_generation.pb import generate_pb2

Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
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

class Sampling:
    def __call__(self, logits):
        probs = torch.nn.functional.softmax(logits, dim=-1)
        next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
        return next_tokens


class Greedy:
    def __call__(self, logits):
        return logits.argmax(dim=-1)


class NextTokenChooser:
    def __init__(self, temperature=1.0, top_k=None, top_p=None, do_sample=False):
        warpers = LogitsProcessorList()
        # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files
        # all samplers can be found in `generation_utils_samplers.py`
        sampling = do_sample
        if temperature is not None and temperature != 1.0:
            temperature = float(temperature)
            warpers.append(TemperatureLogitsWarper(temperature))
            sampling = True
        if top_k is not None and top_k != 0:
            warpers.append(TopKLogitsWarper(top_k=top_k))
            sampling = True
        if top_p is not None and top_p < 1.0:
            warpers.append(TopPLogitsWarper(top_p=top_p))
            sampling = True

        self.warpers = warpers
        self.choice = Sampling() if sampling else Greedy()

    def __call__(self, input_ids, scores):
OlivierDehaene's avatar
OlivierDehaene committed
58
        # Warp logits
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
59
        scores = self.warpers(input_ids, scores)
OlivierDehaene's avatar
OlivierDehaene committed
60
61
62
        # Compute logprobs
        logprobs = torch.log_softmax(scores, -1)
        # Choose tokens
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
63
        next_ids = self.choice(scores)
OlivierDehaene's avatar
OlivierDehaene committed
64
        return next_ids, logprobs
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
65

66
    @classmethod
OlivierDehaene's avatar
OlivierDehaene committed
67
    def from_pb(cls, pb: generate_pb2.NextTokenChooserParameters) -> "NextTokenChooser":
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
        return NextTokenChooser(
            temperature=pb.temperature,
            top_k=pb.top_k,
            top_p=pb.top_p,
            do_sample=pb.do_sample,
        )


class StopSequenceCriteria:
    def __init__(self, tokens: List[int]):
        if not tokens:
            raise ValueError("tokens cannot be empty")

        self.tokens = tokens
        self.current_token_idx = 0

    def __call__(self, last_token: int) -> bool:
        if last_token == self.tokens[self.current_token_idx]:
            # Increase idx to go to next token
            self.current_token_idx += 1
        else:
            # Reset to first token of the stopping sequence
            self.current_token_idx = 0

        if self.current_token_idx == len(self.tokens):
            # We matched the entire sequence without resetting
            return True
        return False

Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
97
98

class StoppingCriteria:
99
100
101
102
    def __init__(
        self, stop_sequence_criterias: List[StopSequenceCriteria], max_new_tokens=20
    ):
        self.stop_sequence_criterias = stop_sequence_criterias
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
103
104
105
        self.max_new_tokens = max_new_tokens
        self.current_tokens = 0

106
    def __call__(self, all_ids) -> Tuple[bool, Optional[str]]:
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
107
108
        self.current_tokens += 1
        if self.current_tokens >= self.max_new_tokens:
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
            return True, "length"

        last_token = all_ids[-1]
        for stop_sequence_criteria in self.stop_sequence_criterias:
            if stop_sequence_criteria(last_token):
                return True, "stop_sequence"

        return False, None

    @classmethod
    def from_pb(
        cls, pb: generate_pb2.StoppingCriteriaParameters, tokenizer: AutoTokenizer
    ) -> "StoppingCriteria":
        stop_sequence_criterias = []
        for stop_sequence in pb.stop_sequences:
            tokens = tokenizer(
                stop_sequence, padding=False, return_attention_mask=False
            ).input_ids
            if tokens:
                stop_sequence_criterias.append(StopSequenceCriteria(tokens))
        stop_sequence_criterias.append(StopSequenceCriteria([tokenizer.eos_token_id]))

        return StoppingCriteria(stop_sequence_criterias, pb.max_new_tokens)
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152


def initialize_torch_distributed():
    rank = int(os.getenv("RANK", "0"))
    world_size = int(os.getenv("WORLD_SIZE", "1"))

    if torch.cuda.is_available():
        # initialized `torch.distributed`
        # Set the device id.
        assert world_size <= torch.cuda.device_count(), "Each process is one gpu"
        device = rank % torch.cuda.device_count()
        torch.cuda.set_device(device)
        backend = "nccl"
    else:
        backend = "gloo"

    # Call the init process.
    torch.distributed.init_process_group(
        backend=backend,
        world_size=world_size,
        rank=rank,
Olivier Dehaene's avatar
Olivier Dehaene committed
153
        timeout=timedelta(seconds=60),
Olivier Dehaene's avatar
Init  
Olivier Dehaene committed
154
155
156
157
158
    )

    return torch.distributed.distributed_c10d._get_default_group(), rank, world_size


159
def weight_hub_files(model_name, extension=".safetensors"):
Nicolas Patry's avatar
Nicolas Patry committed
160
161
162
    """Get the safetensors filenames on the hub"""
    api = HfApi()
    info = api.model_info(model_name)
163
    filenames = [s.rfilename for s in info.siblings if s.rfilename.endswith(extension)]
Nicolas Patry's avatar
Nicolas Patry committed
164
165
166
    return filenames


167
def weight_files(model_name, extension=".safetensors"):
Nicolas Patry's avatar
Nicolas Patry committed
168
    """Get the local safetensors filenames"""
169
    filenames = weight_hub_files(model_name, extension)
Nicolas Patry's avatar
Nicolas Patry committed
170
171
172
173
174
175
176
    files = []
    for filename in filenames:
        cache_file = try_to_load_from_cache(model_name, filename=filename)
        if cache_file is None:
            raise LocalEntryNotFoundError(
                f"File {filename} of model {model_name} not found in "
                f"{os.getenv('HUGGINGFACE_HUB_CACHE', 'the local cache')}. "
177
                f"Please run `text-generation-server download-weights {model_name}` first."
Nicolas Patry's avatar
Nicolas Patry committed
178
179
180
181
182
183
            )
        files.append(cache_file)

    return files


184
def download_weights(model_name, extension=".safetensors"):
Nicolas Patry's avatar
Nicolas Patry committed
185
    """Download the safetensors files from the hub"""
186
    filenames = weight_hub_files(model_name, extension)
Nicolas Patry's avatar
Nicolas Patry committed
187
188

    download_function = partial(
189
190
191
        hf_hub_download,
        repo_id=model_name,
        local_files_only=False,
Nicolas Patry's avatar
Nicolas Patry committed
192
    )
193
194

    executor = ThreadPoolExecutor(max_workers=5)
195
196
197
198
    futures = [
        executor.submit(download_function, filename=filename) for filename in filenames
    ]
    files = [
199
200
        future.result()
        for future in tqdm(concurrent.futures.as_completed(futures), total=len(futures))
201
    ]
202

Nicolas Patry's avatar
Nicolas Patry committed
203
    return files