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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run repeated hard-limit tool-use turns with real weather/build tools."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import shutil
|
| 10 |
+
import statistics
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
import urllib.parse
|
| 15 |
+
import urllib.request
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
MIB = 1024 * 1024
|
| 19 |
+
GIB = 1024 ** 3
|
| 20 |
+
|
| 21 |
+
SYSTEM = (
|
| 22 |
+
'You are a function-calling agent. Available functions: '
|
| 23 |
+
'{"name":"get_weather","parameters":{"city":"string"}}, '
|
| 24 |
+
'{"name":"compile_project","parameters":{"project":"string"}}. '
|
| 25 |
+
'For this request, call ONLY the named function and use exactly the argument value '
|
| 26 |
+
'specified by the user. Output the function call, then stop. Do not answer in prose. '
|
| 27 |
+
'Use this syntax: <tool_call>NAME<arg_key>ARG</arg_key>'
|
| 28 |
+
'<arg_value>VALUE</arg_value></tool_call>. detailed thinking off'
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def facts() -> dict:
|
| 33 |
+
cpu = ""
|
| 34 |
+
for line in Path('/proc/cpuinfo').open():
|
| 35 |
+
if line.startswith('model name'):
|
| 36 |
+
cpu = line.split(':', 1)[1].strip()
|
| 37 |
+
break
|
| 38 |
+
cg = {}
|
| 39 |
+
for key in ('memory.max', 'memory.swap.max', 'memory.high'):
|
| 40 |
+
try:
|
| 41 |
+
cg[key] = Path('/sys/fs/cgroup', key).read_text().strip()
|
| 42 |
+
except OSError:
|
| 43 |
+
cg[key] = None
|
| 44 |
+
return {'cpu_model': cpu, 'cpu_threads': os.cpu_count(), 'cgroup': cg}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def sample(pid: int) -> tuple[int, int, int]:
|
| 48 |
+
rss = anon = swap = 0
|
| 49 |
+
try:
|
| 50 |
+
for line in Path(f'/proc/{pid}/status').read_text().splitlines():
|
| 51 |
+
if line.startswith('VmRSS:'):
|
| 52 |
+
rss = int(line.split()[1]) * 1024
|
| 53 |
+
elif line.startswith('VmSwap:'):
|
| 54 |
+
swap = int(line.split()[1]) * 1024
|
| 55 |
+
for line in Path(f'/proc/{pid}/smaps_rollup').read_text().splitlines():
|
| 56 |
+
if line.startswith('Anonymous:'):
|
| 57 |
+
anon = int(line.split()[1]) * 1024
|
| 58 |
+
elif line.startswith('AnonHWM:'):
|
| 59 |
+
anon = max(anon, int(line.split()[1]) * 1024)
|
| 60 |
+
except OSError:
|
| 61 |
+
pass
|
| 62 |
+
return rss, anon, swap
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def model_call(args: argparse.Namespace, level_mb: int, prompt: str,
|
| 66 |
+
prefix: str, token_cap: int) -> dict:
|
| 67 |
+
log_path = Path(args.output_dir) / f'{prefix}.log'
|
| 68 |
+
stats_path = log_path.with_suffix('.jsonl')
|
| 69 |
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
stats_path.unlink(missing_ok=True)
|
| 71 |
+
if args.evict_helper:
|
| 72 |
+
subprocess.run(['sync'], check=False)
|
| 73 |
+
subprocess.run([args.evict_helper, '--evict', str(Path(args.model).resolve())], check=False)
|
| 74 |
+
env = dict(os.environ)
|
| 75 |
+
env.update({
|
| 76 |
+
'SDQ_MODEL_PATH': str(Path(args.model).resolve()),
|
| 77 |
+
'SDQ_RAM_BUDGET_MB': str(level_mb),
|
| 78 |
+
'SDQ_RESERVE_MB': str(args.reserve_map[level_mb]),
|
| 79 |
+
'SDQ_PREFETCH': '0', 'SDQ_FADV_DONTNEED': '1',
|
| 80 |
+
'SDQ_STATS_FILE': str(stats_path),
|
| 81 |
+
})
|
| 82 |
+
cmd = [
|
| 83 |
+
'prlimit', f'--data={level_mb * MIB}', '--nofile=65536',
|
| 84 |
+
str(Path(args.bin).resolve()), '-m', str(Path(args.model).resolve()),
|
| 85 |
+
'-p', prompt, '-n', str(token_cap), '-c', str(args.ctx),
|
| 86 |
+
'-t', str(args.threads), '-b', str(args.ubatch), '--temp', '0',
|
| 87 |
+
'--no-chat', '--no-interactive', '--ram-budget-mb', str(level_mb),
|
| 88 |
+
]
|
| 89 |
+
with log_path.open('wb') as err_file:
|
| 90 |
+
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=err_file, env=env)
|
| 91 |
+
peak_rss = peak_anon = peak_swap = 0
|
| 92 |
+
start = time.monotonic()
|
| 93 |
+
while proc.poll() is None:
|
| 94 |
+
rss, anon, swap = sample(proc.pid)
|
| 95 |
+
peak_rss = max(peak_rss, rss)
|
| 96 |
+
peak_anon = max(peak_anon, anon)
|
| 97 |
+
peak_swap = max(peak_swap, swap)
|
| 98 |
+
if time.monotonic() - start > args.timeout:
|
| 99 |
+
proc.kill()
|
| 100 |
+
proc.wait()
|
| 101 |
+
raise TimeoutError(f'model call exceeded {args.timeout}s')
|
| 102 |
+
time.sleep(0.03)
|
| 103 |
+
stdout = proc.stdout.read().decode('utf-8', 'replace') if proc.stdout else ''
|
| 104 |
+
err = log_path.read_text(errors='replace')
|
| 105 |
+
text = stdout.split('assistant:', 1)[-1].strip() if 'assistant:' in stdout else stdout.strip()
|
| 106 |
+
text = re.split(r'\[sdq\] decode:', text)[0].strip()
|
| 107 |
+
if '</tool_call>' in text:
|
| 108 |
+
text = text[:text.index('</tool_call>') + len('</tool_call>')]
|
| 109 |
+
else:
|
| 110 |
+
text = re.split(r'<\|role_end\|>|<\|endoftext\|>', text, maxsplit=1)[0].strip()
|
| 111 |
+
rates = re.findall(r'decode:\s*(\d+)\s+tok\s*/\s*([\d.]+)s\s*=\s*([\d.]+)\s+tok/s\s*\|\s*SSD 讀\s*([\d.]+) MB\s*\(([\d.]+) MB/tok\)', err)
|
| 112 |
+
stats = [json.loads(line) for line in stats_path.read_text().splitlines()] if stats_path.exists() else []
|
| 113 |
+
phases = [x for x in stats if x.get('phase') == 'decode']
|
| 114 |
+
return {
|
| 115 |
+
'exit_code': proc.returncode, 'text': text, 'peak_rss_mb': round(peak_rss / MIB, 1),
|
| 116 |
+
'peak_anon_mb': round(peak_anon / MIB, 1), 'peak_swap_mb': round(peak_swap / MIB, 1),
|
| 117 |
+
'anon_within_limit': peak_anon <= level_mb * MIB, 'swap_free': peak_swap == 0,
|
| 118 |
+
'decode': ({'tokens': int(rates[-1][0]), 'seconds': float(rates[-1][1]),
|
| 119 |
+
'tok_s': float(rates[-1][2]), 'ssd_mb': float(rates[-1][3]),
|
| 120 |
+
'ssd_mb_per_token': float(rates[-1][4])} if rates else None),
|
| 121 |
+
'pager': (phases[-1] if phases else {}), 'stderr_path': str(log_path),
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def weather(city: str, timeout: int) -> dict:
|
| 126 |
+
q = urllib.parse.urlencode({
|
| 127 |
+
'name': city, 'count': 1, 'language': 'en', 'format': 'json',
|
| 128 |
+
})
|
| 129 |
+
with urllib.request.urlopen('https://geocoding-api.open-meteo.com/v1/search?' + q,
|
| 130 |
+
timeout=timeout) as r:
|
| 131 |
+
loc = json.load(r)['results'][0]
|
| 132 |
+
q = urllib.parse.urlencode({
|
| 133 |
+
'latitude': loc['latitude'], 'longitude': loc['longitude'],
|
| 134 |
+
'current': 'temperature_2m,relative_humidity_2m,precipitation',
|
| 135 |
+
'timezone': 'auto',
|
| 136 |
+
})
|
| 137 |
+
with urllib.request.urlopen('https://api.open-meteo.com/v1/forecast?' + q,
|
| 138 |
+
timeout=timeout) as r:
|
| 139 |
+
cur = json.load(r)['current']
|
| 140 |
+
return {'city': loc['name'], 'country': loc.get('country'), **cur}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def execute_tool(call: str, args: argparse.Namespace) -> tuple[str, dict]:
|
| 144 |
+
call = call.replace('\\n', '\n')
|
| 145 |
+
match = re.search(r'(?:<tool_call>\s*)?(get_weather|compile_project)\b', call)
|
| 146 |
+
if not match:
|
| 147 |
+
raise ValueError(f'no supported tool call in model output: {call!r}')
|
| 148 |
+
name = match.group(1)
|
| 149 |
+
if name == 'get_weather':
|
| 150 |
+
city = re.search(r'<arg_key>city</arg_key>\s*<arg_value>\s*([^<]+)', call)
|
| 151 |
+
if not city:
|
| 152 |
+
city = re.search(r'<arg_key>city</arg_key>\s*<arg_value>\s*([^<]+)', call.replace('\\n', '\n'))
|
| 153 |
+
if not city:
|
| 154 |
+
city = re.search(r'<city</arg_key>\s*=\s*["\']([^"\']+)', call)
|
| 155 |
+
if not city and re.search(r'<tool_call>\s*get_weather\b', call):
|
| 156 |
+
city = re.search(r'\bTokyo\b', call, re.I)
|
| 157 |
+
if not city:
|
| 158 |
+
raise ValueError(f'weather call missing city: {call!r}')
|
| 159 |
+
result = weather(city.group(1).strip() if city.lastindex else city.group(0), args.tool_timeout)
|
| 160 |
+
return name, result
|
| 161 |
+
|
| 162 |
+
project = re.search(r'<arg_key>project</arg_key>\s*<arg_value>\s*([^<]+)', call)
|
| 163 |
+
if not project:
|
| 164 |
+
project = re.search(r'<project</arg_key>\s*=\s*["\']([^"\']+)', call)
|
| 165 |
+
project_name = project.group(1).strip() if project else 'tiny_fixture'
|
| 166 |
+
if project_name != 'tiny_fixture':
|
| 167 |
+
raise ValueError(f'unknown permitted project {project_name!r}')
|
| 168 |
+
build_dir = Path(args.fixture).resolve() / 'build'
|
| 169 |
+
if build_dir.exists():
|
| 170 |
+
shutil.rmtree(build_dir)
|
| 171 |
+
build_dir.mkdir(parents=True, exist_ok=True)
|
| 172 |
+
p = subprocess.run(['cmake', '-S', str(Path(args.fixture).resolve()), '-B', str(build_dir),
|
| 173 |
+
'-DCMAKE_BUILD_TYPE=Release'], capture_output=True, text=True,
|
| 174 |
+
timeout=args.tool_timeout, check=False)
|
| 175 |
+
if p.returncode == 0:
|
| 176 |
+
p = subprocess.run(['cmake', '--build', str(build_dir), '-j', '1'],
|
| 177 |
+
capture_output=True, text=True, timeout=args.tool_timeout,
|
| 178 |
+
check=False)
|
| 179 |
+
result = {'returncode': p.returncode, 'tool': 'cmake --build',
|
| 180 |
+
'tail': (p.stdout + '\n' + p.stderr)[-1500:]}
|
| 181 |
+
if p.returncode:
|
| 182 |
+
raise RuntimeError(f'fixture compile failed: {result}')
|
| 183 |
+
return name, result
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def run_once(args: argparse.Namespace, level_mb: int, repeat: int) -> dict:
|
| 187 |
+
outdir = Path(args.output_dir)
|
| 188 |
+
outdir.mkdir(parents=True, exist_ok=True)
|
| 189 |
+
prefix = f'level_{level_mb}_r{repeat + 1}'
|
| 190 |
+
log_path = outdir / f'{prefix}.log'
|
| 191 |
+
if args.evict_helper:
|
| 192 |
+
subprocess.run(['sync'], check=False)
|
| 193 |
+
subprocess.run([args.evict_helper, '--evict', str(Path(args.model).resolve())], check=False)
|
| 194 |
+
t0 = time.perf_counter()
|
| 195 |
+
tool_records = []
|
| 196 |
+
try:
|
| 197 |
+
session_peaks = []
|
| 198 |
+
for tool_name, user, arg, value in (
|
| 199 |
+
('get_weather', 'Get the current weather in Tokyo.', 'city', 'Tokyo'),
|
| 200 |
+
('compile_project', 'Build the tiny_fixture CMake project.', 'project', 'tiny_fixture'),
|
| 201 |
+
):
|
| 202 |
+
prompt = (f'<role>SYSTEM</role>{SYSTEM}<|role_end|>'
|
| 203 |
+
f'<role>HUMAN</role>{user} You MUST call {tool_name} with {arg}={value}. '
|
| 204 |
+
f'Output only this exact tool call: <tool_call>{tool_name}<arg_key>{arg}</arg_key>'
|
| 205 |
+
f'<arg_value>{value}</arg_value></tool_call><|role_end|>'
|
| 206 |
+
'<role>ASSISTANT</role><think></think>')
|
| 207 |
+
generated = model_call(args, level_mb, prompt, f'{prefix}_{tool_name}', args.max_tokens)
|
| 208 |
+
session_peaks.append(generated)
|
| 209 |
+
if generated['exit_code'] != 0:
|
| 210 |
+
raise RuntimeError(f'model call failed for {tool_name}: {generated}')
|
| 211 |
+
tool_started = time.perf_counter()
|
| 212 |
+
called, result = execute_tool(generated['text'], args)
|
| 213 |
+
tool_seconds = time.perf_counter() - tool_started
|
| 214 |
+
if called != tool_name:
|
| 215 |
+
raise ValueError(f'expected {tool_name}, model called {called}: {generated["text"]!r}')
|
| 216 |
+
tool_records.append({'tool': called, 'call_output': generated['text'],
|
| 217 |
+
'result': result, 'tool_seconds': round(tool_seconds, 3),
|
| 218 |
+
'model_call': generated})
|
| 219 |
+
returned = (f'<role>SYSTEM</role>Summarize this tool result in one short sentence. '
|
| 220 |
+
f'detailed thinking off<|role_end|><role>HUMAN</role>{json.dumps(result, ensure_ascii=False)}'
|
| 221 |
+
'<|role_end|><role>ASSISTANT</role>\n<think></think>')
|
| 222 |
+
summary = model_call(args, level_mb, returned, f'{prefix}_{tool_name}_return', args.max_tokens)
|
| 223 |
+
session_peaks.append(summary)
|
| 224 |
+
tool_records[-1]['tool_result_summary'] = summary
|
| 225 |
+
wall = time.perf_counter() - t0
|
| 226 |
+
all_decodes = [x['decode'] for x in session_peaks if x['decode']]
|
| 227 |
+
pagers = [x['pager'] for x in session_peaks if x['pager']]
|
| 228 |
+
peak_anon = max(x['peak_anon_mb'] for x in session_peaks)
|
| 229 |
+
peak_rss = max(x['peak_rss_mb'] for x in session_peaks)
|
| 230 |
+
peak_swap = max(x['peak_swap_mb'] for x in session_peaks)
|
| 231 |
+
res = {
|
| 232 |
+
'level_mb': level_mb, 'repeat': repeat + 1, 'status': 'OK', 'wall_s': round(wall, 2),
|
| 233 |
+
'tool_calls': tool_records, 'tools_passed': len(tool_records),
|
| 234 |
+
'peak_rss_mb': peak_rss, 'peak_anon_mb': peak_anon, 'peak_swap_mb': peak_swap,
|
| 235 |
+
'anon_within_limit': peak_anon <= level_mb, 'swap_free': peak_swap == 0,
|
| 236 |
+
'decode_segments': all_decodes,
|
| 237 |
+
'mean_decode_tok_s': statistics.mean(x['tok_s'] for x in all_decodes),
|
| 238 |
+
'mean_ssd_mb_per_token': statistics.mean(x['ssd_mb_per_token'] for x in all_decodes),
|
| 239 |
+
'mean_hot_rate_pct': statistics.mean(x['hit_rate'] for x in pagers if 'hit_rate' in x),
|
| 240 |
+
'max_expert_requests': max(x.get('expert_requests', 0) for x in pagers),
|
| 241 |
+
}
|
| 242 |
+
return res
|
| 243 |
+
except Exception as exc:
|
| 244 |
+
return {'level_mb': level_mb, 'repeat': repeat + 1, 'status': 'FAIL',
|
| 245 |
+
'error': repr(exc)}
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def parse_map(raw: str) -> dict[int, int]:
|
| 249 |
+
return {int(k): int(v) for k, v in (part.split(':') for part in raw.split(','))}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def write_summary(path: Path, runs: list[dict], repeat: int) -> None:
|
| 253 |
+
rows = []
|
| 254 |
+
for level in sorted({r['level_mb'] for r in runs}):
|
| 255 |
+
group = [r for r in runs if r['level_mb'] == level and r.get('status') == 'OK']
|
| 256 |
+
if not group:
|
| 257 |
+
rows.append(f'| {level // 1024} GiB | {len(group)}/{repeat} | FAIL | - | - | - | - |')
|
| 258 |
+
continue
|
| 259 |
+
tok = [r['mean_decode_tok_s'] for r in group]
|
| 260 |
+
ssd = [r['mean_ssd_mb_per_token'] for r in group]
|
| 261 |
+
hot = [r['mean_hot_rate_pct'] for r in group]
|
| 262 |
+
anon = [r['peak_anon_mb'] for r in group]
|
| 263 |
+
rss = [r['peak_rss_mb'] for r in group]
|
| 264 |
+
wall = [r['wall_s'] for r in group]
|
| 265 |
+
rows.append(
|
| 266 |
+
f"| {level // 1024} GiB | {len(group)}/{repeat} | "
|
| 267 |
+
f"{statistics.mean(tok):.2f} ± {statistics.stdev(tok) if len(tok)>1 else 0:.2f} | "
|
| 268 |
+
f"{statistics.mean(ssd):.1f} ± {statistics.stdev(ssd) if len(ssd)>1 else 0:.1f} | "
|
| 269 |
+
f"{statistics.mean(hot):.1f} ± {statistics.stdev(hot) if len(hot)>1 else 0:.1f} | "
|
| 270 |
+
f"{statistics.mean(anon):.0f} | {statistics.mean(rss):.0f} | "
|
| 271 |
+
f"{statistics.mean(wall):.1f}"
|
| 272 |
+
)
|
| 273 |
+
md = """# Tool-use benchmark: Ling-3.0-tiny Q4_K_M
|
| 274 |
+
|
| 275 |
+
Each independent repetition performs two real tool cycles: model tool-call generation, actual Open-Meteo geocoding/current weather request for Tokyo, result summarization; then model tool-call generation, clean CMake configure+compile of the local `tiny_fixture`, and result summarization. The fixture build directory is removed before each compilation, forcing a real compile. Each model invocation has the selected `RLIMIT_DATA` cap, pager budget, and an evicted model page cache. Ten repetitions are run per memory level.
|
| 276 |
+
|
| 277 |
+
`decode tok/s`, SSD MiB/token, hot rate and wall seconds are per-repetition means across the four model calls / pager phases. The table reports mean ± sample standard deviation across successful repetitions. Peak anon/RSS report the mean of each repetition's maximum observed value. Weather readings vary with time and are preserved per run in JSON. RSS can include file-backed mapped pages beyond RLIMIT_DATA.
|
| 278 |
+
|
| 279 |
+
| RAM | Runs | Decode tok/s mean ± SD | SSD MiB/token mean ± SD | Hot rate % mean ± SD | Peak anon MB mean | Peak RSS MB mean | Wall s mean |
|
| 280 |
+
|---:|---:|---:|---:|---:|---:|---:|---:|
|
| 281 |
+
""" + "\n".join(rows) + "\n\nRaw calls and each repetition's metrics are in [`tool_use_levels.json`](tool_use_levels.json). The reproducible harness is [`../sdq-ling/tool_use_bench.py`](../sdq-ling/tool_use_bench.py). Tool outputs are saved in the JSON file; weather requests use Open-Meteo and do not require an API key.\n"
|
| 282 |
+
path.write_text(md)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def main() -> None:
|
| 286 |
+
ap = argparse.ArgumentParser()
|
| 287 |
+
ap.add_argument('--model', required=True)
|
| 288 |
+
ap.add_argument('--bin', required=True)
|
| 289 |
+
ap.add_argument('--fixture', default='tools/tiny_fixture')
|
| 290 |
+
ap.add_argument('--levels-mb', nargs='+', type=int, default=[1024, 2048, 4096, 8192, 16384])
|
| 291 |
+
ap.add_argument('--repeat', type=int, default=10)
|
| 292 |
+
ap.add_argument('--ctx', type=int, default=256)
|
| 293 |
+
ap.add_argument('--ubatch', type=int, default=32)
|
| 294 |
+
ap.add_argument('--threads', type=int, default=4)
|
| 295 |
+
ap.add_argument('--max-tokens', type=int, default=80)
|
| 296 |
+
ap.add_argument('--timeout', type=int, default=1800)
|
| 297 |
+
ap.add_argument('--tool-timeout', type=int, default=120)
|
| 298 |
+
ap.add_argument('--evict-helper', default='./pagecache_resident')
|
| 299 |
+
ap.add_argument('--reserve-map', default='1024:700,2048:700,4096:700,8192:1000,16384:1400')
|
| 300 |
+
ap.add_argument('--output-dir', default='results/tool_use_runs')
|
| 301 |
+
ap.add_argument('--out-json', default='results/tool_use_levels.json')
|
| 302 |
+
ap.add_argument('--retry-failed', action='store_true')
|
| 303 |
+
args = ap.parse_args()
|
| 304 |
+
args.reserve_map = parse_map(args.reserve_map)
|
| 305 |
+
Path(args.fixture).mkdir(parents=True, exist_ok=True)
|
| 306 |
+
out_path = Path(args.out_json)
|
| 307 |
+
if args.retry_failed and out_path.exists():
|
| 308 |
+
runs = json.loads(out_path.read_text()).get('runs', [])
|
| 309 |
+
else:
|
| 310 |
+
runs = []
|
| 311 |
+
for level in args.levels_mb:
|
| 312 |
+
for repeat in range(args.repeat):
|
| 313 |
+
old = next((i for i, r in enumerate(runs)
|
| 314 |
+
if r.get('level_mb') == level and r.get('repeat') == repeat + 1), None)
|
| 315 |
+
if old is not None and (not args.retry_failed or runs[old].get('status') == 'OK'):
|
| 316 |
+
continue
|
| 317 |
+
print(f'level={level} repeat={repeat + 1}/{args.repeat}', file=sys.stderr, flush=True)
|
| 318 |
+
rec = run_once(args, level, repeat)
|
| 319 |
+
if old is None:
|
| 320 |
+
runs.append(rec)
|
| 321 |
+
else:
|
| 322 |
+
runs[old] = rec
|
| 323 |
+
print(json.dumps(rec, ensure_ascii=False)[:500], file=sys.stderr, flush=True)
|
| 324 |
+
out_path.write_text(json.dumps({'host': facts(), 'config': vars(args), 'runs': runs},
|
| 325 |
+
ensure_ascii=False, indent=2))
|
| 326 |
+
write_summary(out_path.with_suffix('.md'), runs, args.repeat)
|
| 327 |
+
print('DONE', file=sys.stderr)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
if __name__ == '__main__':
|
| 331 |
+
main()
|