forked from microsoft/CoML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
176 lines (142 loc) · 4.58 KB
/
utils.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
166
167
168
169
170
171
172
173
174
175
176
import os
import re
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from langchain.embeddings import OpenAIEmbeddings
from langchain_openai import OpenAI
from .constants import *
LLM_MODELS = {
"suggest": lambda: OpenAI(model_name="text-davinci-003", temperature=0),
"knowledge": lambda: OpenAI(model_name="text-davinci-003"),
"embedding": lambda: OpenAIEmbeddings(),
}
_TOKEN_COUNT_FUNC = None
def clean_input(prompt: str = ""):
try:
return input(prompt)
except KeyboardInterrupt:
print("You interrupted CoML")
print("Quitting...")
exit(0)
pattern_0 = re.compile("Configuration(?: \d)*: (.*)\.\n")
def parse_configs(
response: str,
TOP_k: int,
inverse_bin_map: Dict = {},
quantile_info: Optional[Dict] = None,
) -> List[Dict]:
"""
Parse the response from the LLM API and return the suggested configurations.
Parameters
----------
response : str
The response from the LLM API.
TOP_k : int
The number of suggested configurations to return.
inverse_bin_map : Dict
The inverse bin map from the Space object.
quantile_info : Optional[Dict]
The meta train info for statistics from the Space object.
Returns
-------
suggest_configs : List[Dict]
The suggested configurations.
"""
suggest_configs = []
groups = re.findall(pattern_0, response + "\n")
for t in groups[:TOP_k]:
kvs = t.split(". ")
config = {}
for kv in kvs:
_k, v = kv.strip().split(" is ")
if v in inverse_bin_map:
config_col = list(quantile_info[_k])
value = config_col[q_num.index(inverse_bin_map[v])]
elif v in ("True", "False"):
value = eval(v)
else:
value = v
config[_k] = value
suggest_configs.append(config)
return suggest_configs
def format_config(
config: Dict[str, Any],
quantile_info: Optional[Dict[str, List[float]]] = None,
bin_map: Dict[float, str] = {},
) -> str:
"""
Format the configuration to a string which can be input to the LLM API.
Parameters
----------
config
The configuration to be formatted.
quantile_info
The meta train info for statistics from the Space object.
bin_map
The bin map is to map the bin value to the string.
Returns
-------
config_str : str
The formatted configuration.
"""
result = []
for k, v in config.items():
_k = k
if v is None:
continue
elif v in ["TRUE", "FALSE"]:
result.append(f"{_k} is {v.lower().capitalize()}")
elif v is True or v is False:
v = str(v)
result.append(f"{_k} is {v.lower().capitalize()}")
elif isinstance(v, str):
result.append(f"{_k} is {v}")
elif isinstance(v, (float, int)):
assert quantile_info is not None, "quantile_info is None"
config_col = list(quantile_info[k])
anchor = min(config_col, key=lambda x: abs(x - v))
value = bin_map[q_num[config_col.index(anchor)]]
result.append(f"{_k} is {value}")
else:
assert False, f"{v}"
return ". ".join(result) + "."
@lru_cache(maxsize=1000)
def _token_count(text):
import tiktoken
try:
encoding = tiktoken.encoding_for_model("gpt-4")
except KeyError:
print("Warning: model not found. Using gpt-2 encoding.")
encoding = tiktoken.get_encoding("gpt2")
return len(encoding.encode(text))
def token_count(texts):
if isinstance(texts, str):
return _token_count(texts)
l = 0
for text in texts:
l += _token_count(text)
return l
def set_token_count_func(func):
global _TOKEN_COUNT_FUNC
_TOKEN_COUNT_FUNC = func
def get_token_count_func():
global _TOKEN_COUNT_FUNC
return _TOKEN_COUNT_FUNC
def get_llm(model_type: str):
return LLM_MODELS[model_type]
def set_llms(
suggest_model: Optional[Callable] = None,
knowledge_model: Optional[Callable] = None,
embedding_model: Optional[Callable] = None,
):
global LLM_MODELS
if suggest_model is not None:
LLM_MODELS["suggest"] = suggest_model
if knowledge_model is not None:
LLM_MODELS["knowledge"] = knowledge_model
if embedding_model is not None:
LLM_MODELS["embedding"] = embedding_model
def escape(text: str) -> str:
return re.sub("(?<!{)\{(.*?)\}(?!})", r"{{\1}}", text)
set_token_count_func(token_count)