Views
No views yet



| Model | IFEval - TH | IFEval - EN | MT-Bench TH | MT-Bench EN | Thai Code-Switching(t=0.7) | Thai Code-Switching(t=1.0) | FC-TH | FC-EN | GSM8K-TH | GSM8K-EN | MATH-TH | MATH-EN | HumanEval-TH | HumanEval-EN | MBPP-TH | MBPP-EN |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Typhoon2 Qwen2.5 7B Instruct | 74.37% | 73.34% | 6.186 | 8.094 | 99.2% | 96.8% | 74.24% | 75.44% | 79.07% | 84.2% | 55.42% | 66.42% | 73.2% | 79.3% | 78.3% | 81.7% |
| Qwen2.5 7B Instruct | 68.47% | 76.82% | 6.0 | 8.537 | 85.8% | 20.4% | 66.06% | 74.81% | 47.53% | 81.0% | 17.41% | 73.4% | 77.4% | 81.1% | 80.4% | 79.6% |
| Openthaigpt 1.5 7B | 67.38% | 75.47% | 5.692 | 8.106 | 93.8% | 28% | 65.53% | 73.10% | 65.73% | 68.0% | 24.44% | 69.68% | 71.3% | 78.7% | 77.5% | 79.1% |
1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3
4model_id = "scb10x/typhoon2-qwen2.5-7b-instruct"
5
6tokenizer = AutoTokenizer.from_pretrained(model_id)
7model = AutoModelForCausalLM.from_pretrained(
8 model_id,
9 torch_dtype=torch.bfloat16,
10 device_map="auto",
11)
12
13messages = [
14 {"role": "system", "content": "You are a male AI assistant named Typhoon created by SCB 10X to be helpful, harmless, and honest. Typhoon is happy to help with analysis, question answering, math, coding, creative writing, teaching, role-play, general discussion, and all sorts of other tasks. Typhoon responds directly to all human messages without unnecessary affirmations or filler phrases like “Certainly!”, “Of course!”, “Absolutely!”, “Great!”, “Sure!”, etc. Specifically, Typhoon avoids starting responses with the word “Certainly” in any way. Typhoon follows this information in all languages, and always responds to the user in the language they use or request. Typhoon is now being connected with a human. Write in fluid, conversational prose, Show genuine interest in understanding requests, Express appropriate emotions and empathy. Also showing information in term that is easy to understand and visualized."},
15 {"role": "user", "content": "ขอสูตรไก่ย่าง"},
16]
17
18input_ids = tokenizer.apply_chat_template(
19 messages,
20 add_generation_prompt=True,
21 return_tensors="pt"
22).to(model.device)
23
24
25outputs = model.generate(
26 input_ids,
27 max_new_tokens=512,
28 do_sample=True,
29 temperature=0.6,
30 top_p=0.9,
31)
32response = outputs[0][input_ids.shape[-1]:]
33print(tokenizer.decode(response, skip_special_tokens=True))1pip install vllm
2vllm serve scb10x/typhoon2-qwen2.5-7b-instruct
3# see more information at https://docs.vllm.ai/1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3import ast
4model_name = "scb10x/typhoon2-qwen2.5-7b-instruct"
5tokenizer = AutoTokenizer.from_pretrained(model_name)
6model = AutoModelForCausalLM.from_pretrained(
7 model_name, torch_dtype=torch.bfloat16, device_map="auto",
8)
9
10get_weather_api = {
11 "name": "get_weather",
12 "description": "Get the current weather for a location",
13 "parameters": {
14 "type": "object",
15 "properties": {
16 "location": {
17 "type": "string",
18 "description": "The city and state, e.g. San Francisco, New York",
19 },
20 "unit": {
21 "type": "string",
22 "enum": ["celsius", "fahrenheit"],
23 "description": "The unit of temperature to return",
24 },
25 },
26 "required": ["location"],
27 },
28}
29
30
31search_api = {
32 "name": "search",
33 "description": "Search for information on the internet",
34 "parameters": {
35 "type": "object",
36 "properties": {
37 "query": {
38 "type": "string",
39 "description": "The search query, e.g. 'latest news on AI'",
40 }
41 },
42 "required": ["query"],
43 },
44}
45
46get_stock = {
47 "name": "get_stock_price",
48 "description": "Get the stock price",
49 "parameters": {
50 "type": "object",
51 "properties": {
52 "symbol": {
53 "type": "string",
54 "description": "The stock symbol, e.g. AAPL, GOOG",
55 }
56 },
57 "required": ["symbol"],
58 },
59}
60# Tool input are same format with OpenAI tools
61openai_format_tools = [get_weather_api, search_api, get_stock]
62
63messages = [
64 {"role": "system", "content": "You are an expert in composing functions."},
65 {"role": "user", "content": "ขอราคาหุ้น Tasla (TLS) และ Amazon (AMZ) ?"},
66]
67
68inputs = tokenizer.apply_chat_template(
69 messages, tools=openai_format_tools, add_generation_prompt=True, return_tensors="pt"
70).to(model.device)
71
72outputs = model.generate(
73 inputs,
74 max_new_tokens=512,
75 do_sample=True,
76 temperature=0.7,
77 num_return_sequences=1,
78)
79response = outputs[0][inputs.shape[-1]:]
80
81print("Here Output:", tokenizer.decode(response, skip_special_tokens=True))
82
83
84# Decoding function utility
85def resolve_ast_by_type(value):
86 if isinstance(value, ast.Constant):
87 if value.value is Ellipsis:
88 output = "..."
89 else:
90 output = value.value
91 elif isinstance(value, ast.UnaryOp):
92 output = -value.operand.value
93 elif isinstance(value, ast.List):
94 output = [resolve_ast_by_type(v) for v in value.elts]
95 elif isinstance(value, ast.Dict):
96 output = {
97 resolve_ast_by_type(k): resolve_ast_by_type(v)
98 for k, v in zip(value.keys, value.values)
99 }
100 elif isinstance(
101 value, ast.NameConstant
102 ): # Added this condition to handle boolean values
103 output = value.value
104 elif isinstance(
105 value, ast.BinOp
106 ): # Added this condition to handle function calls as arguments
107 output = eval(ast.unparse(value))
108 elif isinstance(value, ast.Name):
109 output = value.id
110 elif isinstance(value, ast.Call):
111 if len(value.keywords) == 0:
112 output = ast.unparse(value)
113 else:
114 output = resolve_ast_call(value)
115 elif isinstance(value, ast.Tuple):
116 output = tuple(resolve_ast_by_type(v) for v in value.elts)
117 elif isinstance(value, ast.Lambda):
118 output = eval(ast.unparse(value.body[0].value))
119 elif isinstance(value, ast.Ellipsis):
120 output = "..."
121 elif isinstance(value, ast.Subscript):
122 try:
123 output = ast.unparse(value.body[0].value)
124 except:
125 output = ast.unparse(value.value) + "[" + ast.unparse(value.slice) + "]"
126 else:
127 raise Exception(f"Unsupported AST type: {type(value)}")
128 return output
129
130
131def resolve_ast_call(elem):
132 func_parts = []
133 func_part = elem.func
134 while isinstance(func_part, ast.Attribute):
135 func_parts.append(func_part.attr)
136 func_part = func_part.value
137 if isinstance(func_part, ast.Name):
138 func_parts.append(func_part.id)
139 func_name = ".".join(reversed(func_parts))
140 args_dict = {}
141 for arg in elem.keywords:
142 output = resolve_ast_by_type(arg.value)
143 args_dict[arg.arg] = output
144 return {func_name: args_dict}
145
146
147def ast_parse(input_str, language="Python"):
148 if language == "Python":
149 cleaned_input = input_str.strip("[]'")
150 parsed = ast.parse(cleaned_input, mode="eval")
151 extracted = []
152 if isinstance(parsed.body, ast.Call):
153 extracted.append(resolve_ast_call(parsed.body))
154 else:
155 for elem in parsed.body.elts:
156 assert isinstance(elem, ast.Call)
157 extracted.append(resolve_ast_call(elem))
158 return extracted
159 else:
160 raise NotImplementedError(f"Unsupported language: {language}")
161
162
163def parse_nested_value(value):
164 """
165 Parse a potentially nested value from the AST output.
166
167 Args:
168 value: The value to parse, which could be a nested dictionary, which includes another function call, or a simple value.
169
170 Returns:
171 str: A string representation of the value, handling nested function calls and nested dictionary function arguments.
172 """
173 if isinstance(value, dict):
174 # Check if the dictionary represents a function call (i.e., the value is another dictionary or complex structure)
175 if all(isinstance(v, dict) for v in value.values()):
176 func_name = list(value.keys())[0]
177 args = value[func_name]
178 args_str = ", ".join(
179 f"{k}={parse_nested_value(v)}" for k, v in args.items()
180 )
181 return f"{func_name}({args_str})"
182 else:
183 # If it's a simple dictionary, treat it as key-value pairs
184 return (
185 "{"
186 + ", ".join(f"'{k}': {parse_nested_value(v)}" for k, v in value.items())
187 + "}"
188 )
189 return repr(value)
190
191def default_decode_ast_prompting(result, language="Python"):
192 result = result.strip("`\n ")
193 if not result.startswith("["):
194 result = "[" + result
195 if not result.endswith("]"):
196 result = result + "]"
197 decoded_output = ast_parse(result, language)
198 return decoded_output
199
200
201fc_result = default_decode_ast_prompting(tokenizer.decode(response, skip_special_tokens=True))
202print(fc_result) # [{'Function': {'arguments': '{"symbol": "TLS"}', 'name': 'get_stock_price'}}, {'Function': {'arguments': '{"symbol": "AMZ"}', 'name': 'get_stock_price'}}]config.json is set for context length up to 32,768 tokens.
To handle extensive inputs exceeding 32,768 tokens, we utilize YaRN, a technique for enhancing model length extrapolation, ensuring optimal performance on lengthy texts.config.json to enable YaRN:1{
2 ...,
3 "rope_scaling": {
4 "factor": 4.0,
5 "original_max_position_embeddings": 32768,
6 "type": "yarn"
7 }
8}rope_scaling configuration only when processing long contexts is required.@misc{typhoon2,
title={Typhoon 2: A Family of Open Text and Multimodal Thai Large Language Models},
author={Kunat Pipatanakul and Potsawee Manakul and Natapong Nitarach and Warit Sirichotedumrong and Surapon Nonesung and Teetouch Jaknamon and Parinthapat Pengpun and Pittawat Taveekitworachai and Adisai Na-Thalang and Sittipong Sripaisarnmongkol and Krisanapong Jirayoot and Kasima Tharnpipitchai},
year={2024},
eprint={2412.13702},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2412.13702},
}