kunato commited on
Commit
54ec182
·
verified ·
1 Parent(s): 5525df5

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +334 -0
README.md ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: llama3.1
3
+ pipeline_tag: text-generation
4
+ ---
5
+
6
+ Llama3.1-Typhoon2-8B: Thai Large Language Model (Instruct)
7
+
8
+ Llama3.1-Typhoon2-8B-instruct is a instruct Thai 🇹🇭 large language model with 8 billion parameters, and it is based on Llama3.1-8B.
9
+
10
+
11
+ [TODO add one image and table result]
12
+
13
+ For release post, please see our [blog](...).
14
+ *To acknowledge Meta's effort in creating the foundation model and to comply with the license, we explicitly include "llama-3.1" in the model name.
15
+
16
+ ## **Model Description**
17
+
18
+ - **Model type**: A 8B instruct decoder-only model based on Llama architecture.
19
+ - **Requirement**: transformers 4.45.0 or newer.
20
+ - **Context length**: 90k
21
+ - **Primary Language(s)**: Thai 🇹🇭 and English 🇬🇧
22
+ - **License**: [Llama 3.1 Community License](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE)
23
+
24
+
25
+ ## Usage Example
26
+
27
+ ```python
28
+ from transformers import AutoTokenizer, AutoModelForCausalLM
29
+ import torch
30
+
31
+ model_id = "scb10x/llama3.1-typhoon2-8b-instruct"
32
+
33
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
34
+ model = AutoModelForCausalLM.from_pretrained(
35
+ model_id,
36
+ torch_dtype=torch.bfloat16,
37
+ device_map="auto",
38
+ )
39
+
40
+ messages = [
41
+ {"role": "system", "content": "You are Typhoon, an AI assistant created by SCB 10X, designed to be helpful, harmless, and honest. Typhoon assists with analysis, answering questions, math, coding, creative writing, teaching, role-play, discussions, and more. Typhoon responds directly without affirmations or filler phrases (e.g., “Certainly,” “Of course”). Responses do not start with “Certainly” in any form. Typhoon adheres to these rules in all languages and always replies in the user's language or as requested. Communicate in fluid, conversational prose, showing genuine interest, empathy, and presenting information clearly and visually."},
42
+ {"role": "user", "content": "ขอสูตรไก่ย่าง"},
43
+ ]
44
+
45
+ input_ids = tokenizer.apply_chat_template(
46
+ messages,
47
+ add_generation_prompt=True,
48
+ return_tensors="pt"
49
+ ).to(model.device)
50
+
51
+ terminators = [
52
+ tokenizer.eos_token_id,
53
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
54
+ ]
55
+
56
+ outputs = model.generate(
57
+ input_ids,
58
+ max_new_tokens=512,
59
+ eos_token_id=terminators,
60
+ do_sample=True,
61
+ temperature=0.4,
62
+ top_p=0.9,
63
+ )
64
+ response = outputs[0][input_ids.shape[-1]:]
65
+ print(tokenizer.decode(response, skip_special_tokens=True))
66
+ ```
67
+
68
+ ## Inference Server Hosting Example
69
+ ```bash
70
+ pip install vllm
71
+ vllm serve scb10x/llama3.1-typhoon2-8b-instruct
72
+ # see more information at https://docs.vllm.ai/
73
+ ```
74
+
75
+
76
+ ## Function-Call Example
77
+ ```python
78
+ import json
79
+ import torch
80
+ from transformers import AutoModelForCausalLM, AutoTokenizer
81
+ import os
82
+ import ast
83
+
84
+ model_name = "scb10x/llama3.1-typhoon2-8b-instruct"
85
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
86
+ model = AutoModelForCausalLM.from_pretrained(
87
+ model_name, torch_dtype=torch.bfloat16
88
+ )
89
+
90
+ get_weather_api = {
91
+ "name": "get_weather",
92
+ "description": "Get the current weather for a location",
93
+ "parameters": {
94
+ "type": "object",
95
+ "properties": {
96
+ "location": {
97
+ "type": "string",
98
+ "description": "The city and state, e.g. San Francisco, New York",
99
+ },
100
+ "unit": {
101
+ "type": "string",
102
+ "enum": ["celsius", "fahrenheit"],
103
+ "description": "The unit of temperature to return",
104
+ },
105
+ },
106
+ "required": ["location"],
107
+ },
108
+ }
109
+
110
+
111
+ search_api = {
112
+ "name": "search",
113
+ "description": "Search for information on the internet",
114
+ "parameters": {
115
+ "type": "object",
116
+ "properties": {
117
+ "query": {
118
+ "type": "string",
119
+ "description": "The search query, e.g. 'latest news on AI'",
120
+ }
121
+ },
122
+ "required": ["query"],
123
+ },
124
+ }
125
+
126
+ get_stock = {
127
+ "name": "get_stock_price",
128
+ "description": "Get the stock price",
129
+ "parameters": {
130
+ "type": "object",
131
+ "properties": {
132
+ "symbol": {
133
+ "type": "string",
134
+ "description": "The stock symbol, e.g. AAPL, GOOG",
135
+ }
136
+ },
137
+ "required": ["symbol"],
138
+ },
139
+ }
140
+ # Tool input are same format with OpenAI tools
141
+ openai_format_tools = [get_weather_api, search_api, get_stock]
142
+
143
+ messages = [
144
+ {"role": "system", "content": "You are helpful assistance."},
145
+ {"role": "user", "content": "ขอราคาหุ้น Tasla (TLS) และ Amazon (AMZ) ?"},
146
+ ]
147
+
148
+ final_prompt = tokenizer.apply_chat_template(
149
+ messages, tools=openai_format_tools, add_generation_prompt=True, tokenize=False
150
+ )
151
+
152
+ inputs = tokenizer.apply_chat_template(
153
+ messages, tools=openai_format_tools, add_generation_prompt=True, return_tensors="pt"
154
+ ).to(model.device)
155
+
156
+ outputs = model.generate(
157
+ inputs,
158
+ max_new_tokens=512,
159
+ do_sample=True,
160
+ temperature=0.7,
161
+ num_return_sequences=1,
162
+ eos_token_id=[tokenizer.eos_token_id, 128009],
163
+ )
164
+ response = outputs[0][input_ids.shape[-1]:]
165
+
166
+ print("Here Output:", tokenizer.decode(response, skip_special_tokens=True))
167
+
168
+
169
+ # Decoding function utility
170
+ def resolve_ast_by_type(value):
171
+ if isinstance(value, ast.Constant):
172
+ if value.value is Ellipsis:
173
+ output = "..."
174
+ else:
175
+ output = value.value
176
+ elif isinstance(value, ast.UnaryOp):
177
+ output = -value.operand.value
178
+ elif isinstance(value, ast.List):
179
+ output = [resolve_ast_by_type(v) for v in value.elts]
180
+ elif isinstance(value, ast.Dict):
181
+ output = {
182
+ resolve_ast_by_type(k): resolve_ast_by_type(v)
183
+ for k, v in zip(value.keys, value.values)
184
+ }
185
+ elif isinstance(
186
+ value, ast.NameConstant
187
+ ): # Added this condition to handle boolean values
188
+ output = value.value
189
+ elif isinstance(
190
+ value, ast.BinOp
191
+ ): # Added this condition to handle function calls as arguments
192
+ output = eval(ast.unparse(value))
193
+ elif isinstance(value, ast.Name):
194
+ output = value.id
195
+ elif isinstance(value, ast.Call):
196
+ if len(value.keywords) == 0:
197
+ output = ast.unparse(value)
198
+ else:
199
+ output = resolve_ast_call(value)
200
+ elif isinstance(value, ast.Tuple):
201
+ output = tuple(resolve_ast_by_type(v) for v in value.elts)
202
+ elif isinstance(value, ast.Lambda):
203
+ output = eval(ast.unparse(value.body[0].value))
204
+ elif isinstance(value, ast.Ellipsis):
205
+ output = "..."
206
+ elif isinstance(value, ast.Subscript):
207
+ try:
208
+ output = ast.unparse(value.body[0].value)
209
+ except:
210
+ output = ast.unparse(value.value) + "[" + ast.unparse(value.slice) + "]"
211
+ else:
212
+ raise Exception(f"Unsupported AST type: {type(value)}")
213
+ return output
214
+
215
+
216
+ def resolve_ast_call(elem):
217
+ func_parts = []
218
+ func_part = elem.func
219
+ while isinstance(func_part, ast.Attribute):
220
+ func_parts.append(func_part.attr)
221
+ func_part = func_part.value
222
+ if isinstance(func_part, ast.Name):
223
+ func_parts.append(func_part.id)
224
+ func_name = ".".join(reversed(func_parts))
225
+ args_dict = {}
226
+ for arg in elem.keywords:
227
+ output = resolve_ast_by_type(arg.value)
228
+ args_dict[arg.arg] = output
229
+ return {func_name: args_dict}
230
+
231
+
232
+ def ast_parse(input_str, language="Python"):
233
+ if language == "Python":
234
+ cleaned_input = input_str.strip("[]'")
235
+ parsed = ast.parse(cleaned_input, mode="eval")
236
+ extracted = []
237
+ if isinstance(parsed.body, ast.Call):
238
+ extracted.append(resolve_ast_call(parsed.body))
239
+ else:
240
+ for elem in parsed.body.elts:
241
+ assert isinstance(elem, ast.Call)
242
+ extracted.append(resolve_ast_call(elem))
243
+ return extracted
244
+ else:
245
+ raise NotImplementedError(f"Unsupported language: {language}")
246
+
247
+
248
+ def parse_nested_value(value):
249
+ """
250
+ Parse a potentially nested value from the AST output.
251
+
252
+ Args:
253
+ value: The value to parse, which could be a nested dictionary, which includes another function call, or a simple value.
254
+
255
+ Returns:
256
+ str: A string representation of the value, handling nested function calls and nested dictionary function arguments.
257
+ """
258
+ if isinstance(value, dict):
259
+ # Check if the dictionary represents a function call (i.e., the value is another dictionary or complex structure)
260
+ if all(isinstance(v, dict) for v in value.values()):
261
+ func_name = list(value.keys())[0]
262
+ args = value[func_name]
263
+ args_str = ", ".join(
264
+ f"{k}={parse_nested_value(v)}" for k, v in args.items()
265
+ )
266
+ return f"{func_name}({args_str})"
267
+ else:
268
+ # If it's a simple dictionary, treat it as key-value pairs
269
+ return (
270
+ "{"
271
+ + ", ".join(f"'{k}': {parse_nested_value(v)}" for k, v in value.items())
272
+ + "}"
273
+ )
274
+ return repr(value)
275
+
276
+
277
+ def decoded_output_to_execution_list(decoded_output):
278
+ """
279
+ Convert decoded output to a list of executable function calls.
280
+
281
+ Args:
282
+ decoded_output (list): A list of dictionaries representing function calls.
283
+
284
+ Returns:
285
+ list: A list of strings, each representing an executable function call.
286
+ """
287
+ execution_list = []
288
+ for function_call in decoded_output:
289
+ for key, value in function_call.items():
290
+ args_str = ", ".join(
291
+ f"{k}={parse_nested_value(v)}" for k, v in value.items()
292
+ )
293
+ execution_list.append(f"{key}({args_str})")
294
+ return execution_list
295
+
296
+
297
+ def default_decode_ast_prompting(result, language="Python"):
298
+ result = result.strip("`\n ")
299
+ if not result.startswith("["):
300
+ result = "[" + result
301
+ if not result.endswith("]"):
302
+ result = result + "]"
303
+ decoded_output = ast_parse(result, language)
304
+ return decoded_output
305
+
306
+
307
+ fc_result = default_decode_ast_prompting(tokenizer.decode(response, skip_special_tokens=True))
308
+ print(fc_result) # [{'Function': {'arguments': '{"symbol": "TLS"}', 'name': 'get_stock_price'}}, {'Function': {'arguments': '{"symbol": "AMZ"}', 'name': 'get_stock_price'}}]
309
+ ```
310
+
311
+ ## **Intended Uses & Limitations**
312
+
313
+ This model is an instructional model. However, it’s still undergoing development. It incorporates some level of guardrails, but it still may produce answers that are inaccurate, biased, or otherwise objectionable in response to user prompts. We recommend that developers assess these risks in the context of their use case.
314
+
315
+ ## **Follow us**
316
+
317
+ **https://twitter.com/opentyphoon**
318
+
319
+ ## **Support**
320
+
321
+ **https://discord.gg/CqyBscMFpg**
322
+
323
+ ## **Citation**
324
+
325
+ - If you find Typhoon2 useful for your work, please cite it using:
326
+ ```
327
+ @article{pipatanakul2023typhoon,
328
+ title={Typhoon: Thai Large Language Models},
329
+ author={Kunat Pipatanakul and Phatrasek Jirabovonvisut and Potsawee Manakul and Sittipong Sripaisarnmongkol and Ruangsak Patomwong and Pathomporn Chokchainant and Kasima Tharnpipitchai},
330
+ year={2023},
331
+ journal={arXiv preprint arXiv:2312.13951},
332
+ url={https://arxiv.org/abs/2312.13951}
333
+ }
334
+ ```