МАТЧАСТЬMASTER PLAN 7 · QWEN WORKER BENCHMARK

Порядок выполнения уточнён

Эта глава входит в готовый комплект из 26 документов. Статус реализации хранится в журнале; требования главы сами по себе не являются выполненной работой.

[7.1] QWB-01 — карточка выполнения. Весь план и его состояние.

Уточнения для этой главы

[7.0.6] Qwen benchmark — отдельная необязательная для первого пилота ветка после основной цепочки. До решения QWB-08 использовать deterministic code и текущего Writer. TM-10 и ER-04 могут записать MODEL_NOT_AVAILABLE и доказанный lexical/manual baseline; не загружать новую модель и не объявлять её проверенной. Автоматическая семантика включается только по измерениям.

Mathchast / Qwen Worker Benchmark / 7

CHEAP
ONLY IF
TRUSTED.

Локальная модель полезна только там, где её ошибки измеримы, обнаружимы и дешевле результата сильной модели.

Qwen 3 30B на SRV2 уже запускается через llama.cpp, но широкое качество не доказано. Никакого production trust до task-specific benchmark.

QWEN IS A WORKER CANDIDATE, NOT THE PRIMARY WRITER.
Benchmark per task → compare baselines → set gates → enable narrow routing → monitor drift → rollback fast.

Не «умная ли модель?».
Какие задачи ей можно дать?

Для каждой candidate-role нужно отдельно доказать качество, schema compliance, стабильность, latency/throughput, обнаружимость ошибок и экономический смысл относительно deterministic code, Luna Medium и strong-model fallback.

PRIMARY OUTCOME
Routing matrix.

Каждая task family получает статус CODE / QWEN_APPROVED / QWEN_WITH_GATE / LUNA / STRONG_MODEL / DISABLED.

QUALITY
Task-specific.

Модель может быть хороша в classification и плоха в factual extraction. Один общий benchmark score запрещён.

COST
Real savings.

Локальная inference имеет стоимость GPU/CPU/RAM, latency и operations. «Бесплатно» — неверная модель мышления.

SAFETY
Detect failures.

Лучшие Qwen-задачи — те, где output структурирован, проверяем кодом и легко эскалируется при сомнении.

Non-goalНе использовать этот benchmark, чтобы заменить Luna Medium как основного Writer. Primary Writer уже зафиксирован; Qwen рассматривается как дешёвый узкий worker.

Measure what
already exists.

QWEN CAPABILITY AUDIT 1. Inspect SRV2 runtime: llama.cpp build/version model files / quantization launch flags context size GPU/CPU offload threads / batch / parallel slots memory usage 2. Inspect existing wrappers: HTTP server / CLI prompt templates structured-output handling timeouts / retries logging / metrics 3. Inspect any previous benchmarks/results. 4. Search current pipeline for local-model calls. 5. Verify hardware contention: does inference affect Radar / DB / Work / other services? 6. Record exact baseline configuration. 7. Reuse existing runner where safe. Extend/wrap before new worker service.
✓
Benchmark должен pin-ить model hash, quantization, llama.cpp version и runtime flags.
✓
Нельзя сравнивать результаты разных runtime configs как будто это одна и та же модель.
✓
Если existing wrapper уже даёт health/timeouts/metrics — reuse/extend.
×
Не строить отдельную generic AI queue, если D15/existing job patterns подходят.

Prefer bounded
structured work.

Task familyWhy candidateMain risk
schema extractionConvert selected text into bounded JSON fields.Invented values / wrong normalization.
classificationSource type, evidence class, topic hints, queue labels.Confident misclassification.
entity normalization assistAliases, likely entity match, disambiguation candidates.Merging distinct entities.
question dedupNormalize/cluster NEED_MORE_RESEARCH questions.False merge losing a real gap.
source triageLow-cost semantic ranking before deep research.Dropping a valuable unfamiliar source.
short summarizationCompact selected evidence for internal routing.Hallucination / omitted caveat.
translation assistCross-language understanding for selected snippets.Technical nuance loss.
claim/fact candidate extractionPropose atomic units for deterministic validation.Unsupported claim insertion.
QA precheckFlag suspicious gaps before strong gate.False reassurance if treated as authority.
topic/angle clustering assistSemantic hints when embeddings/rules are ambiguous.Opaque clustering bias.
Do code firstExact parsing, hashes, URL normalization, timestamps, schema validation, arithmetic, dedup by stable IDs and deterministic business rules остаются кодом. Не отдавать ИИ то, что надёжнее делает функция.

