File size: 12,875 Bytes
17b0632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""Audit data_native/*.jsonl splits for the MiniCPM5-1B tool-call pipeline.

Read-only: never modifies the data. Reports per-split stats and data bugs.

Usage:
    python pipeline/audit_dataset.py --data data_native --out reports
"""
import argparse
import collections
import json
from pathlib import Path


def load_rows(path):
    rows = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def first_user_content(messages):
    for m in messages:
        if m.get("role") == "user":
            return m.get("content", "") or ""
    return ""


def all_calls(messages):
    calls = []
    for m in messages:
        if m.get("role") == "assistant":
            for c in m.get("tool_calls") or []:
                calls.append(c)
    return calls


def tool_required(tool):
    """Return the required-arg list, handling both schema placements."""
    req = tool.get("required")
    if isinstance(req, list) and req:
        return req
    params = tool.get("parameters") or {}
    if isinstance(params, dict):
        req = params.get("required")
        if isinstance(req, list) and req:
            return req
    return []


def arg_kind(v):
    if isinstance(v, bool):
        return "bool"
    if isinstance(v, (int, float)):
        return "number"
    if isinstance(v, str):
        return "string"
    if isinstance(v, list):
        return "list"
    if isinstance(v, dict):
        return "object"
    if v is None:
        return "null"
    return "other"


def has_deep_nesting(v):
    if isinstance(v, dict):
        return any(isinstance(x, (dict, list)) for x in v.values())
    if isinstance(v, list):
        return any(isinstance(x, (dict, list)) for x in v)
    return False


def percentile(sorted_vals, p):
    if not sorted_vals:
        return 0
    idx = min(int(len(sorted_vals) * p), len(sorted_vals) - 1)
    return sorted_vals[idx]


def audit_split(name, rows, tokenizer):
    n = len(rows)
    users = [first_user_content(r.get("messages", [])) for r in rows]
    uniq = len(set(users))
    dup_rate = 1.0 - uniq / n if n else 0.0

    tok_lens, render_errors = [], 0
    for r in rows:
        try:
            text = tokenizer.apply_chat_template(
                r["messages"], tools=r.get("tools"), tokenize=False
            )
            ids = tokenizer(text, add_special_tokens=False)["input_ids"]
            tok_lens.append(len(ids))
        except Exception:
            render_errors += 1
    tok_lens.sort()

    tool_buckets = collections.Counter()
    for r in rows:
        k = len(r.get("tools") or [])
        if k <= 1:
            tool_buckets["1"] += 1
        elif k <= 4:
            tool_buckets["2-4"] += 1
        elif k <= 9:
            tool_buckets["5-9"] += 1
        else:
            tool_buckets["10+"] += 1

    call_buckets = collections.Counter()
    arg_types = collections.Counter()
    calls_with_complex = 0  # any arg is list/dict
    calls_with_deep = 0  # nested inside a list/dict arg
    total_calls = 0
    for r in rows:
        calls = all_calls(r.get("messages", []))
        total_calls += len(calls)
        call_buckets["0" if not calls else "1" if len(calls) == 1 else "2+"] += 1
        for c in calls:
            args = c.get("arguments") or {}
            complex_hit, deep_hit = False, False
            for v in args.values():
                kind = arg_kind(v)
                arg_types[kind] += 1
                if kind in ("list", "object"):
                    complex_hit = True
                if has_deep_nesting(v):
                    deep_hit = True
            calls_with_complex += complex_hit
            calls_with_deep += deep_hit

    # schema coverage
    n_tools, tools_with_required = 0, 0
    calls_missing_required = 0
    rows_missing_required = 0
    for r in rows:
        tools = r.get("tools") or []
        by_name = {t.get("name"): t for t in tools if isinstance(t, dict)}
        n_tools += len(tools)
        for t in tools:
            if tool_required(t):
                tools_with_required += 1
        row_bad = False
        for c in all_calls(r.get("messages", [])):
            schema = by_name.get(c.get("name"))
            if schema is None:
                continue  # counted as a bug flag instead
            req = tool_required(schema)
            if req:
                given = c.get("arguments") or {}
                if any(k not in given for k in req):
                    calls_missing_required += 1
                    row_bad = True
        rows_missing_required += row_bad

    abstention = sum(1 for r in rows if not all_calls(r.get("messages", [])))

    # stage-2 type for multi-turn rows
    stage2 = None
    if name.startswith("mt_"):
        s2 = collections.Counter()
        for r in rows:
            assistants = [m for m in r.get("messages", []) if m.get("role") == "assistant"]
            last = assistants[-1] if assistants else {}
            s2["call" if (last.get("tool_calls") or []) else "text"] += 1
        stage2 = dict(s2)

    freq = collections.Counter()
    for r in rows:
        for c in all_calls(r.get("messages", [])):
            freq[c.get("name", "<missing>")] += 1

    # bug flags
    bugs = collections.Counter()
    bug_examples = collections.defaultdict(list)
    seen_prompts = set()
    for i, r in enumerate(rows):
        msgs = r.get("messages", [])
        tools = r.get("tools") or []
        names = {t.get("name") for t in tools if isinstance(t, dict)}
        if not tools:
            bugs["empty_tools_list"] += 1
            bug_examples["empty_tools_list"].append(i)
        u = first_user_content(msgs)
        if not (u or "").strip():
            bugs["empty_user_content"] += 1
            bug_examples["empty_user_content"].append(i)
        if u in seen_prompts:
            bugs["duplicate_user_prompt"] += 1
        else:
            seen_prompts.add(u)
        for j, m in enumerate(msgs):
            if m.get("role") == "assistant":
                content = m.get("content", "")
                tc = m.get("tool_calls") or []
                if (not (content or "").strip()) and not tc:
                    bugs["empty_assistant_no_call"] += 1
                    bug_examples["empty_assistant_no_call"].append(i)
                    break
                for c in tc:
                    if c.get("name") not in names:
                        bugs["call_name_not_in_tools"] += 1
                        bug_examples["call_name_not_in_tools"].append(i)
                        break
            if m.get("role") == "tool":
                prior_call = any(
                    (pm.get("role") == "assistant" and (pm.get("tool_calls") or []))
                    for pm in msgs[:j]
                )
                if not prior_call:
                    bugs["tool_without_preceding_call"] += 1
                    bug_examples["tool_without_preceding_call"].append(i)
                    break

    return {
        "rows": n,
        "unique_user_prompts": uniq,
        "duplicate_rate": round(dup_rate, 4),
        "rendered_tokens": {
            "p50": percentile(tok_lens, 0.5),
            "p90": percentile(tok_lens, 0.9),
            "max": max(tok_lens) if tok_lens else 0,
            "render_errors": render_errors,
        },
        "tool_count_dist": {k: tool_buckets.get(k, 0) for k in ("1", "2-4", "5-9", "10+")},
        "call_count_dist": {k: call_buckets.get(k, 0) for k in ("0", "1", "2+")},
        "total_calls": total_calls,
        "arg_types": {k: arg_types.get(k, 0) for k in ("string", "number", "bool", "list", "object", "null", "other")},
        "calls_with_complex_arg": calls_with_complex,
        "calls_with_deep_nesting": calls_with_deep,
        "schema": {
            "n_tools": n_tools,
            "tools_with_required": tools_with_required,
            "calls_missing_required_arg": calls_missing_required,
            "rows_missing_required_arg": rows_missing_required,
        },
        "abstention_rows": abstention,
        "abstention_share": round(abstention / n, 4) if n else 0.0,
        "stage2_dist": stage2,
        "top_tools": freq.most_common(5),
        "bugs": dict(bugs),
        "bug_row_examples": {k: v[:5] for k, v in bug_examples.items()},
    }


def write_markdown(report, splits):
    L = ["# Dataset Audit", ""]
    L.append("| Split | Rows | Uniq prompts | Dup rate | p50 | p90 | Max | Abstain |")
    L.append("|---|---|---|---|---|---|---|---|---|")
    for s in splits:
        d = report[s]
        t = d["rendered_tokens"]
        L.append(
            f"| {s} | {d['rows']} | {d['unique_user_prompts']} | {d['duplicate_rate']:.2%} "
            f"| {t['p50']} | {t['p90']} | {t['max']} | {d['abstention_share']:.2%} |"
        )
    L += ["", "## Tool / call counts", "",
          "| Split | Tools 1 | 2-4 | 5-9 | 10+ | Calls 0 | 1 | 2+ |",
          "|---|---|---|---|---|---|---|---|"]
    for s in splits:
        d = report[s]
        tc, cc = d["tool_count_dist"], d["call_count_dist"]
        L.append(f"| {s} | {tc['1']} | {tc['2-4']} | {tc['5-9']} | {tc['10+']} "
                 f"| {cc['0']} | {cc['1']} | {cc['2+']} |")
    L += ["", "## Argument types (whole dataset: all splits pooled)", ""]
    pool = collections.Counter()
    cx = dx = 0
    for s in splits:
        pool.update({k: v for k, v in report[s]["arg_types"].items()})
        cx += report[s]["calls_with_complex_arg"]
        dx += report[s]["calls_with_deep_nesting"]
    tot = sum(pool.values()) or 1
    L.append("| Type | Count | Share |")
    L.append("|---|---|---|")
    for k in ("string", "number", "bool", "list", "object", "null", "other"):
        L.append(f"| {k} | {pool.get(k, 0)} | {pool.get(k, 0) / tot:.2%} |")
    L.append(f"| calls with list/dict arg | {cx} | |")
    L.append(f"| calls with deep nesting | {dx} | |")
    L += ["", "## Schema coverage (required args)", "",
          "| Split | Tools w/ required | Calls omitting required | Rows affected |",
          "|---|---|---|---|"]
    for s in splits:
        sc = report[s]["schema"]
        L.append(f"| {s} | {sc['tools_with_required']}/{sc['n_tools']} "
                 f"| {sc['calls_missing_required_arg']} | {sc['rows_missing_required_arg']} |")
    mt = [s for s in splits if s.startswith("mt_")]
    if mt:
        L += ["", "## Multi-turn stage-2 (last assistant message)", "",
              "| Split | call | text |", "|---|---|---|"]
        for s in mt:
            s2 = report[s]["stage2_dist"] or {}
            L.append(f"| {s} | {s2.get('call', 0)} | {s2.get('text', 0)} |")
    L += ["", "## Top tools per split", ""]
    for s in splits:
        top = ", ".join(f"{k} ({v})" for k, v in report[s]["top_tools"])
        L.append(f"- **{s}**: {top}")
    L += ["", "## Bug flags", "",
          "| Split | Flag | Count | Example rows |",
          "|---|---|---|---|"]
    any_bug = False
    for s in splits:
        for flag, cnt in sorted(report[s]["bugs"].items()):
            any_bug = True
            ex = report[s]["bug_row_examples"].get(flag, [])
            L.append(f"| {s} | {flag} | {cnt} | {ex} |")
    if not any_bug:
        L.append("| (all splits) | no flags | 0 | — |")
    L += ["", "## Notes",
          "- `hard_test.jsonl` (50 rows) exists in `data_native/` but is not documented in its README.",
          "- 3 train rows render above the 1,400-token filter stated in the README (max 1,736); "
          "likely tokenizer/template drift since generation. 79/7,600 train rows exceed the "
          "1,280-token training cap and will be truncated at train time."]
    L.append("")
    return "\n".join(L)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", default="data_native")
    ap.add_argument("--out", default="reports")
    args = ap.parse_args()

    from transformers import AutoTokenizer
    tok = AutoTokenizer.from_pretrained("openbmb/MiniCPM5-1B", trust_remote_code=True)

    data_dir = Path(args.data)
    files = sorted(data_dir.glob("*.jsonl"))
    if not files:
        raise SystemExit(f"no .jsonl files in {data_dir}")
    report, order = {}, []
    for fp in files:
        name = fp.stem
        order.append(name)
        rows = load_rows(fp)
        print(f"{name}: {len(rows)} rows, auditing...", flush=True)
        report[name] = audit_split(name, rows, tok)

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    with open(out / "dataset_audit.json", "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    with open(out / "dataset_audit.md", "w", encoding="utf-8") as f:
        f.write(write_markdown(report, order))
    print(f"wrote {out / 'dataset_audit.json'} and {out / 'dataset_audit.md'}")


if __name__ == "__main__":
    main()