dsv4-flash-0731-vision / source /repository /data /validate_samples.py
sigilwen's picture
Back up private DSV4-VL source at 38faa0fcaff0
1d7c7c4 verified
Raw History Blame Contribute Delete
3.85 kB
#!/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()