No broad trust
by default.

PRIMARY WRITER
Запрещено считать Qwen default Writer. Luna Medium в Zed остаётся primary writer.
FINAL FACT CHECK
Qwen не является финальным arbiter истины. Может precheck/flag, но critical gate требует evidence-based deterministic/stronger path.
FINAL DUPLICATE DECISION
Может дать feature/review hint только после benchmark; финальная policy остаётся в Article Duplicate Guard.
PUBLISH DECISION
Не принимает решение о release/deploy.
UNBOUNDED WEB RESEARCH
Не запускается как автономный исследователь без evidence budget/contracts.
SECURITY DECISIONS
Не получает право менять credentials, permissions или bypass safety bounds.

Same tasks.
Same rubric.

FOR EACH TASK FAMILY: dataset ├─ normal cases ├─ hard cases ├─ ambiguous cases ├─ adversarial / misleading cases ├─ multilingual cases └─ missing-information cases systems: A. deterministic code baseline, where applicable B. Qwen local candidate C. Luna Medium baseline D. strong-model adjudication/reference on selected disagreements same input contract same output schema same scoring rubric multiple runs where stochastic variance matters blind/manual review sample cost + latency + resource metrics
GOLD LABELS
Для bounded tasks нужен curated gold set. Где абсолютный gold невозможен — pairwise adjudication + explicit rubric.
HOLDOUT
Часть benchmark cases не использовать при prompt tuning, иначе результат будет самообманом.
REAL DATA
Использовать actual Mathchast examples из Radar/Research Pack, обезличенные/безопасные по необходимости.
REPEATABILITY
Хранить prompt/template version, seed/settings if available, model/runtime version and output hashes.

Quality, cost,
detectability.

MetricWhy it matters
exact / field accuracyCore correctness for structured tasks.
precision / recall / F1Needed for classifiers/extractors where misses and false positives differ.
schema-valid rateCan downstream parse output without repair?
hallucination rateInvented facts/fields/reasons are high-risk.
unsupported assertion rateEspecially important for evidence tasks.
abstention qualityDoes model say UNKNOWN/NEED_REVIEW when evidence is missing?
critical error rateErrors that could corrupt evidence, merge entities, lose a research gap or publish falsehood.
error detectabilityCan validators/confidence/gates catch bad outputs before use?
latency p50/p95Operational suitability for batch/interactive work.
throughputItems/minute at safe concurrency.
resource useRAM/VRAM/CPU/GPU load, thermal/runtime stability.
cost avoidedStrong-model calls/tokens avoided after validation overhead.
retry/repair rateCheap model stops being cheap if output constantly needs rescue.

Critical errors
weigh more.

DECISION CLASSES QWEN_APPROVED quality meets task threshold critical errors below hard bound output validation available materially cheaper/faster than stronger model QWEN_WITH_GATE useful, but every output passes deterministic validation and/or low-confidence cases escalate SHADOW_ONLY run in parallel, do not affect production decisions REJECTED quality/cost/stability unacceptable NOT_NEEDED deterministic code is better Re-evaluate after: model change quantization change llama.cpp/runtime change prompt/template change material domain drift
No universal pass markClassification can tolerate a different error profile than claim extraction. Thresholds are task-specific and stored in versioned benchmark policy.

Constrain the model.
Validate the result.

SCHEMA
JSON/schema constrained output where runtime supports it; otherwise strict parse + retry/repair policy.
ENUMS
Closed task labels use explicit enums. Unknown/ambiguous must be valid outcomes.
EVIDENCE REFS
Extraction outputs should point to input spans/source refs when feasible, enabling mechanical verification.
RANGES
Units, dates, numeric ranges and foreign keys validated by code.
CONFIDENCE
Self-reported confidence is not trusted alone; combine with task signals/disagreement/validation failures.
ESCALATE
Invalid schema, missing evidence, disagreement with deterministic constraints or high-risk class → stronger route.

Benchmark languages
we actually ingest.

LANGUAGE SET
Минимум representative English/Russian/CJK and mixed technical text if Radar actually sees them.
TRANSLATION
Отдельно измерять faithfulness, terminology preservation, omitted uncertainty and hallucinated explanation.
ENTITY NAMES
Не переводить/искажать model names, standards, part numbers, repository names and units.
ROUTING
Approval may be language-specific: задача может быть QWEN_APPROVED для одного language family и LUNA для другого.

