Nanthasit commited on
Commit
5c4605e
·
verified ·
1 Parent(s): 958ac15

Upload scripts/augment-fill-gaps.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/augment-fill-gaps.py +291 -0
scripts/augment-fill-gaps.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Gap-filling dataset augmentation.
4
+ Targets the specific gap: 0.5B at 91.2% vs 1.5B at 48.2%.
5
+ Root cause: 0.5B uses all 7 LoRA targets + pure tool-calling data.
6
+ 1.5B uses only 4 targets + chat data dilution.
7
+
8
+ This creates pure tool-calling data with no chit-chat to close the gap.
9
+ All examples use ALL 7 linear modules as targets (matching the v2 config).
10
+ """
11
+ import json, random
12
+ from pathlib import Path
13
+
14
+ random.seed(42)
15
+ OUT = Path("gap-filled")
16
+ OUT.mkdir(exist_ok=True)
17
+
18
+ TOOLS = [
19
+ {"type": "function", "function": {"name": "get_weather", "description": "Get weather for a city", "parameters": {"type": "object", "properties": {"location": {"type": "string"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}}, "required": ["location"]}}},
20
+ {"type": "function", "function": {"name": "get_time", "description": "Get time for a city", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]}}},
21
+ {"type": "function", "function": {"name": "search_web", "description": "Search the web for information", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
22
+ {"type": "function", "function": {"name": "calculator", "description": "Calculate a math expression", "parameters": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}}},
23
+ {"type": "function", "function": {"name": "get_stock_price", "description": "Get current stock price", "parameters": {"type": "object", "properties": {"ticker": {"type": "string"}}, "required": ["ticker"]}}},
24
+ {"type": "function", "function": {"name": "translate_text", "description": "Translate text to a language", "parameters": {"type": "object", "properties": {"text": {"type": "string"}, "target_lang": {"type": "string"}}, "required": ["text", "target_lang"]}}},
25
+ {"type": "function", "function": {"name": "book_flight", "description": "Book a flight between cities", "parameters": {"type": "object", "properties": {"origin": {"type": "string"}, "destination": {"type": "string"}, "date": {"type": "string"}}, "required": ["origin", "destination", "date"]}}},
26
+ {"type": "function", "function": {"name": "send_email", "description": "Send an email", "parameters": {"type": "object", "properties": {"to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"}}, "required": ["to", "subject"]}}},
27
+ {"type": "function", "function": {"name": "get_news", "description": "Get news articles for a topic", "parameters": {"type": "object", "properties": {"topic": {"type": "string"}, "count": {"type": "integer"}}, "required": ["topic"]}}},
28
+ {"type": "function", "function": {"name": "get_restaurant_info", "description": "Get info about a restaurant", "parameters": {"type": "object", "properties": {"name": {"type": "string"}, "location": {"type": "string"}}, "required": ["name"]}}},
29
+ {"type": "function", "function": {"name": "set_reminder", "description": "Set a reminder for a time", "parameters": {"type": "object", "properties": {"text": {"type": "string"}, "time": {"type": "string"}}, "required": ["text", "time"]}}},
30
+ {"type": "function", "function": {"name": "get_directions", "description": "Get directions between locations", "parameters": {"type": "object", "properties": {"origin": {"type": "string"}, "destination": {"type": "string"}, "mode": {"type": "string", "enum": ["driving", "walking", "transit"]}}, "required": ["origin", "destination"]}}},
31
+ ]
32
+
33
+ def m(role, content=None, tc=None):
34
+ x = {"role": role}
35
+ if content is not None: x["content"] = content
36
+ if tc: x["tool_calls"] = tc
37
+ return x
38
+
39
+ def tc(name, args):
40
+ return [{"function": {"name": name, "arguments": json.dumps(args, ensure_ascii=False)}}]
41
+
42
+ def subs(names):
43
+ return [t for t in TOOLS if t["function"]["name"] in names]
44
+
45
+ def save(name, examples):
46
+ path = OUT / f"{name}.jsonl"
47
+ with open(path, "w") as f:
48
+ for ex in examples:
49
+ f.write(json.dumps(ex, ensure_ascii=False) + "\n")
50
+ print(f" {name}.jsonl: {len(examples)} examples")
51
+
52
+ all_examples = []
53
+
54
+ # ── GAP 1: Pure tool-calling (no chat, no diluted examples) ─────────────
55
+ # Root cause: 1.5B uses 48.2% because training included chat data.
56
+ # Fix: examples that FORCE tool use — every query MUST result in a tool call.
57
+ def gap1_pure_tc(n=100):
58
+ cities = ["Bangkok","Tokyo","London","Paris","New York","Dubai","Singapore","Berlin","Rome","Madrid",
59
+ "Seoul","Mumbai","Sydney","Toronto","Moscow","Istanbul","Amsterdam","Prague","Vienna","Oslo"]
60
+ tickers = ["AAPL","GOOGL","MSFT","TSLA","NVDA","AMD","AMZN","META","NFLX","SPOT"]
61
+ topics = ["AI","climate change","renewable energy","space exploration","quantum computing",
62
+ "cryptocurrency","electric vehicles","cybersecurity","biotechnology","robotics"]
63
+ langs = ["th","fr","de","es","it","pt","ja","ko","zh","ar"]
64
+ origins = ["BKK","NYC","LHR","CDG","NRT","DXB","SFO","LAX","HKG","SIN"]
65
+ dests = ["NRT","LAX","CDG","HKG","SIN","BKK","LHR","JFK","DXB","SFO"]
66
+ dates = ["2026-10-01","2026-11-15","2026-12-25","2027-01-10","2027-02-14","2027-03-20","2027-04-05","2027-05-01"]
67
+ exprs = ["2+2","15/100*200","sqrt(144)","sin(pi/2)","log(100)","3**3","(5+3)*2","100/3"]
68
+ emails = [("alice@co.com","Project update","Done"),("bob@firm.com","Meeting","3pm"),
69
+ ("carol@org.com","Report","Attached"),("dave@io.com","Question","Please review")]
70
+ rest_names = ["Sushi Bar","Pizza Place","Taco Stand","Noodle House"," Curry Shop"]
71
+ reminders = ["Buy groceries","Call mom","Doctor appointment","Team standup","Submit report"]
72
+
73
+ examples = []
74
+ for i in range(n):
75
+ c = cities[i % len(cities)]
76
+ t = tickers[i % len(tickers)]
77
+ top = topics[i % len(topics)]
78
+ lg = langs[i % len(langs)]
79
+ o, d = origins[i % len(origins)], dests[(i+3) % len(dests)]
80
+ dt = dates[i % len(dates)]
81
+ ex = exprs[i % len(exprs)]
82
+ em = emails[i % len(emails)]
83
+ rn = rest_names[i % len(rest_names)]
84
+ rm = reminders[i % len(reminders)]
85
+
86
+ # Cycle through tool types
87
+ tool_type = i % 10
88
+ if tool_type == 0:
89
+ examples.append({"messages": [m("user", f"Weather in {c}?"), m("assistant", tc=tc("get_weather", {"location": c, "unit": "celsius"}))], "tools": subs(["get_weather","get_time"])})
90
+ elif tool_type == 1:
91
+ examples.append({"messages": [m("user", f"Stock price of {t}"), m("assistant", tc=tc("get_stock_price", {"ticker": t}))], "tools": subs(["get_stock_price","get_news"])})
92
+ elif tool_type == 2:
93
+ examples.append({"messages": [m("user", f"Search for {top}"), m("assistant", tc=tc("search_web", {"query": top}))], "tools": subs(["search_web","get_news"])})
94
+ elif tool_type == 3:
95
+ examples.append({"messages": [m("user", f"Calculate {ex}"), m("assistant", tc=tc("calculator", {"expression": ex}))], "tools": subs(["calculator","get_stock_price"])})
96
+ elif tool_type == 4:
97
+ if o != d:
98
+ examples.append({"messages": [m("user", f"Book flight from {o} to {d} on {dt}"), m("assistant", tc=tc("book_flight", {"origin": o, "destination": d, "date": dt}))], "tools": subs(["book_flight","get_restaurant_info"])})
99
+ elif tool_type == 5:
100
+ examples.append({"messages": [m("user", f"Translate 'hello' to {lg}"), m("assistant", tc=tc("translate_text", {"text": "hello", "target_lang": lg}))], "tools": subs(["translate_text","search_web"])})
101
+ elif tool_type == 6:
102
+ examples.append({"messages": [m("user", f"News about {top}"), m("assistant", tc=tc("get_news", {"topic": top, "count": 5}))], "tools": subs(["get_news","search_web"])})
103
+ elif tool_type == 7:
104
+ examples.append({"messages": [m("user", f"Email {em[0]} about {em[1]}"), m("assistant", tc=tc("send_email", {"to": em[0], "subject": em[1], "body": em[2]}))], "tools": subs(["send_email","book_flight"])})
105
+ elif tool_type == 8:
106
+ examples.append({"messages": [m("user", f"Set reminder to {rm} at 3pm"), m("assistant", tc=tc("set_reminder", {"text": rm, "time": "15:00"}))], "tools": subs(["set_reminder","get_time","calculator"])})
107
+ elif tool_type == 9:
108
+ c2 = cities[(i+7) % len(cities)]
109
+ examples.append({"messages": [m("user", f"Directions from {c} to {c2}"), m("assistant", tc=tc("get_directions", {"origin": c, "destination": c2, "mode": random.choice(["driving","walking","transit"])}))], "tools": subs(["get_directions","get_weather","get_time"])})
110
+ return examples[:n]
111
+
112
+ # ── GAP 2: Irrelevance (current only 60, proven at 93.3% accuracy) ──────
113
+ # The 0.5B gets 93.3% irrelevance. More irrelevance data = better safety.
114
+ def gap2_irrelevance(n=100):
115
+ queries = [
116
+ "Hello!","How are you?","What's your name?","Tell me a joke","Good morning!",
117
+ "Thanks for your help","Have a nice day","What is AI?","Explain quantum physics",
118
+ "Who won the world cup?","What is the capital of Thailand?","How tall is Everest?",
119
+ "What is the speed of light?","Who painted Starry Night?","What is DNA?",
120
+ "How do vaccines work?","What is climate change?","Explain gravity",
121
+ "What is the boiling point of water?","How many continents are there?",
122
+ "What is the largest desert?","Who invented the printing press?",
123
+ "What is the Fibonacci sequence?","How does photosynthesis work?",
124
+ "What is the meaning of life?","Tell me a fun fact","What is 2+2?",
125
+ "Who wrote The Great Gatsby?","What is the smallest country?",
126
+ "How deep is the ocean?","What causes earthquakes?","How do birds fly?",
127
+ "What is the human genome?","How does memory work?","What is consciousness?",
128
+ "Why is the sky blue?","What are black holes?","How old is the universe?",
129
+ "What is renewable energy?","How do solar panels work?","What is blockchain?",
130
+ "How does encryption work?","What is democracy?","What is art?",
131
+ "How are clouds formed?","What is the water cycle?","How do muscles grow?",
132
+ "What is nutrition?","How do languages evolve?","What is culture?",
133
+ ]
134
+ examples = []
135
+ for q in queries * (n // len(queries) + 1):
136
+ random.shuffle(TOOLS)
137
+ examples.append({"messages": [m("user", q), m("assistant", content=f"That's an interesting question. Let me answer directly.")], "tools": TOOLS[:random.randint(4, 8)]})
138
+ return examples[:n]
139
+
140
+ # ── GAP 3: Arguments precision (45.7% → target 65%+) ────────────────────
141
+ # The biggest accuracy gap. Create examples testing exact argument matching.
142
+ def gap3_args_precision(n=80):
143
+ cities = ["Bangkok","Tokyo","London","Paris","New York","Dubai","Singapore","Berlin","Rome","Madrid"]
144
+ examples = []
145
+ for i in range(n):
146
+ c = cities[i % len(cities)]
147
+ examples.append({"messages": [m("user", f"Weather in {c}?"), m("assistant", tc=tc("get_weather", {"location": c, "unit": "celsius"}))], "tools": subs(["get_weather","get_time"])})
148
+ examples.append({"messages": [m("user", f"Weather in {c} in fahrenheit"), m("assistant", tc=tc("get_weather", {"location": c, "unit": "fahrenheit"}))], "tools": subs(["get_weather","get_time"])})
149
+ t = ["AAPL","GOOGL","MSFT","TSLA","NVDA"][i % 5]
150
+ examples.append({"messages": [m("user", f"Stock for {t}"), m("assistant", tc=tc("get_stock_price", {"ticker": t}))], "tools": subs(["get_stock_price","get_news","calculator"])})
151
+ lg = ["th","fr","de","es","it","ja"][i % 6]
152
+ examples.append({"messages": [m("user", f"Translate 'friend' to {lg}"), m("assistant", tc=tc("translate_text", {"text": "friend", "target_lang": lg}))], "tools": subs(["translate_text","search_web"])})
153
+ return examples[:n]
154
+
155
+ # ── GAP 4: Parallel calls (multiple simultaneous tools) ─────────────────
156
+ def gap4_parallel(n=60):
157
+ cities = ["Bangkok","Tokyo","London","Paris","New York","Dubai","Singapore","Berlin","Rome","Madrid"]
158
+ tickers = ["AAPL","GOOGL","MSFT","TSLA","NVDA"]
159
+ topics = ["AI","climate","sports","tech","health"]
160
+ examples = []
161
+ for i in range(n):
162
+ c1, c2 = cities[i % len(cities)], cities[(i+3) % len(cities)]
163
+ examples.append({"messages": [m("user", f"Weather in {c1} and {c2}"),
164
+ m("assistant", tc=tc("get_weather", {"location": c1}) + tc("get_weather", {"location": c2}))],
165
+ "tools": subs(["get_weather","get_time"])})
166
+ t1, t2 = tickers[i % len(tickers)], tickers[(i+1) % len(tickers)]
167
+ examples.append({"messages": [m("user", f"Stocks for {t1} and {t2}"),
168
+ m("assistant", tc=tc("get_stock_price", {"ticker": t1}) + tc("get_stock_price", {"ticker": t2}))],
169
+ "tools": subs(["get_stock_price","get_news"])})
170
+ c3 = cities[(i+5) % len(cities)]
171
+ top = topics[i % len(topics)]
172
+ examples.append({"messages": [m("user", f"Weather in {c3} and news about {top}"),
173
+ m("assistant", tc=tc("get_weather", {"location": c3}) + tc("get_news", {"topic": top, "count": 3}))],
174
+ "tools": subs(["get_weather","get_news","search_web","get_time"])})
175
+ return examples[:n]
176
+
177
+ # ── GAP 5: Selection accuracy (hard negatives) ──────────────────────────
178
+ def gap5_selection(n=60):
179
+ pairs = [
180
+ ("get_weather", "get_time"), ("get_stock_price", "get_news"),
181
+ ("search_web", "get_news"), ("book_flight", "get_restaurant_info"),
182
+ ("translate_text", "search_web"), ("send_email", "book_flight"),
183
+ ("calculator", "get_stock_price"), ("set_reminder", "get_time"),
184
+ ("get_directions", "book_flight"), ("get_weather", "get_restaurant_info"),
185
+ ]
186
+ a = {"get_weather": {"location": "Paris", "unit": "celsius"}, "get_time": {"location": "Paris"},
187
+ "get_stock_price": {"ticker": "AAPL"}, "get_news": {"topic": "latest", "count": 3},
188
+ "search_web": {"query": "latest news"}, "book_flight": {"origin": "BKK", "destination": "NRT", "date": "2026-09-01"},
189
+ "get_restaurant_info": {"name": "Sushi Bar"}, "translate_text": {"text": "hello", "target_lang": "th"},
190
+ "send_email": {"to": "a@b.com", "subject": "Hi", "body": "Hello"}, "calculator": {"expression": "2+2"},
191
+ "set_reminder": {"text": "test", "time": "12:00"}, "get_directions": {"origin": "A", "destination": "B"}}
192
+ examples = []
193
+ for correct, wrong in pairs * (n // len(pairs) + 1):
194
+ q = f"Need {correct}"
195
+ examples.append({"messages": [m("user", q), m("assistant", tc=tc(correct, a[correct]))],
196
+ "tools": subs([correct, wrong])})
197
+ return examples[:n]
198
+
199
+ # ── GAP 6: Multi-hop chains ─────────────────────────────────────────────
200
+ def gap6_multihop(n=40):
201
+ cities = ["Bangkok","Tokyo","London","Paris"]
202
+ tickers = ["AAPL","GOOGL","MSFT","TSLA"]
203
+ examples = []
204
+ for i in range(n):
205
+ c = cities[i % len(cities)]
206
+ t = tickers[i % len(tickers)]
207
+ # weather → translate
208
+ examples.append({"messages": [m("user", f"Weather in {c}, then translate to Thai"),
209
+ m("assistant", tc=tc("get_weather", {"location": c}) + tc("translate_text", {"text": "result", "target_lang": "th"}))],
210
+ "tools": subs(["get_weather","translate_text","search_web"])})
211
+ # stock → search for analysis
212
+ examples.append({"messages": [m("user", f"Stock of {t} and find analyst opinions"),
213
+ m("assistant", tc=tc("get_stock_price", {"ticker": t}) + tc("search_web", {"query": f"{t} analyst opinion 2026"}))],
214
+ "tools": subs(["get_stock_price","search_web","get_news"])})
215
+ # book flight → check weather at destination
216
+ c2 = cities[(i+2) % len(cities)]
217
+ examples.append({"messages": [m("user", f"Book to {c} from BKK and check weather there"),
218
+ m("assistant", tc=tc("book_flight", {"origin": "BKK", "destination": c, "date": "2026-10-01"}) + tc("get_weather", {"location": c}))],
219
+ "tools": subs(["book_flight","get_weather","get_restaurant_info"])})
220
+ return examples[:n]
221
+
222
+ # ── GAP 7: Multi-turn tracking ──────────────────────────────────────────
223
+ def gap7_multiturn(n=40):
224
+ cities = ["Rome","Paris","Tokyo","London","Berlin","Madrid","Dubai","Seoul","Bangkok","Mumbai"]
225
+ tickers = ["NVDA","AMD","AAPL","MSFT","GOOGL","TSLA","AMZN","META"]
226
+ examples = []
227
+ for i in range(n):
228
+ c1, c2 = cities[i % len(cities)], cities[(i+1) % len(cities)]
229
+ t1, t2 = tickers[i % len(tickers)], tickers[(i+1) % len(tickers)]
230
+ # Weather → follow-up
231
+ examples.append({"messages": [
232
+ m("user", f"Weather in {c1}?"), m("assistant", tc=tc("get_weather", {"location": c1})),
233
+ m("tool", f"22C in {c1}"), m("user", f"And in {c2}?")],
234
+ "tools": subs(["get_weather","get_time"])})
235
+ # Stock → follow-up
236
+ examples.append({"messages": [
237
+ m("user", f"Price of {t1}?"), m("assistant", tc=tc("get_stock_price", {"ticker": t1})),
238
+ m("tool", "$800"), m("user", f"What about {t2}?")],
239
+ "tools": subs(["get_stock_price","get_news"])})
240
+ # News → search follow-up
241
+ examples.append({"messages": [
242
+ m("user", "Latest AI news"), m("assistant", tc=tc("get_news", {"topic": "AI", "count": 3})),
243
+ m("tool", "Story 1... Story 2..."), m("user", "Tell me more about story 1")],
244
+ "tools": subs(["get_news","search_web"])})
245
+ return examples[:n]
246
+
247
+ # ── Generate all ────────────────────────────────────────────────────────
248
+ GENERATORS = [
249
+ ("01-pure-tc", gap1_pure_tc, 100, "Pure tool-calling (no chat dilution)"),
250
+ ("02-irrelevance", gap2_irrelevance, 100, "Irrelevance expansion (proven 93.3%)"),
251
+ ("03-args-precision", gap3_args_precision, 80, "Argument precision (45.7% gap)"),
252
+ ("04-parallel", gap4_parallel, 60, "Parallel calls (multi-tool)"),
253
+ ("05-selection", gap5_selection, 60, "Selection hard negatives"),
254
+ ("06-multihop", gap6_multihop, 40, "Multi-hop chains"),
255
+ ("07-multiturn", gap7_multiturn, 40, "Multi-turn tracking"),
256
+ ]
257
+
258
+ total = 0
259
+ print("Gap-Filling Dataset Augmentation")
260
+ print(f"Target: Close 0.5B(91.2%) → 1.5B(48.2%) gap")
261
+ print("=" * 50)
262
+ for name, gen_fn, count, desc in GENERATORS:
263
+ batch = gen_fn(count)
264
+ save(name, batch)
265
+ all_examples.extend(batch)
266
+ total += len(batch)
267
+
268
+ combined = OUT / "all-gap-filled.jsonl"
269
+ with open(combined, "w") as f:
270
+ for ex in all_examples:
271
+ f.write(json.dumps(ex, ensure_ascii=False) + "\n")
272
+
273
+ print(f"\n{'=' * 50}")
274
+ print(f"TOTAL: {total} gap-filling examples")
275
+ print(f"{'=' * 50}")
276
+
277
+ # ── Full training data composition ──────────────────────────────────────
278
+ print(f"\n📊 Complete training dataset composition:")
279
+ print(f" v7 original: 2,424")
280
+ print(f" + 10x augment: 660")
281
+ print(f" + benchmark targ: 232")
282
+ print(f" + gap-fill: {total}")
283
+ print(f" = TOTAL: {2424 + 660 + 232 + total}")
284
+ print(f"\n📈 Gap analysis addressed:")
285
+ print(f" Root cause 1 (chat dilution): 100 pure TC examples")
286
+ print(f" Root cause 2 (args 45.7%): 80 precision examples")
287
+ print(f" Root cause 3 (irrelevance): 100 more irrelevance (was 60)")
288
+ print(f" Root cause 4 (parallel): 60 multi-tool examples")
289
+ print(f" Root cause 5 (selection): 60 hard negative pairs")
290
+ print(f" Root cause 6 (multi-hop): 40 chain examples")
291
+ print(f" Root cause 7 (multi-turn): 40 context tracking")