-
Notifications
You must be signed in to change notification settings - Fork 208
/
huggingface_local.py
165 lines (132 loc) · 5.31 KB
/
huggingface_local.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
58
59
60
61
62
63
64
65
66
67
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
97
98
99
100
101
102
103
104
105
106
107
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import logging
from typing import Optional, Sequence
import numpy as np
import torch
import transformers
from peft import PeftModel
from torch.utils.data import Dataset
from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer
from .. import constants, utils
__all__ = ["huggingface_local_completions"]
class ListDataset(Dataset):
def __init__(self, original_list):
self.original_list = original_list
def __len__(self):
return len(self.original_list)
def __getitem__(self, i):
return self.original_list[i]
def huggingface_local_completions(
prompts: Sequence[str],
model_name: str,
do_sample: bool = False,
batch_size: int = 1,
model_kwargs=None,
cache_dir: Optional[str] = constants.DEFAULT_CACHE_DIR,
remove_ending: Optional[str] = None,
is_fast_tokenizer: bool = True,
adapters_name: Optional[str] = None,
**kwargs,
) -> dict[str, list]:
"""Decode locally using huggingface transformers pipeline.
Parameters
----------
prompts : list of str
Prompts to get completions for.
model_name : str, optional
Name of the model (repo on hugging face hub) to use for decoding.
do_sample : bool, optional
Whether to use sampling for decoding.
batch_size : int, optional
Batch size to use for decoding. This currently does not work well with to_bettertransformer.
model_kwargs : dict, optional
Additional kwargs to pass to from_pretrained.
cache_dir : str, optional
Directory to use for caching the model.
remove_ending : str, optional
The ending string to be removed from completions. Typically eos_token.
kwargs :
Additional kwargs to pass to `InferenceClient.__call__`.
"""
model_kwargs = model_kwargs or {}
if "device_map" not in model_kwargs:
model_kwargs["device_map"] = "auto"
if "torch_dtype" in model_kwargs and isinstance(model_kwargs["torch_dtype"], str):
model_kwargs["torch_dtype"] = getattr(torch, model_kwargs["torch_dtype"])
n_examples = len(prompts)
if n_examples == 0:
logging.info("No samples to annotate.")
return []
else:
logging.info(f"Using `huggingface_local_completions` on {n_examples} prompts using {model_name}.")
if not torch.cuda.is_available():
model_kwargs["load_in_8bit"] = False
model_kwargs["torch_dtype"] = None
# faster but slightly less accurate matrix multiplications
torch.backends.cuda.matmul.allow_tf32 = torch.backends.cudnn.allow_tf32 = True
tokenizer = AutoTokenizer.from_pretrained(
model_name,
cache_dir=cache_dir,
padding_side="left",
use_fast=is_fast_tokenizer,
**model_kwargs,
)
model = AutoModelForCausalLM.from_pretrained(model_name, cache_dir=cache_dir, **model_kwargs).eval()
if adapters_name:
logging.info(f"Merging adapter from {adapters_name}.")
model = PeftModel.from_pretrained(model, adapters_name)
model = model.merge_and_unload()
if batch_size == 1:
try:
model = model.to_bettertransformer()
except:
# could be not implemented or natively supported
pass
logging.info(f"Model memory: {model.get_memory_footprint() / 1e9} GB")
if batch_size > 1:
# sort the prompts by length so that we don't necessarily pad them by too much
# save also index to reorder the completions
original_order, prompts = zip(*sorted(enumerate(prompts), key=lambda x: len(x[1])))
prompts = list(prompts)
if not tokenizer.pad_token_id:
# set padding token if not set
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenizer.pad_token = tokenizer.eos_token
default_kwargs = dict(
do_sample=do_sample,
model_kwargs={k: v for k, v in model_kwargs.items() if k != "trust_remote_code"},
batch_size=batch_size,
)
default_kwargs.update(kwargs)
logging.info(f"Kwargs to completion: {default_kwargs}")
pipeline = transformers.pipeline(
task="text-generation",
model=model,
tokenizer=tokenizer,
**default_kwargs,
trust_remote_code=model_kwargs.get("trust_remote_code", False),
)
## compute and log the time for completions
prompts_dataset = ListDataset(prompts)
completions = []
with utils.Timer() as t:
for out in tqdm(
pipeline(
prompts_dataset,
return_full_text=False,
pad_token_id=tokenizer.pad_token_id,
)
):
generated_text = out[0]["generated_text"]
if remove_ending is not None and generated_text.endswith(remove_ending):
generated_text = generated_text[: -len(remove_ending)]
completions.append(generated_text)
logging.info(f"Time for {n_examples} completions: {t}")
if batch_size > 1:
# reorder the completions to match the original order
completions, _ = zip(*sorted(list(zip(completions, original_order)), key=lambda x: x[1]))
completions = list(completions)
# local => price is really your compute
price = [np.nan] * len(completions)
avg_time = [t.duration / n_examples] * len(completions)
return dict(completions=completions, price_per_example=price, time_per_example=avg_time)