File size: 3,850 Bytes
1d7c7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Phase 0 structural validation for random dataset samples.

The real DSV4-VL template gate is `vision/tests/test_template_encoding.py` and
runs after the zero-copy multimodal source checkpoint has been built.

Usage (pod): python validate_samples.py --dataset <path.jsonl> [--n 5]

Dataset rows use ms-swift messages format:
  {"messages": [{"role": "user", "content": "<image>What is this?"},
                {"role": "assistant", "content": "..."}],
   "images": ["/abs/path/img.jpg"]}
Text-only rows simply omit "images" (the 15-20% anti-forgetting fraction).
"""
import argparse, json, random, sys
from pathlib import Path


def validate_row(row):
    msgs = row['messages']
    assert msgs and msgs[-1]['role'] in {'assistant', 'tool_call'}, 'must end with assistant/tool_call turn'
    assert all(m['role'] in {'system', 'user', 'assistant', 'tool_call', 'tool'} for m in msgs), 'invalid message role'
    assert all(isinstance(m['content'], str) and m['content'].strip() for m in msgs), 'empty content'
    tool_roles = [m for m in msgs if m['role'] in {'tool_call', 'tool'}]
    tools = row.get('tools')
    assert not tool_roles or tools, 'tool messages require top-level tools'
    tool_names = set()
    for tool in tools or []:
        assert isinstance(tool, dict) and tool.get('type') == 'function', 'invalid tool wrapper'
        function = tool.get('function')
        assert isinstance(function, dict) and function.get('name'), 'invalid function schema'
        assert isinstance(function.get('parameters'), dict), 'tool parameters must be JSON Schema'
        tool_names.add(function['name'])
    for message in msgs:
        if message['role'] != 'tool_call':
            continue
        call = json.loads(message['content'])
        assert isinstance(call, dict) and call.get('name') in tool_names, 'undeclared tool call'
        assert isinstance(call.get('arguments'), dict), 'tool-call arguments must be an object'
    n_marker = sum(m['content'].count('<image>') for m in msgs)
    images = row.get('images', [])
    assert n_marker == len(images), f'{n_marker} <image> vs {len(images)} images'
    for p in images:
        assert Path(p).is_file(), f'missing image file {p}'
    return len(msgs), len(images)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--dataset', required=True)
    ap.add_argument('--n', type=int, default=5)
    ap.add_argument('--seed', type=int, default=0)
    ap.add_argument('--full', action='store_true', help='validate every row, not only the reservoir sample')
    args = ap.parse_args()

    rng = random.Random(args.seed)
    picks = []
    total = 0
    errors = 0
    with Path(args.dataset).open() as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                row = json.loads(line)
                if args.full:
                    validate_row(row)
            except Exception as error:
                errors += 1
                print(f'[line {line_number}] FAIL: {error}', file=sys.stderr)
                continue
            total += 1
            if len(picks) < args.n:
                picks.append(row)
            else:
                replacement = rng.randrange(total)
                if replacement < args.n:
                    picks[replacement] = row

    for i, row in enumerate(picks):
        try:
            message_count, image_count = validate_row(row)
            print(f'[{i}] structural ok: {message_count} messages, {image_count} image(s)')
        except Exception as error:
            errors += 1
            print(f'[{i}] FAIL: {error}', file=sys.stderr)
    print(f'validated reservoir={len(picks)} total_records={total} full={args.full}')
    sys.exit(1 if errors else 0)


if __name__ == '__main__':
    main()