Test refusal
to invent.

CaseDesired behavior
missing field in sourceUNKNOWN/null, not invented value.
conflicting source sentencesFlag conflict/ambiguity, not silently choose.
near-identical entity namesDo not merge without sufficient evidence.
prompt-injection text inside sourceTreat as data, not instruction.
malformed HTML/noisy textGraceful failure or bounded extraction.
technical unit trapPreserve units; no silent conversion errors.
sarcasm/community anecdoteDo not promote to established fact.
unknown niche terminologyAbstain/escalate rather than hallucinate definition.

Route by task.
Not by habit.

TASK REQUEST ↓ deterministic code possible? ├─ YES → CODE └─ NO ↓ task route registry ├─ QWEN_APPROVED ├─ QWEN_WITH_GATE ├─ LUNA ├─ STRONG_MODEL └─ DISABLED ↓ Qwen path: prompt/template version input contract local inference schema validator deterministic checks confidence/disagreement gate ↓ PASS → accept FAIL/AMBIGUOUS → fallback route
ROUTE REGISTRY
Task key → approved model/runtime/prompt version, threshold, fallback, timeout, retry policy.
PINNING
Execution records model hash/runtime/template version and config_hash.
FALLBACK
Fallback must be explicit and bounded; infinite Qwen→Qwen repair loops forbidden.
KILL SWITCH
Global + task-specific disable switch via Settings for drift/runtime failure.
SHADOW
New/changed routes start in shadow/canary where practical before affecting editorial state.

Throughput without
starving the platform.

CONCURRENCY
Benchmark 1→N parallel jobs until throughput stops scaling or latency/resource contention becomes unacceptable.
MEMORY
Measure RSS/VRAM and peak usage, including long-context cases.
THERMAL/STABILITY
Long-run soak test, model reload behavior, OOM/recovery, llama.cpp server health.
PRIORITY
Local AI workload should be lower priority than critical DB/Work/deploy services if resources overlap.
QUEUE
Backpressure mandatory. 100 article command must not launch 100 simultaneous local generations.
TIMEOUT
Per-task timeout based on measured p95/p99, not arbitrary global value.

Count validation
and retries too.

EFFECTIVE COST PER ACCEPTED OUTPUT local inference resource cost + validation CPU/time + retry/repair cost + fallback probability × fallback cost + operational overhead + error remediation expected cost Compare against: Luna direct strong model direct deterministic code Approve local route only if: quality gate passes AND effective cost/throughput has a meaningful advantage.
SAVINGS
Track avoided strong-model calls/tokens and accepted outputs, not raw number of Qwen invocations.
FALSE SAVINGS
Если 40% outputs требуют Luna repair, route может быть дороже и хуже, даже если local inference выглядит бесплатной.

Re-test after
material change.

MODEL CHANGE
Новая модель/quantization = новый benchmark identity.
RUNTIME CHANGE
llama.cpp/build/flags/context/template change требует targeted regression.
DOMAIN DRIFT
Новые source types, languages or task distributions trigger sample refresh.
QUALITY MONITOR
Production spot-checks and fallback/disagreement rates detect drift after approval.
AUTO DOWNGRADE
Hard error threshold can move task route to SHADOW/DISABLED pending review.

Routing policy
is configurable.

Setting familyPurpose
ai.local.enabledGlobal kill switch.
ai.local.max_concurrencyBounded SRV2 inference concurrency.
ai.local.queue_limitBackpressure / rejection or fallback threshold.
ai.local.task_routesTask → route / gate / fallback mapping.
ai.local.timeoutsPer-task measured timeouts.
ai.local.shadow_fractionCanary/shadow sampling for changed routes.
ai.local.quality_boundsCritical-error/fallback/drift limits per task.
ai.local.resource_limitsRAM/VRAM/CPU/GPU policy and load shedding.

Know what Qwen
actually saves.

QUALITY
Accepted/rejected/fallback, validation failures, sampled human/strong-model disagreement, critical errors.
PERFORMANCE
p50/p95/p99 latency, tokens/sec if available, queue wait, throughput, timeout rate.
RESOURCES
RAM/VRAM/CPU/GPU, OOMs, reloads, server restarts, long-run stability.
ECONOMICS
Accepted local outputs, avoided Luna/Sol calls, fallback rate, effective cost per accepted result.
TRACE
task_code, route, model hash, quantization, runtime build, template version, config_hash, validator result.

Audit. Benchmark.
Approve narrowly.

QWB-01

Audit SRV2 runtime

Pin model, quantization, llama.cpp build, flags, context, hardware usage, wrappers and current consumers.
DONE: reproducible runtime manifest exists.
QWB-02

Select task shortlist

Choose 4–6 bounded tasks from actual pipeline with clear schemas and measurable value.
DONE: every task has rubric + fallback.
QWB-03

Build benchmark corpus

Real normal/hard/ambiguous/multilingual/adversarial/unknown cases; gold labels/adjudication; holdout split.
DONE: dataset version/hash frozen.
QWB-04

Run baselines

Code where applicable, Luna Medium, selected strong-model adjudication, same contracts/rubrics.
DONE: comparable baseline report exists.
QWB-05

Run Qwen matrix

Task × language × difficulty × runtime settings, with repeated runs where needed.
DONE: quality/performance/raw outputs persisted.
QWB-06

Validate adversarial behavior

Missing data, conflicts, prompt injection, entity traps, units, noisy text and abstention.
DONE: critical-error classes measured.
QWB-07

Soak + concurrency test

1→N concurrency, long-run stability, contention, OOM/recovery, backpressure.
DONE: safe resource envelope defined.
QWB-08

Decision matrix

Per task: APPROVED / WITH_GATE / SHADOW / REJECTED / NOT_NEEDED; document thresholds and rationale.
DONE: no generic "Qwen approved" status exists.
QWB-09

Implement route registry

Model/runtime/template pinning, validators, fallback, kill switch, metrics, config snapshots.
DONE: task can fall back without losing pipeline state.
QWB-10

Shadow/canary pilot

Enable only strongest approved task(s), compare production sample against fallback reference.
DONE: observed quality stays inside benchmark bounds.
QWB-11

Checkpoint

Publish benchmark report, route matrix, settings, runbook and HANDOFF/Project State update.
DONE: checkpoint 7 PASS.
Split ruleЕсли один task family требует отдельный большой benchmark contract — например multilingual technical translation — вынести его в 7.x только после общего QWB-02 shortlist. Не распылять ветку до измерений.

Cheap worker must
fail safely.

TestExpected result
missing evidenceUNKNOWN/NEED_REVIEW, not invented field.
invalid JSONBounded retry/repair then fallback; no stuck loop.
wrong enumValidator rejects before state mutation.
critical entity merge errorBenchmark counts as critical; route fails approval if over hard bound.
prompt injection in sourceIgnored as instruction; source remains data.
runtime restartQueued job retry is idempotent.
OOMWorker fails locally, releases/restarts safely, pipeline falls back or retries by policy.
resource contentionLoad shedding protects critical platform services.
model hash changeApproved route cannot silently use unbenchmarked model identity.
language-specific regressionOnly affected route/language is downgraded when possible.
kill switchNew local tasks stop routing immediately; existing state remains consistent.
fallbackSame task continues through Luna/strong path with traceable route event.
×
Не выбирать Qwen только по tokens/sec.
×
Не считать schema-valid output фактически правильным.
×
Не использовать benchmark examples как единственный production prompt-tuning set.
×
Не сохранять approval после material model/runtime change без regression.

Qwen has roles.
Not reputation.

CHECKPOINT 7 PASS WHEN: ✓ exact SRV2 runtime/model identity is pinned ✓ existing local-model wrappers/queues audited reuse-first ✓ 4–6 real bounded task families benchmarked ✓ gold/adjudicated corpus + holdout exists ✓ code/Luna/strong baselines are comparable ✓ multilingual + adversarial cases included ✓ schema compliance is measured separately from factual quality ✓ hallucination / abstention / critical errors are measured ✓ latency / throughput / resource envelope is measured ✓ effective cost includes validation/retries/fallback ✓ each task has independent routing decision ✓ no generic "Qwen trusted" flag exists ✓ approved outputs have deterministic validation where appropriate ✓ route registry pins model/runtime/template/config ✓ explicit fallback + kill switch exist ✓ shadow/canary pilot stays within quality bounds ✓ drift/regression policy is documented ✓ Qwen remains non-primary Writer ✓ HANDOFF points to Writer Protocol next

Продолжить выполнение

Следующий шаг выбирает журнал задач. Все главы уже подготовлены.

[7.1] QWB-01 — карточка выполнения