diff --git a/README.md b/README.md index 954e85b..ede0aba 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ MagicQuant discovers **mixed-precision GGUF quantizations for llama.cpp** that offer better measured tradeoffs between model size and fidelity. It learns tensor configurations from existing quantizations, combines promising choices into new hybrids, and benchmarks the resulting models. The output is a selection of useful GGUFs with the measurements and reproducible recipes behind them. +For controlled search experiments, the [discovery lab](https://github.com/magiccodingman/MagicQuant/blob/main/docs/discovery-lab.md) designs bounded exact-map combinations and analyzes interactions, frontier recovery, short evaluations, and paired measurements. The [implementation and hardware handoff](https://github.com/magiccodingman/MagicQuant/blob/main/docs/discovery-handoff.md) tracks the current review findings, completed groundwork, and next experiments. + **The opportunity is inside the model.** Tensor groups do not all respond to compression in the same way: an attention group may benefit from a higher-precision recipe while a feed-forward group tolerates a smaller one. Their behavior can also change with the surrounding quantization choices. Existing llama.cpp baselines and external quantizations such as Unsloth provide valuable starting recipes; recombining their strengths can uncover choices that a familiar Q4, Q5, or Q6 label alone does not reveal. MagicQuant investigates those opportunities for your model. It measures group changes, predicts promising combinations, then builds and benchmarks actual GGUFs to find out which improvements hold up. **Predictions guide the search; measured results decide what earns a place.** diff --git a/docs/discovery-handoff.md b/docs/discovery-handoff.md new file mode 100644 index 0000000..06a0c75 --- /dev/null +++ b/docs/discovery-handoff.md @@ -0,0 +1,73 @@ +# Discovery implementation and hardware handoff + +This change implements the correctness fixes and experimental groundwork from the MagicQuant deep review. It does not claim a new measured model-quality gain. Review baseline: `700c5e8eeaff17c3d69bbcbafa9fe0ea9c8d452f` on `main`. The next agent should preserve a current-control campaign and evaluate the opt-in challengers under the same artifact and data protocol. + +## What each review finding became + +| Review issue | Implemented here | Follow-up requiring real measurements | +|---|---|---| +| Isolated KLD/size improvements can be pruned by absolute PPL-delta rules | Opt-in bounded rescue queue with exact incumbent-state scope | Rebuild the Q6 KV witness and test it in three representative incumbent contexts | +| Contextual probe outcomes can fail to reach final consideration | Reconcile compatible probe outcomes and references, including rejected/harmful outcomes; retain reasons | Verify a real favorable probe reaches truth finalization without globally unbanning a state | +| PAVA can hide useful interaction reversals | Raw/projected exports, projection-change diagnostics, challenger proposal/replay | Compare discoveries from raw, projected and disagreement proposals; no production projection switch added | +| Validation reused training targets and overstated tie accuracy | Explicit reconstruction/holdout scopes, coefficient-fit exclusions, tie-aware metrics, coverage, population identity | Freeze a production population and conduct a real prospective holdout experiment | +| LIMIT preceded eligibility filtering; ordinary windows left an upper interval uncovered | Shared predicate before SQL LIMIT; opt-in complete interior coverage | Compare proposal membership and useful outcomes at an equal new-recipe budget | +| Selection did not refit from new observations | Sequential residual challenger with acquisition traces in the offline lab | Implement a production batch/refit coordinator only after replay and forward trials justify it | +| Carrier-floor effects can distort additive features | Pure-target shortcut removed; fit seams and raw features exposed; residual baseline available | Measure carrier controls; compare nonnegative calibrated damage and context-conditioned models, rather than blindly subtracting a constant | +| Fixed coarse groups miss finer structure | Exact-map factorial/splice planner supports block/family/expert-name subsets | Test architecture-specific dimensions; production group schema is intentionally unchanged | +| Reuse could accept stale source, imatrix, corpus, or raw logs | Content evidence, exact imatrix lookup, reference sidecars, forced remeasurement, history, clone build proof | Cold/warm A→B imatrix and corpus/toolchain mutation campaigns; actual GPU/process checks | +| Evaluation lacked explicit fidelity/uncertainty protocol | Frozen corpus input, partitioned lab observations, paired-block statistics, screening audit | Produce actual token chunks, per-block KLD, native self-comparison, task/long-context checks and topology repeats | +| Scratch ownership may serialize build and evaluation | Stage/queue/process/lifetime timing with existing ownership retained | Measure overlap bottlenecks before changing lease lifetime, concurrency or tensor-payload caching | +| Release spacing obscured the full measured frontier | Separate unspaced measured-evidence archive and curated-membership flags | Confirm close useful points persist even when the downloadable release omits them | + +See [runtime search](discovery-search.md), [measurement identity](measurement-evidence.md), [prediction diagnostics](prediction-diagnostics.md), and the [offline lab protocol](discovery-lab.md) for the exact APIs and limitations. + +## Phase A: establish an interpretable control + +1. Use a prepared small model first. Pin source weights, native GGUF, tokenizer, llama binaries/libraries, imatrix, YAML, architecture/group profile, numerical execution policy, and three disjoint data partitions. Record actual artifact hashes, not only model names or byte lengths. +2. Run the ordinary checks in [testing](testing.md) and the opt-in prepared-model smoke. Then run a short real baseline/isolation/hybrid path. A synthetic unit-test pass is not a numerical-parity result. +3. Exercise cold run, warm reuse, force-relearn, imatrix A→B, imatrix off, changed corpus, and changed evaluator. Each incompatible change must either cause a clearly identified fresh evaluation or fail with an actionable missing-input error. Repeating the unchanged run should reuse compatible evidence. +4. Confirm native reference sidecars and archived old metrics survive repairs. Legacy rows should remain historical and must not silently seed current prediction. Check external baseline first-learning/resume and clone artifact proof as separate paths. +5. Run the same native artifact against its stored reference and compare independent/shared GPU topology on fixed chunks. Record real self-comparison and repeated variation; reference generation's stored native KLD of zero is not this experiment. + +Do not compare a fresh challenger against stale legacy scores. Rebuild the current control under the evidence protocol first. Cache hashing adds IO, especially at process start; measure it separately from quantization and inference. + +## Phase B: first bounded discovery campaign + +Use a total cap of 24 newly built recipes as an initial investigation, with existing compatible controls recorded separately. This is a starting design, not a claim of an optimal allocation. + +| Arm | New recipes | Question | +|---|---:|---| +| Current policy after shared correctness fixes | 12 | What does the current search discover with reliable evidence and correct eligibility? | +| Rescue contexts | 3 | Does an isolated KLD/size-favorable but pruned state help in real incumbents? | +| Raw/PAVA disagreement or upper-interval proposals | 3 | Is useful ordering or coverage lost before measurement? | +| Two local 2×2 interaction experiments | 6 | For each existing `00` incumbent, measure `10`, `01`, `11` and inspect the mixed contrast | + +Deduplicate concrete maps across arms before building. Predeclare storage ceilings and selection rules. If a proposed map is already measured compatibly, record that reuse and choose whether the saved budget is reallocated according to a written rule. Record failed builds and evaluations; they consume the request budget and do not become high-KLD or successful quality labels. + +The initial review's Q6 KV example is a candidate hypothesis: its isolated size/KLD improvement and pruning witness do not establish a finished hybrid win. Reproduce the actual map and current context, then test the bounded substitutions. Do not count aliases of the same concrete map as independent discoveries. + +Choose proposals using discovery data only. Use validation to compare the resulting policies and useful frontier points. Evaluate the final selected policy/artifacts once on untouched holdout data. If validation repeatedly guides new choices, preserve a new independent final audit set. Record both recipe counts and build/evaluation time; equal counts are not equal compute. + +## Phase C: small oracle and finer structure + +If Phase B finds a plausible signal, enumerate a 3×3×3 exact-map space: three meaningful dimensions and three states each. Measure all 27 unique maps, or report any deduplication/failures. Use the lab to compare frontier recall and regret for random, projected, raw, disagreement and sequential residual policies at budgets such as 3, 6 and 12, across fixed seeds. Keep the initially available training labels identical across arms. + +Run the comparison at multiple storage ceilings. A global ranking dominated by large, low-KLD artifacts can hide useful small models. Report complete frontier coverage and missing outcomes, not just reconstruction error or the single best KLD. + +For an architecture with uncovered SSM or specialized expert structure, use a separate bounded design of at most 16 maps, preserving the incumbent elsewhere. Check that selected names exist, donor maps agree on the full tensor universe, protected F32 tensors remain unchanged, and the built GGUF's resolved map matches the plan. Promote a useful finer dimension into production only after reproducible cross-context evidence warrants the schema/migration work. + +## Phase D: evaluation and throughput experiments + +Build true nested token subsets from fixed independent chunks. Compare a short budget such as 8,192 tokens with a full 32,768-token budget only after confirming what the evaluator actually consumes. Audit how many full-fidelity frontier points a short screen would discard. Set the acceptable recall target before inspecting the result; promotion policy must preserve small-budget candidates as well as low-KLD large ones. + +For close contenders, preserve paired per-block loss sums, token counts, and content IDs. Compare the paired interval with observed effect size. Repeated identical-chunk hardware runs answer numerical variation; block resampling answers variation across evaluation chunks. They are different experiments. Add a compact task-specific and long-context check for final candidates, using separate labels and provenance. + +Use timing sidecars to distinguish writer wait, CPU wait, quantization/preparation, GPU wait, process time, artifact lifetime and cleanup. Only then trial releasing a scratch writer while retaining the artifact lease, or a bounded artifact/tensor cache. Require byte/recipe parity, output-map parity, measured-quality parity, cancellation cleanup and disk-capacity bounds before adopting new concurrency behavior. This branch does not change those ownership defaults. + +## Acceptance and stop rules + +A challenger is promising when it improves compatible validation/holdout KLD at a predeclared byte ceiling, or discovers additional useful non-dominated points, by more than the measured uncertainty or repeat variation. Confirm the exact built map and actual bytes. Gains in prediction MAE alone do not meet this criterion. + +Retain the current policy if the bounded challengers fail to improve frontier outcomes after comparable requests/costs, or if apparent improvements disappear on held-out chunks. That result supports a local plateau within the tested recipe vocabulary and budget. It does not prove the global mixed-precision optimum. Report which dimensions, contexts and budgets were tested so the conclusion remains useful. + +The handoff deliverable should contain the immutable plan, frozen score exports with training provenance, candidate/map joins, per-attempt observations and failures, current benchmark envelopes, full measured frontier, curated release subset, cost/coverage tables, and a short decision for each challenger. Keep the final held-out outcomes out of subsequent fitting. diff --git a/docs/discovery-lab.md b/docs/discovery-lab.md new file mode 100644 index 0000000..2ee9d64 --- /dev/null +++ b/docs/discovery-lab.md @@ -0,0 +1,143 @@ +# Bounded discovery experiments + +`scripts/discovery_lab.py` turns existing exact tensor maps into bounded, reproducible experiments. It can design a small factorial, emit clone manifests, analyze interactions and the complete measured frontier, compare proposal strategies, audit short evaluations, and compare paired blocks. It uses Python's standard library and does not execute models or download data. + +The runtime changes are documented in [discovery search](discovery-search.md), [measurement evidence](measurement-evidence.md), and [prediction diagnostics](prediction-diagnostics.md). The [agent handoff](discovery-handoff.md) gives the order in which to test them on real hardware. + +## 1. Freeze the question before measuring + +Start from a `magicquant.clone-configs.json` containing actual, compatible tensor maps. Choose an incumbent and a few donors. A dimension selects tensor names using shell-style globs, then substitutes the selected names from a donor. Dimensions must not overlap. Every donor must contain the complete incumbent tensor-name set. Unselected tensors retain the incumbent's assignments; F32 tensors are protected unless explicitly allowed. + +For example, three dimensions with three states each create 27 factorial cells. Two dimensions with two states create the four cells needed for one interaction contrast. A dimension can select a group, an early/middle/late block band, an SSM-related family, or a set of expert tensors. This operates on concrete tensor names and does not add new database group IDs or change the production nine-group representation. + +The first state of each dimension must preserve the incumbent. The tool checks the product of state counts against `max_recipes` before enumerating it. The default limit is 64, with an explicit hard ceiling of 10,000. Equivalent resulting maps are deduplicated while retaining their design-cell aliases. The budget is therefore visible both as factorial cells and as unique builds. + +Create a JSON specification with these fields: + +| Field | Required content | +|---|---| +| `schema_version`, `campaign_id` | Version `1` and a descriptive campaign ID | +| `base_artifact` | Exact incumbent `FileName` in the source manifest | +| `max_recipes` | Predeclared cap on factorial cells | +| `byte_ceilings` | Positive integer storage budgets, chosen before inspecting outcomes | +| `artifact_context` | Source-weight SHA-256, quantizer SHA-256, explicit imatrix SHA-256 or `null`, and `quantizer_options` object | +| `evaluation_contexts` | Separate `discovery`, `validation`, and `holdout` definitions | +| `dimensions` | Named dimensions with `tensor_patterns` and named donor states | + +Each evaluation context supplies `chunks_sha256`, `tokenizer_sha256`, `reference_sha256`, `evaluator_sha256`, `context_length`, `token_budget`, `sample_policy`, and `numerical_topology`. Digests must identify actual frozen inputs, not descriptive labels. `sample_policy` is `fixed` or `nested_prefix`; only the latter permits shorter fidelities. The three chunk fingerprints must differ. Distinct digests alone cannot prove that two corpora have no overlapping content; verify the split when creating the tokenized chunks. + +The [example specification](../examples/discovery-lab/spec.template.json) deliberately contains invalid digest placeholders. Replace them with hashes from the prepared campaign, adjust the artifact names, patterns, and byte ceilings, and save a new specification. The planner validates declarations but does not read source weights or establish that those declarations match a machine's configuration. + +```sh +python3 scripts/discovery_lab.py plan \ + --source-manifest /campaign/source/magicquant.clone-configs.json \ + --spec /campaign/design.json --output /campaign/plan-v1 +``` + +This creates `plan.json`, `magicquant.clone-configs.json`, and `measurements.template.jsonl`. `plan_id` hashes the complete frozen plan. `candidate_id` hashes the normalized complete tensor map; it is not a hash of a GGUF. Source scores and source sizes are cleared from generated clone entries so an experimental recipe never inherits a measurement from a donor. All commands refuse to overwrite their requested output path. + +## 2. Build and evaluate actual artifacts + +Use the generated manifest with the existing clone command and a prepared local configuration: + +```sh +magicquant clone-repository-quants --config /campaign/discovery.yaml \ + --source-json /campaign/plan-v1/magicquant.clone-configs.json \ + --benchmark-corpus /campaign/corpora/discovery.txt +``` + +`--benchmark-corpus` reads an existing nonempty frozen text file directly for General measurements and native reference generation. Keep it outside the export directory, which clone mode cleans. This option does not tokenize, enforce a token count, create nested samples, or reserve a holdout. The default C# corpus budget still uses a character approximation. Exact fidelity experiments need a prepared tokenizer/chunk protocol and a runner that records the actual evaluated tokens. Do not label an approximate character budget as an exact token budget. + +Run discovery, validation, and final holdout with separate preserved evaluation directories and matching references. Archive each result before changing context. The current clone command is an artifact builder and benchmark runner, not a three-partition campaign scheduler. Configure reuse deliberately: compatible artifacts may be reused, while changed corpora require fresh reference and candidate measurements. + +Clone build reuse requires `clone-artifact-evidence.json`: source, quantizer, imatrix, requested exact map and build-policy identity, plus the current GGUF digest. The evaluator independently checks its measurement envelope. Equal file sizes or an old release summary no longer establish reuse. Resolved clone maps must be read successfully from the generated GGUF; a failed metadata read cannot present the requested map as observed truth. + +Clone summaries include `ArtifactSha256`, `EvidenceIdentityHash`, `BuildSeconds`, and `EvaluationSeconds`. These durations describe the current call, including preparation or reuse overhead. A warm reuse is not a new inference-cost observation. Retain the benchmark envelope and native-process logs as well as the summary. + +## 3. Record observations without changing the plan + +Copy the pending JSONL template to a separate measurement file. Each observation needs: + +| Field | Meaning | +|---|---| +| `plan_id`, `candidate_id`, `artifact_context_id` | Identities from the immutable plan | +| `artifact_sha256`, `size_bytes` | Actual measured artifact content and length | +| `evaluation_context_id` | Hash of the declared partition context with the actual fidelity budget | +| `partition`, `fidelity_tokens`, `replicate` | Data split, evaluated token count, and explicit repeat ID | +| `status` | `pending`, `measured`, `build_failed`, or `evaluation_failed` | +| `kld` | Finite nonnegative measured KLD; `null` for every non-measurement | +| `build_seconds`, `evaluation_seconds` | Nonnegative recorded costs, including failed attempts where available | +| `blocks` | Optional independent chunk observations: `id`, `tokens`, and additive `kld_sum` | + +`measurement_template(plan, partition)` and `evaluation_id(plan, partition, fidelity)` are importable helpers for an external runner. The template is initially for discovery at full fidelity. There is intentionally no automatic importer that guesses tokenizer, chunk, toolchain, or numerical identities from scalar clone summaries. A runner must verify the actual map, artifact digest, benchmark envelope, and evaluation definition before mapping those observations into this protocol. + +All measurements of a candidate in one plan must have identical artifact bytes and size, including across partitions and replicates. A changed build belongs in a new campaign. Duplicate observation keys, nonfinite JSON, duplicate JSON properties, incompatible context IDs, and quality labels attached to failures are rejected. Full-fidelity analysis excludes partial runs. Replicate scalar KLD values are averaged within the same declared context; replicates do not automatically supply an uncertainty estimate. + +Use content-derived block IDs consistently across candidates. Reusing an observed block ID in different partitions is rejected. A partition-local label such as `block-1` does not establish provenance. When supplied blocks cover the full token budget, their weighted mean must agree with scalar KLD. Partial coverage remains visible. + +## 4. Look for interactions and frontier improvements + +```sh +python3 scripts/discovery_lab.py analyze --plan /campaign/plan-v1/plan.json \ + --measurements /campaign/observations.jsonl --partition discovery \ + --output /campaign/analysis-discovery.json +``` + +The result includes coverage, failures, missing maps, the complete measured Pareto frontier, and the best KLD under each predeclared byte ceiling. This lab uses exact mathematical dominance. The runtime archive uses its established truth-comparison tolerances; these two views should be labeled explicitly when compared. Neither applies release spacing. + +For each complete two-by-two contrast, holding every other dimension fixed, the interaction is: + +`KLD(11) - KLD(10) - KLD(01) + KLD(00)`. + +A negative value means the joint change has less KLD than that local additive comparison predicts. It does not establish a useful size trade until actual artifact sizes are considered. Missing cells produce an incomplete-design record rather than a fabricated contrast. Different background assignments produce different contexts; do not average away a sign reversal before investigating it. + +## 5. Compare ways of choosing the next measurements + +Prepare a frozen score document with `plan_id`, `training_evaluation_context_id`, `training_candidate_ids`, and `scores`. Each score has a known `candidate_id` and explicit `eligible`. Eligible entries require `predicted_size_bytes`, `raw_kld`, and `projected_kld`; excluded entries require `exclusion_reason`. Copying production exports requires a verified join from actual configuration identity to the exact-map candidate identity. Pure-baseline aliases and arbitrary equivalent maps are not automatically resolved. + +Declare every candidate outcome used in producing those scores. The harness checks that declared initial training labels are available in the discovery context, but cannot detect undisclosed training data inside an external producer. Preserve the producer version, training inputs, and raw export with the score file. The production export is before anomaly adjustments and selector gates; it does not establish final eligibility. + +```sh +python3 scripts/discovery_lab.py replay --plan /campaign/plan-v1/plan.json \ + --measurements /campaign/observations.jsonl --scores /campaign/frozen-scores.json \ + --budget 12 --batch-size 3 --seed 17 --output /campaign/replay-seed17.json +``` + +The replay compares projected scores, raw scores, raw/projected disagreement, seeded random selection, and sequential residual correction. The residual challenger fits a regularized first-order one-hot correction to the frozen raw score, using only acquired discovery labels, then refits between batches. It is a small baseline for learning from new measurements, not a Gaussian-process model or calibrated uncertainty estimate. Disagreement is a diagnostic acquisition heuristic, not uncertainty. + +Ranking uses predicted sizes and round-robin storage ceilings. Discovery labels are revealed only after a batch is selected. Validation labels score outcomes and never influence selection or fitting; holdout labels are unused. Failed or missing discovery requests consume budget but cannot earn validation credit. Outputs include the full acquisition trace, missing/excluded candidates, observed-oracle regret, measured-frontier recall, and recorded costs. + +This is observed-pool replay, not exact production-selector replay. The oracle covers only maps measured on validation. Equal recipe budgets do not imply equal GPU time or byte-write cost. Compare several seeds and report the coverage and costs; retain an untouched final holdout for deciding whether the chosen policy generalizes. + +For a forward proposal that cannot read outcome labels at all: + +```sh +python3 scripts/discovery_lab.py propose --plan /campaign/plan-v1/plan.json \ + --scores /campaign/frozen-scores.json --budget 3 --policy disagreement \ + --seed 17 --output /campaign/proposal-01 +``` + +The result contains a selected clone manifest and proposal provenance. This command accepts no measurement file. The sequential residual method currently exists in replay; a production sequential coordinator remains follow-up work. + +## 6. Test whether shorter evaluations are useful + +```sh +python3 scripts/discovery_lab.py screen --plan /campaign/plan-v1/plan.json \ + --measurements /campaign/observations.jsonl --partition discovery \ + --low-tokens 8192 --keep-fraction 0.5 --output /campaign/screen-8192.json +``` + +The full context must declare a larger budget and `nested_prefix`. The audit compares short and full observations, promotes low-KLD candidates within storage ceilings, and reports full-frontier points lost by screening. A frontier candidate without a short observation counts as missed. The overlapping storage strata can retain more than the requested fraction globally. This is a retrospective recall check; it does not run adaptive promotion or claim a measured speedup. Validate recall and actual evaluation costs before using it to cut real budgets. + +## 7. Compare paired uncertainty + +```sh +python3 scripts/discovery_lab.py paired --plan /campaign/plan-v1/plan.json \ + --measurements /campaign/observations.jsonl --partition validation \ + --left CANDIDATE_ID_A --right CANDIDATE_ID_B --replicate 0 \ + --resamples 2000 --seed 17 --output /campaign/paired-a-b.json +``` + +Both candidates need identical block identities and token counts. The tool resamples paired independent blocks and computes the token-weighted right-minus-left KLD difference. Negative favors the right candidate. It reports the block contrast separately from the full scalar contrast, labels partial coverage, and returns no interval for a single block. Choose independent chunk boundaries in the evaluation runner; this routine cannot make adjacent dependent tokens independent or estimate hardware nondeterminism. + +Task accuracy, coding behavior, long-context quality, and cross-topology repeatability require separate evaluations. Keep their context IDs and outcomes separate from the distribution-divergence label. The handoff lists those experiments rather than implying that KLD alone answers them. diff --git a/docs/discovery-search.md b/docs/discovery-search.md new file mode 100644 index 0000000..f337a59 --- /dev/null +++ b/docs/discovery-search.md @@ -0,0 +1,175 @@ +# Discovery search: runtime controls and evidence + +This page describes the implemented selection changes. The search still uses learned tensor recipes, measured General KLD, and model bytes. These changes make specific candidates reachable and retain evidence; they do not establish a new model-quality frontier without a real campaign. + +## Defaults and opt-in behavior + +| Behavior | Default | +| --- | --- | +| Apply the deterministic near-anchor gain requirement before SQL `LIMIT` | Always enabled | +| Count the complete deterministically eligible query pool | Always enabled | +| Reconcile compatible measured contextual references and probes | Always enabled | +| Write the measured archive and unspaced frontier | Always enabled | +| Extend the last ordinary interior window to its larger anchor | Disabled | +| Build contextual swaps from isolated size/KLD rescue evidence | Disabled | + +A custom configuration that omits the new keys inherits the same opt-in defaults as the distributed YAML. + +```yaml +isolation_pruning: + kld_size_rescue_enabled: false + kld_size_rescue_max_candidates_per_group: 1 + kld_size_rescue_max_context_probes_per_run: 3 + +candidate_selection: + interior_window_fractions: [0.35, 0.35] + complete_interior_coverage: false +``` + +The production projection and anomaly scoring policy are unchanged by these controls. The optional prediction-score export and offline experiment tools are documented in [the discovery lab](discovery-lab.md). + +## Candidate filtering before truncation + +Near-baseline and interior queries already require a candidate to beat their prediction-space linear KLD line and fit the intersection of prediction and real-validation size windows. They also impose a stronger gain requirement close to the smaller prediction anchor. + +Previously, the query fetched a limited ranked prefix before applying that last requirement. Every fetched row could fail while a later row passed. The query now applies the near-anchor requirement before ordering and limiting results. SQL and in-memory diagnostics share `NearAnchorGainRequirement`. + +The requirement retains the existing semantics: + +- Outside the configured near-anchor zone, the additional gain threshold does not apply. +- Inside or exactly on the zone boundary, predicted gain must be at least the configured fraction of the anchors' KLD gap, bounded below by the improvement epsilon. +- A zero prediction-anchor size span bypasses this additional requirement. The ordinary line-improvement condition remains separate. + +`DeterministicEligibleCount` now counts the complete eligible pool. `FetchedCandidateCount` and the scan limit still describe the bounded prefix fetched for diversity/validation. Rejection counts are pool counts; they are not inferred from that prefix. + +This correction does not increase the configured physical validation-attempt limits. A window that previously returned no usable candidate can now use its existing allowance. + +Implementation: [RemainingCombinationStore.cs](../src/MagicQuant/Services/RemainingCombinationStore.cs), [SelectionEligibility.cs](../src/MagicQuant/Services/SelectionEligibility.cs), and [PredictionGuidedHybridSelectionService.cs](../src/MagicQuant/Services/PredictionGuidedHybridSelectionService.cs). + +## Optional complete interior coverage + +With the default fractions `[0.35, 0.35]` and `complete_interior_coverage: false`, ordinary interior discovery covers the first 35% and the next 35% of an adjacent-anchor size interval. + +With `complete_interior_coverage: true`, its final window ends at the larger anchor: + +| Window | Default | Complete coverage | +| --- | --- | --- | +| First | 0–35% | 0–35% | +| Last | 35–70% | 35–100% | + +The number of windows and configured attempts per window remain the same. The extension is applied in both prediction-space and real-validation coordinates; candidates must still satisfy their intersected window and the existing gain conditions. + +This setting changes ordinary interior discovery only. Strict replacement, near-baseline replacement, and the existing smart fallback retain their policies. Smart interior fallback already extends its final window and remains a separate failure-triggered path. + +Equal attempt limits are not an equal-compute guarantee. Previously empty windows may now produce requests, model sizes differ, and cache hits can differ. Record requested recipes, physical builds, evaluator work, and elapsed time separately when comparing campaigns. + +## Bounded isolated size/KLD rescue + +The rescue path retains evidence from group candidates removed by the existing bad-trade heuristic. It does not change that heuristic's arithmetic or remove global candidate bans. + +### What enters the queue + +The isolation optimizer considers a retained bad-trade removal only if it is still banned after the normal group processing. Candidates already removed before that stage by hard-damage or other filtering do not enter through this queue. + +A queued candidate must have valid finite metrics, be no larger and no worse in KLD than the recorded accepted anchor, and improve size or improve KLD beyond the configured floating-point epsilon. Another measured group candidate must not dominate it under the same size/KLD comparison. + +The queue preserves the original removal reason, group and baseline identities, and both sides' isolated bytes/KLD. Queue recording can occur while contextual testing is disabled. + +| Setting | Default | Normalized range | Meaning | +| --- | --- | --- | --- | +| `kld_size_rescue_enabled` | `false` | Boolean | Permit the additional local test batch | +| `kld_size_rescue_max_candidates_per_group` | `1` | 0–16 | Bound retained states per group | +| `kld_size_rescue_max_context_probes_per_run` | `3` | 0–128 | Bound planned local recipe requests | + +Zero candidates per group leaves the queue empty. Zero contextual probes prevents the additional batch even when rescue is enabled. + +### How a contextual request is constructed + +Rescue runs after ordinary strict, near, and interior selection and after measured contextual reconciliation. It uses the resulting measured incumbents. + +For each queued state, the planner visits the lowest-size, highest-size, middle, then remaining incumbent contexts. The group must be active, and the incumbent's effective group choice—explicit or inherited from its carrier—must equal the exact accepted-anchor baseline from the isolated comparison. + +Only that group's learned recipe is replaced. The carrier and other group assignments are copied from the incumbent. Duplicate configuration requests and already-present incumbent configurations are excluded. The batch stops at the run cap. + +The planner deduplicates configuration keys; this is not a claim that different recipe labels always produce different tensor bytes. Keep the builder's effective-map/artifact checks and count actual work separately. + +The requested swaps go through real construction/benchmarking and current-evidence checks. Valid measurements enter final size/KLD consideration and the archive. A favorable isolated observation alone never becomes a measured hybrid score. + +**Neither queue recording nor contextual testing unbans a Cartesian group choice.** This is a bounded route for specific measured comparisons, not a general reopening of rejected states. + +Implementation: [IsolationOptimizationService.cs](../src/MagicQuant/Services/IsolationOptimizationService.cs) and [IsolationRescuePlanner.cs](../src/MagicQuant/Services/IsolationRescuePlanner.cs). + +## Reconcile both sides of measured contextual probes + +Final reconciliation previously admitted one best confirmed beneficial probe. It now examines both reference and probe configurations from the current scoped contextual observations. + +The observation must match architecture family, tensor-group profile, model, imatrix, and General category, and must be explicitly contextual, not an old BF16 isolation, with all active groups explicit. Each side must resolve to a compatible current benchmark snapshot. Its recorded configuration key, when present, must match; its recorded KLD must agree with the snapshot within the implemented numeric tolerance: the greater of `1e-12` absolute and `1e-9 * abs(recorded KLD)`. + +`Accepted` and beneficial/harmful classification describe the hypothesis. They no longer decide whether either already-measured artifact deserves frontier consideration. A better reference from a harmful probe can therefore be considered without globally unbanning the reference's isolated group state. + +Current snapshot loading enforces benchmark evidence compatibility. Missing legacy proof, mismatched inputs, invalid metrics, or observation disagreement cannot be replaced by the observation's stored scalar alone. Reconciliation records why a side was omitted. + +Reconciliation can use compatible historical contextual measurements even when new anomaly generation is disabled. The legacy best-beneficial reconciliation summary remains available when anomaly mode is enabled; the new archive contains the broader reconciliation record. + +Implementation: [MeasuredFrontierArchive.cs](../src/MagicQuant/Services/MeasuredFrontierArchive.cs) and the selector's `LoadContextualMeasurementsAsync`. + +## Archive and curated release are separate views + +The selector returns: + +| Result | Contents | +| --- | --- | +| `MeasuredSnapshots` | Current compatible General measurements, plus valid measurements encountered by the current selection phases | +| `UnspacedFrontier` | The existing final dominance/equivalent-truth result over those measurements, without release spacing | +| `Survivors` | The curated selector result after its normal gates, contextual reconciliation, optional rescue, spacing, and final dominance | + +The archive can include pure/native or isolation artifacts, dominated observations, and valid candidates that failed a selector line gate. A failed process with no valid current measurement supplies no quality observation. Within a configuration key, the archive keeps the last supplied current observation rather than selecting the most optimistic repeated scalar. + +“Unspaced” retains the existing final judge: same-or-smaller bytes and strictly lower KLD using the configured epsilon, plus the existing equivalent-truth representative selection. It does not introduce a different mathematical Pareto definition. All valid measurement rows remain available even when that policy removes a frontier representative. + +Archiving a row does not enable its release or export every artifact. Normal failed-line candidates are retained for research without automatically entering the curated selector. Contextual references/probes and opted-in rescue results follow the reconciliation described above. Existing manual release enablement and export remain downstream. + +### Location + +With an output directory, the file is: + +```text +/magicquant-manifest/magicquant.measured-frontier.json +``` + +Without an output directory, it is written in the selector's GGUF diagnostics directory: the model MagicQuant directory's `GGUF` subdirectory, then the shared MagicQuant directory's `GGUF` subdirectory, then `./GGUF` as fallback. + +### Schema version 1 + +The JSON contains: + +- `schemaVersion`, `generatedAtUtc`, `modelId`, `imatrixIdentity`, and `comparisonPolicy`. +- `measuredCount` and `unspacedFrontierCount`. +- `measurements`: each entry contains `observation`, `slots`, `onUnspacedFrontier`, and `inCuratedSelection`. +- `contextualReconciliation`: observation ID, side (`reference` or `probe`), configuration key, recorded KLD, and resolution status. +- `isolatedRescueEnabled`, `isolatedRescueQueue`, and `isolatedRescueAttempts`. + +An `observation` includes its configuration key, display/provider/family metadata, bytes, KLD, PPL, and `evidenceIdentityHash`. `slots` stores the carrier and nine encoded group choices. Reconciliation statuses are `included`, `missing_configuration`, `observation_configuration_mismatch`, `current_measurement_unavailable_or_incompatible`, and `observation_kld_mismatch`. + +A rescue attempt records the candidate configuration, incumbent context key, isolation evidence, whether a valid current measurement was available, and its result when available. These entries describe requests and outcomes; they do not assert that the request produced a fresh physical build. + +Keep the associated benchmark evidence envelopes, configuration, exact-map exports, and run provenance. Runtime numeric recipe IDs are not a cross-campaign identity, and an evidence hash is not the full proof object. The archive alone is not an automatically validated input to an unrelated campaign. + +## Acceptance checks before relying on model results + +The CPU regression suite exercises the query false-empty case with 126 distinct configurations, SQL/in-memory boundary agreement, opt-in window coverage, rescue scope/caps, harmful-reference reconciliation, incompatible-evidence rejection, and close unspaced options: + +```sh +dotnet test tests/MagicQuant.Tests/MagicQuant.Tests.csproj -c Release --filter FullyQualifiedName~SearchDiscoveryCorrectnessTests +``` + +A representative hardware campaign should then establish the following: + +1. **Freeze the comparison.** Pin source weights, learned maps, imatrix or explicit imatrix-off, toolchain, corpus/reference, context, and execution settings. Decide whether deterministic fixes are shared by both experimental arms. Keep independent validation/holdout inputs separate. +2. **Check default behavior first.** With the two opt-in flags disabled, verify that no rescue batch runs, the existing ordinary window fractions remain, and SQL diagnostics separate full eligible counts from fetched counts. Verify that compatible current measurements appear in the archive and incompatible evidence stays excluded. +3. **Check one opt-in change at a time.** For coverage, verify the final ordinary window reaches its larger anchor without adding windows. For rescue, start with the three-request cap and inspect every changed group against its recorded anchor state. Global runtime bans and the generated Cartesian universe should remain unchanged by rescue. +4. **Verify paid-for outcomes.** Check emitted tensor maps and artifact/evaluation identities, actual bytes, and real General results. Confirm that a valid contextual reference reaches final consideration even when its hypothesis is harmful or rejected. Dominated results may still be excluded from the frontier. +5. **Inspect both output views.** A close useful point may appear on the unspaced frontier but not in the curated selection. Failed selector gates should not erase a valid measurement from the archive. Preserve negative and unsuccessful requests. +6. **Judge quality on independent data.** Compare credible finalists with their incumbents on the same independent chunks and predefined byte ceilings. Record request counts, physical builds, evaluator work, and elapsed time separately. A new prediction, changed shortlist, or larger archive is not a measured quality gain. + +These runtime controls provide an auditable experiment path. They do not run the complete offline factorial, refit the general predictor after every result, or establish global saturation. diff --git a/docs/measurement-evidence.md b/docs/measurement-evidence.md new file mode 100644 index 0000000..1f27e08 --- /dev/null +++ b/docs/measurement-evidence.md @@ -0,0 +1,128 @@ +# Measurement evidence and timing + +Benchmark reuse now requires a versioned content envelope in `bench_metrics.json`. +The SQLite `AiBenchmarks.EvidenceIdentityHash` points to that envelope. A DB tuple, +plausible scalar values, equal GGUF byte length, or an old raw log is insufficient. +This is a change to what counts as current measured evidence, so old untagged runs +must be measured again before they can drive current selection or prediction. + +## What is identified + +The envelope records the SHA-256 of the native GGUF and the measured output GGUF. +Recipe identity includes the base quantizer argument, group overrides, actual +group rules and fallback rules, relevant learned tensor-map contents, active +imatrix bytes and whether that imatrix is applied, the quantizer and adjacent +llama/ggml libraries, an explicit quantization-recipe contract version, and CPU/writer +policy inputs. Native GGUF contents cover the tokenizer and converted model +metadata actually supplied to the quantizer. + +The quantization contract version must be bumped when tensor resolution, +materialization or quantizer arguments change. Whole-assembly IDs are deliberately +excluded so predictor, CLI and documentation-only changes can compare existing +measurements without repeating inference. + +Evaluation identity includes the perplexity executable and adjacent libraries, +hardware and execution-plan policy, requested character-based corpus budget, +context/command policy, actual corpus bytes, and the native reference-logit +content and producer definition for each domain. The result records whether +independent GPU topology was permitted. Existing native-process logs retain the +actual command and topology details. Native reference generation still stores +native KLD as zero; this is not a measured comparator self-comparison. +Artifact comparisons with an explicit reference require KLD even when their +carrier ID is BF16/F16/native. Such comparisons retain measured self-comparison +values rather than replacing them with the native-reference zero convention. + +The default target named `tokenTarget` remains a **character-based approximation**: +the corpus builder requests at least four characters per requested token and may +overshoot by a source row. These changes do not introduce exact token chunks, +multi-fidelity promotion, confidence intervals, or cross-topology numerical +equivalence. Hardware/plan identity prevents reuse across changed recorded +policies; it does not establish that two allowed slots produce identical logits. + +File contents are hashed in full once per observed path/length/write-time/creation- +time tuple in a process. This amortizes reads of large GGUFs and logits. Treat +campaign inputs as immutable: replacing contents while deliberately preserving +all file metadata is outside this cache contract. File stamps are checked after +hashing, and measurement inputs are revalidated before results are saved. Drivers +and externally loaded libraries outside the llama binary directory are not fully +captured by this first implementation. + +## Cache and historical behavior + +- Same source, recipe, artifact, evaluation and reference may reuse a completed + result, including after a temporary candidate GGUF has been cleaned up. If the + candidate GGUF is present, its content digest must match. +- Missing or mismatched envelopes, changed imatrices, changed corpora, changed + budgets, changed evaluators and changed materialized outputs are cache misses. + Raw per-domain logs are never promoted into current metrics by themselves. +- Native reference logits have a producer/content sidecar. The existing native + benchmark hydration path regenerates references when that proof is absent or + incompatible. Candidate comparison refuses unproven references. +- Forced baseline relearning now forces measurement after rebuilding. Inner disk + or log reuse cannot override that request. +- Snapshot retrieval requires exact active imatrix identity, including explicit + imatrix-off. A configured but unrecorded active imatrix yields no snapshot. + Snapshot domains are exact; Code/Math cannot stand in for General. +- Recorded evidence reads validate current source, recipe, corpus, references and + toolchain under the recorded execution/CPU policy. Offline diagnostics need not + rediscover GPU scheduling. An explicit known imatrix hash can select a recorded + bucket without the original calibration file inside the diagnostic read scope; + live search also checks the active imatrix application policy, and new execution + still needs bytes. The diagnostic scope never relaxes new-run cache matching. +- Existing metrics and raw logs are copied into a per-benchmark `history` folder + before a fresh evaluation replaces them. A DB row whose identity is replaced + is also archived under `Benchmarks/_evidence_history/database`. Archives are + historical evidence, not an automatic input to current training. +- Native artifact repair preserves compact evidence and prior history outside the + directory being cleared, under `_evidence_history/native-repair`, while allowing + the large serialized logits to be regenerated. +- Prepared external baseline tensor maps are persisted against an unmeasured + identity placeholder before their first measurement. That placeholder has no + current evidence or categories, so learning the recipe does not invent a score. +- Isolation deduplication now verifies full concrete tensor overrides and base + quantizer argument equality, requires current source evidence, and records the + source evidence hash in the derived envelope. + +The nullable DB column does not create a complete immutable multi-evaluation +relational history. SQLite still stores the current measurement for its existing +logical tuple; historical envelopes and DB snapshots live in the archive. This +is deliberate groundwork for a richer evaluation-definition schema. + +## Frozen text for separate evaluations + +`BenchmarkService.RunAllBenchmarksAsync` accepts an optional +`IReadOnlyDictionary corpusOverrides` with domain keys `general`, +`code`, and `math`. The service reads supplied local files directly, hashes their +actual bytes, and leaves the default corpus files unchanged. It does not trim, +tokenize, shuffle, or expand a frozen file to satisfy `tokenTarget`. + +Generate native references with the same frozen files before comparing +candidates. Use separate benchmark and reference directories for discovery and +validation campaigns; reusing a reference path for different text invalidates +the old reference identity. An explicit text override does not by itself enforce +a train/holdout split. The caller must provide disjoint frozen data and preserve +the split in its experiment manifest. + +## Timing groundwork + +Concurrency limits and scratch root ownership are unchanged. Small JSON sidecars +next to quantization logs record scratch queue wait, CPU queue wait, quantization +with preparation, and benchmark time with identity/persistence overhead. The +benchmark envelope records GPU queue wait and elapsed perplexity-process totals. +Scratch sidecars record artifact lifetime and cleanup time. Native-process totals +include model loading, inference and any retries; they are not pure kernel time. +`QuantizationRun.DurationMs` keeps its existing end-to-end meaning. + +These measurements support a later controlled experiment separating scratch +writer ownership from artifact lifetime. No throughput gain, overlapping queue, +tensor-payload cache or hot-swapping implementation is claimed by this change. + +## Validation boundary + +`BenchmarkEvidenceTests` uses temporary files and SQLite fixtures to exercise +warm reuse, content changes, reference compatibility, legacy rejection, exact +imatrix snapshots, scalar validation, historical preservation and recipe +equivalence. It performs no model inference. Before adopting new performance or +numerical policies, run a small-model A-to-B imatrix warm-resume comparison, +native self-comparison, paired topology check, forced-relearn run, and frozen +discovery/holdout campaign with actual native processes and hardware. diff --git a/docs/prediction-diagnostics.md b/docs/prediction-diagnostics.md new file mode 100644 index 0000000..71cfcb0 --- /dev/null +++ b/docs/prediction-diagnostics.md @@ -0,0 +1,83 @@ +# Prediction diagnostics and frozen candidate scores + +The prediction exports separate three questions: how well the model reconstructs measurements used in fitting, how it scores excluded hybrid outcomes, and which raw interaction signals the production projection suppresses. None of these exports alone proves that a candidate would pass the live selector or improve a measured frontier. + +## Reconstruct the measured subset + +Run the existing command with the same model, tensor-group profile and imatrix context as the campaign: + +```sh +MagicQuant validate-predictions --model-dir /models/example --output-dir /reports/prediction +``` + +If the campaign uses an imatrix, also pass its `--imatrix-path` or `--imatrix-identity-hash`. The command writes `prediction_validation_general.csv`, `.md` and `.json`. The default JSON mode is `in_sample_reconstruction`: available General outcomes also participate in fitting. It is not an out-of-sample accuracy estimate. + +Use an existing campaign directory with its native GGUF, benchmark evidence and original YAML tensor rules. The command resolves the exact model's registered family, selects the existing profile with the matching rule fingerprint, restores persisted custom baseline IDs and derives active groups from the native tensor names. It does not create or activate a tensor-group profile, download external baselines or execute benchmarks. A missing profile or mismatched native tensor signature fails explicitly. + +The CSV and JSON keep unscored rows in the coverage denominator. Missing/nonfinite JSON numbers are `null`. Error metrics use only comparable, finite KLD pairs; absent comparisons are `null`, not zero error. Predicted ties earn half credit among pairs with different actual KLD. An entirely tied predictor therefore scores 50% if actual KLD varies. Actual ties are excluded from this accuracy denominator, and a dataset with no orderable actual pairs has no defined accuracy. Kendall tau-b is reported separately and is undefined for an entirely tied axis. These are exact numeric ties, not a claim about measurement uncertainty. + +The rank-movement table uses deterministic ranks within the comparable subset and size to break KLD ties. Use the tie-aware pairwise metrics when assessing discrimination; a convenient size tie-break is not additional KLD information. + +## Exclude hybrid targets from coefficient fitting + +Create a nonempty JSON array of existing configuration keys, copied from the export: + +```json +["", ""] +``` + +Then run: + +```sh +MagicQuant validate-predictions --model-dir /models/example \ + --prediction-holdout-keys /reports/heldout-keys.json \ + --output-dir /reports/coefficient-holdout +``` + +This produces mode `coefficient_holdout_subset_diagnostic`. The requested configurations and their canonical prediction-coordinate aliases are removed before fitting alpha, beta and the bit-stress threshold. Only the requested measured subset is scored. Targets that are also required pure, base-only or isolation inputs are rejected, because removing them only from coefficient fitting would leave their outcomes inside the features. Unknown keys fail explicitly. The exported fit training keys use canonical prediction coordinates; requested target keys use actual configuration coordinates. `fit_training_config_key_scope` records this distinction, and each scored record provides its canonical key for comparison. + +This is a configuration-level coefficient holdout within one existing campaign. Isolation learning remains shared, and arbitrary tensor-map-equivalent configurations are not discovered by this key-based split. For policy development, reserve a separate final audit set and avoid repeatedly using it to choose experiments. + +## Inspect raw versus projected signals + +Validation JSON has schema version 1. Each record includes: + +| Field | Meaning | +|---|---| +| `config_key` | Actual benchmark configuration identity | +| `prediction_config_key` | Synthetic coordinate used to generate features | +| `additive_kld`, `cross_term` | Isolation sum and fitted interaction feature | +| `raw_interaction_kld` | Nonnegative alpha/beta score before PAVA | +| `projected_kld` | Rank-safe PAVA result before anomaly rules | +| `projection_adjustment_kld`, `projection_changed_score` | Direct evidence that projection changed the score | +| `prediction_coverage` | Numeric prediction and size coverage, not live selection eligibility | +| `selection_eligible` | `null`: this diagnostic does not run the selector | +| `actual_kld`, `actual_size_bytes` | Observed outcome, kept separate from prediction | + +The metadata records the model/family/profile/imatrix identifiers, fit, training keys, requested holdout keys and a hash of the scored key population. Its `production_replay` value is always `false`. + +Quantized pure baselines, including Q8, are scored through their virtual Q8-carrier group coordinates. Their measured KLD is a fit target, not a shortcut input to their own prediction. Native precision remains the zero-damage origin. Real pure artifacts can differ from virtual coordinates on uncovered tensors; the diagnostic states that equivalence is unverified. Removing the former shortcut can change the fitted coefficients and hence production rankings even though the production projection policy is unchanged. + +## Export the production materialization population + +For an offline challenger experiment, enable the opt-in streaming export: + +```yaml +prediction: + export_candidate_scores: true +``` + +The normal materializer then writes these files in the model work directory's `PredictionDiagnostics` folder: + +- `prediction_candidates_pre_anomaly.jsonl` +- `prediction_candidates_pre_anomaly.metadata.json` + +The JSONL is streamed and may be large. Each record carries additive, interaction and projected scores, projected rank, size, anchor flags and prediction coverage. The metadata contains the exact JSONL SHA-256, row counts, fit training keys and context identifiers. Preserve both files together with a timestamped experiment manifest before another materialization replaces them. `prediction_support_score` is the existing heuristic support score, not calibrated uncertainty. + +This export captures the actual materialized population at that moment, before anomaly adjustments and selector gates. It does not reinstate states already removed by pruning and does not assert final eligibility. A later materialization or a different population can give a different PAVA score for the same configuration. + +The full-population export and the measured-subset diagnostic intentionally describe different scopes. Raw interaction scores can be compared as an offline challenger while the live system continues to use rank-safe projection and existing anomaly behavior. To measure discovery value, join frozen proposal scores to compatible, provenance-checked actual outcomes and evaluate frontier recovery or regret under a fixed budget. Do not fit to the eventual replay targets, and do not interpret reconstruction MAE as frontier improvement. + +## Regression coverage + +`PredictionDiagnosticTests` exercises misleading all-tie metrics, actual ties, missing coverage, standard JSON nulls, quantized-pure target independence, native zero, coefficient holdout invariance when excluded targets change, rejection of input-feature holdouts, retention of raw scores through the real DuckDB projection path, and the effect of changing the PAVA population. The SQL fixture verifies the same projected scores as C# and the existing size tie-break while preserving the original raw reversal. diff --git a/docs/testing.md b/docs/testing.md index a062963..868f65b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -12,6 +12,8 @@ Repeat with `-c Debug` when changing startup or compilation-dependent behavior. The suite covers CLI startup/preflight, YAML contracts, managed/output path containment, symlinks on Linux, SQLite/DuckDB identity, native argument construction, log parsing, conversion success markers, concurrency policy, and existing research-policy regressions. It does not establish numerical equivalence for every model or hardware topology. Tests remain serial because the legacy runtime registries are shared. +Discovery regression coverage also exercises content-identified measurements and native references, clone artifact proof, exact imatrix snapshots, SQL eligibility before LIMIT, bounded rescue scope, probe reconciliation, unspaced frontier preservation, prediction target independence, coefficient holdouts, tie-aware diagnostics, and C#/DuckDB projection parity. The standard Python suite includes `test_discovery_lab.py`, covering frozen plans, exact-map factorials, partition/fidelity identity, observed-pool acquisition, screening misses, and paired block statistics. All of these use temporary or synthetic fixtures; follow the [hardware handoff](discovery-handoff.md) to establish model-quality and throughput results. + To update dependencies intentionally, edit package versions, run an unlocked `dotnet restore`, review `packages.lock.json` changes, and rerun the suite. Audit with: ```sh diff --git a/examples/discovery-lab/README.md b/examples/discovery-lab/README.md new file mode 100644 index 0000000..2ba5d0f --- /dev/null +++ b/examples/discovery-lab/README.md @@ -0,0 +1,13 @@ +# Adapting the experiment template + +Read the [discovery lab protocol](../../docs/discovery-lab.md) before using `spec.template.json`. It is a design template, not a runnable measured example: its digest placeholders are intentionally invalid. + +Copy it into a dedicated campaign directory and set: + +- Real incumbent and donor `FileName` values from one compatible clone manifest. +- Tensor-name patterns that exist in that model. These example dense-model patterns are not universal and are not regular expressions. +- Storage ceilings meaningful for your model and decided before inspecting outcomes. +- SHA-256 digests of actual source weights, tools, tokenizer, frozen chunks, and native references, plus all quantizer options. Replace `imatrix_sha256: null` with the actual digest if calibration is used. +- Three disjoint prepared data partitions and their actual numerical execution policy. A claimed `32768`-token budget must be enforced and counted by the evaluation runner; the default C# corpus preparation uses an approximation. + +The example has three dimensions and three states, capped at 27 factorial cells. Duplicate exact maps may reduce the number of builds. Preserve `plan.json`, build/evaluation evidence and each attempt's status. Generated manifests contain no inherited donor quality labels. diff --git a/examples/discovery-lab/spec.template.json b/examples/discovery-lab/spec.template.json new file mode 100644 index 0000000..488bf27 --- /dev/null +++ b/examples/discovery-lab/spec.template.json @@ -0,0 +1,74 @@ +{ + "schema_version": 1, + "campaign_id": "replace-with-campaign-name", + "base_artifact": "incumbent.gguf", + "max_recipes": 27, + "byte_ceilings": [40000000000, 50000000000, 60000000000], + "artifact_context": { + "source_weights_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "quantizer_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "imatrix_sha256": null, + "quantizer_options": {} + }, + "evaluation_contexts": { + "discovery": { + "chunks_sha256": "REPLACE_WITH_DISCOVERY_CHUNKS_SHA256", + "tokenizer_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "reference_sha256": "REPLACE_WITH_DISCOVERY_REFERENCE_SHA256", + "evaluator_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "context_length": 2048, + "token_budget": 32768, + "sample_policy": "nested_prefix", + "numerical_topology": "REPLACE_WITH_RECORDED_DEVICE_AND_EXECUTION_POLICY" + }, + "validation": { + "chunks_sha256": "REPLACE_WITH_VALIDATION_CHUNKS_SHA256", + "tokenizer_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "reference_sha256": "REPLACE_WITH_VALIDATION_REFERENCE_SHA256", + "evaluator_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "context_length": 2048, + "token_budget": 32768, + "sample_policy": "nested_prefix", + "numerical_topology": "REPLACE_WITH_RECORDED_DEVICE_AND_EXECUTION_POLICY" + }, + "holdout": { + "chunks_sha256": "REPLACE_WITH_HOLDOUT_CHUNKS_SHA256", + "tokenizer_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "reference_sha256": "REPLACE_WITH_HOLDOUT_REFERENCE_SHA256", + "evaluator_sha256": "REPLACE_WITH_ACTUAL_SHA256", + "context_length": 2048, + "token_budget": 32768, + "sample_policy": "nested_prefix", + "numerical_topology": "REPLACE_WITH_RECORDED_DEVICE_AND_EXECUTION_POLICY" + } + }, + "dimensions": [ + { + "name": "attention-kv", + "tensor_patterns": ["blk.*.attn_k.weight", "blk.*.attn_v.weight"], + "states": [ + {"name": "incumbent", "donor_artifact": "$base"}, + {"name": "donor-a", "donor_artifact": "donor-a.gguf"}, + {"name": "donor-b", "donor_artifact": "donor-b.gguf"} + ] + }, + { + "name": "ffn-down", + "tensor_patterns": ["blk.*.ffn_down.weight"], + "states": [ + {"name": "incumbent", "donor_artifact": "$base"}, + {"name": "donor-a", "donor_artifact": "donor-a.gguf"}, + {"name": "donor-b", "donor_artifact": "donor-b.gguf"} + ] + }, + { + "name": "attention-output", + "tensor_patterns": ["blk.*.attn_output.weight"], + "states": [ + {"name": "incumbent", "donor_artifact": "$base"}, + {"name": "donor-a", "donor_artifact": "donor-a.gguf"}, + {"name": "donor-b", "donor_artifact": "donor-b.gguf"} + ] + } + ] +} diff --git a/scripts/discovery_lab.py b/scripts/discovery_lab.py new file mode 100644 index 0000000..ec6ab0f --- /dev/null +++ b/scripts/discovery_lab.py @@ -0,0 +1,708 @@ +#!/usr/bin/env python3 +"""Offline, bounded experimental design for MagicQuant's exact tensor recipes. + +No model execution, downloads, or third-party packages. Plans are immutable inputs; +failed processes never become quality labels; replay exposes only acquired labels. +See docs/discovery-lab.md for the protocol and the limits of observed-pool replay. +""" +from __future__ import annotations + +import argparse +import copy +import fnmatch +import hashlib +import itertools +import json +import math +import random +import statistics +import sys +from collections import defaultdict +from pathlib import Path + +VERSION = 1 +PARTITIONS = ("discovery", "validation", "holdout") +MAX_RECIPES = 10000 + + +class ProtocolError(ValueError): + pass + + +def require(condition, message): + if not condition: + raise ProtocolError(message) + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, + allow_nan=False) + + +def digest(value): + return hashlib.sha256(canonical(value).encode("utf-8")).hexdigest() + + +def file_digest(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + result.update(block) + return result.hexdigest() + + +def parse_json(text): + def reject_constant(value): + raise ProtocolError(f"Non-finite JSON number: {value}") + def unique_keys(pairs): + result = {} + for key, value in pairs: + require(key not in result, f"Duplicate JSON key: {key}") + result[key] = value + return result + return json.loads(text, parse_constant=reject_constant, object_pairs_hook=unique_keys) + + +def read_json(path): + return parse_json(Path(path).read_text(encoding="utf-8")) + + +def write_json(path, value): + Path(path).write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n", + encoding="utf-8") + + +def number(value, name, *, minimum=0): + require(isinstance(value, (int, float)) and not isinstance(value, bool) + and math.isfinite(value) and value >= minimum, + f"{name} must be a finite number >= {minimum}") + return value + + +def positive_int(value, name, *, maximum=None): + require(type(value) is int and value > 0, f"{name} must be a positive integer") + require(maximum is None or value <= maximum, f"{name} exceeds {maximum}") + return value + + +def sha(value, name): + require(isinstance(value, str) and len(value) == 64 + and all(c in "0123456789abcdef" for c in value), + f"{name} must be a lowercase SHA-256 digest of the actual input") + return value + + +def validate_protocol(spec): + require(spec.get("schema_version") == VERSION, "Unsupported specification version") + require(isinstance(spec.get("campaign_id"), str) and spec["campaign_id"].strip(), + "campaign_id is required") + artifact = spec.get("artifact_context", {}) + for name in ("source_weights_sha256", "quantizer_sha256"): + sha(artifact.get(name), name) + require("imatrix_sha256" in artifact, "Explicit imatrix_sha256 (digest or null) is required") + if artifact["imatrix_sha256"] is not None: + sha(artifact["imatrix_sha256"], "imatrix_sha256") + require(isinstance(artifact.get("quantizer_options"), dict), "quantizer_options object is required") + require(type(spec.get("allow_protected_changes", False)) is bool, "allow_protected_changes must be boolean") + protected = spec.get("protected_types", ["F32"]) + require(isinstance(protected, list) and all(isinstance(t, str) and t for t in protected), + "protected_types must be an array of tensor type names") + contexts = spec.get("evaluation_contexts", {}) + require(set(contexts) == set(PARTITIONS), "Separate discovery, validation, and holdout contexts are required") + for partition, context in contexts.items(): + for name in ("chunks_sha256", "tokenizer_sha256", "reference_sha256", "evaluator_sha256"): + sha(context.get(name), f"{partition}.{name}") + positive_int(context.get("context_length"), "context_length") + positive_int(context.get("token_budget"), "token_budget") + require(bool(context.get("numerical_topology")), "numerical_topology is required") + require(context.get("sample_policy") in ("fixed", "nested_prefix"), + "sample_policy must be fixed or nested_prefix") + require(len({x["chunks_sha256"] for x in contexts.values()}) == 3, + "Partitions must have distinct chunk fingerprints; labels alone do not separate data") + ceilings = spec.get("byte_ceilings", []) + require(isinstance(ceilings, list) and ceilings, "Predeclared byte_ceilings are required") + for ceiling in ceilings: + positive_int(ceiling, "byte ceiling") + + +def normalize_map(tensors): + require(isinstance(tensors, dict) and tensors, "An exact tensor map is required") + result = {} + for name, kind in tensors.items(): + require(isinstance(name, str) and name and not any(c in name for c in "\r\n\0"), + "Invalid tensor name") + require(isinstance(kind, str) and kind.strip(), f"Missing tensor type: {name}") + kind = kind.strip().upper() + require(all(c.isalnum() or c == "_" for c in kind), f"Invalid tensor type: {kind}") + result[name] = kind + return dict(sorted(result.items())) + + +def plan_experiment(source, spec): + validate_protocol(spec) + artifacts = source.get("Artifacts", []) + require(artifacts, "Source must be a MagicQuant clone manifest with Artifacts") + by_name = {} + for artifact in artifacts: + name = artifact.get("FileName") + require(isinstance(name, str) and name and name not in by_name, "Artifact names must be unique") + by_name[name] = dict(artifact, TensorTypes=normalize_map(artifact.get("TensorTypes"))) + base = by_name.get(spec.get("base_artifact")) + require(base is not None, "base_artifact is not in the source manifest") + base_map = base["TensorTypes"] + dimensions = spec.get("dimensions", []) + require(isinstance(dimensions, list) and 1 <= len(dimensions) <= 8, + "Choose 1 to 8 non-overlapping experimental dimensions") + max_recipes = positive_int(spec.get("max_recipes", 64), "max_recipes", maximum=MAX_RECIPES) + occupied, names, prepared = set(), set(), [] + for dimension in dimensions: + name = dimension.get("name") + require(isinstance(name, str) and name and name not in names, "Dimension names must be unique") + names.add(name) + patterns = dimension.get("tensor_patterns", []) + require(isinstance(patterns, list) and patterns and all(isinstance(p, str) and p for p in patterns), + f"{name}: tensor_patterns must be nonempty globs") + selected = sorted(t for t in base_map if any(fnmatch.fnmatchcase(t, p) for p in patterns)) + require(selected, f"{name}: patterns matched no tensors") + require(not occupied.intersection(selected), f"{name}: overlapping dimensions confound the factorial design") + occupied.update(selected) + states, state_names = [], set() + for state in dimension.get("states", []): + state_name = state.get("name") + require(isinstance(state_name, str) and state_name and state_name not in state_names, + f"{name}: state names must be unique") + state_names.add(state_name) + donor = base if state.get("donor_artifact") == "$base" else by_name.get(state.get("donor_artifact")) + require(donor is not None, f"{name}/{state_name}: donor artifact is missing") + require(set(donor["TensorTypes"]) == set(base_map), + f"{name}/{state_name}: donor and base have different tensor names") + overrides = {t: donor["TensorTypes"][t] for t in selected} + protected = {t.strip().upper() for t in spec.get("protected_types", ["F32"])} + require(spec.get("allow_protected_changes", False) or not any( + base_map[t] in protected and overrides[t] != base_map[t] for t in selected), + f"{name}/{state_name}: a protected tensor would change; choose narrower patterns") + states.append({"name": state_name, "donor_artifact": donor["FileName"], "overrides": overrides}) + require(len(states) >= 2, f"{name}: at least two states are required") + require(all(states[0]["overrides"][t] == base_map[t] for t in selected), + f"{name}: first state must preserve the incumbent") + prepared.append({"name": name, "tensors": selected, "states": states}) + cell_count = math.prod(len(d["states"]) for d in prepared) + require(cell_count <= max_recipes, + f"Factorial has {cell_count} cells, exceeding predeclared cap {max_recipes}; reduce the design") + candidates = {} + for state_tuple in itertools.product(*(d["states"] for d in prepared)): + tensor_map, assignments = dict(base_map), {} + for dimension, state in zip(prepared, state_tuple): + tensor_map.update(state["overrides"]) + assignments[dimension["name"]] = state["name"] + candidate_id = digest(tensor_map) + if candidate_id not in candidates: + candidates[candidate_id] = { + "candidate_id": candidate_id, + "file_name": f"mq-experiment-{candidate_id}.gguf", + "tensor_types": dict(sorted(tensor_map.items())), + "assignments": [], + "matches_source_artifacts": sorted(a["FileName"] for a in by_name.values() + if a["TensorTypes"] == tensor_map), + } + candidates[candidate_id]["assignments"].append(assignments) + plan = { + "schema_version": VERSION, + "campaign_id": spec["campaign_id"], + "specification": copy.deepcopy(spec), + "source_manifest_sha256": digest(source), + "artifact_context_id": digest(spec["artifact_context"]), + "base_quant": base.get("BaseQuant", "Q8_0"), + "source_model_id": source.get("SourceModelId"), + "source_architecture_family": source.get("SourceArchitectureFamily"), + "dimensions": prepared, + "factorial_cells": cell_count, + "unique_maps": len(candidates), + "candidates": list(candidates.values()), + "notes": ["Proposals have no inherited quality measurements.", + "Map equality is not artifact-content equality; verify emitted GGUFs.", + "Fingerprints are supplied by the operator; this planner does not inspect model weights."], + } + plan["plan_id"] = digest(plan) + return plan + + +def validate_plan(plan): + require(plan.get("schema_version") == VERSION, "Unsupported plan version") + content = {k: v for k, v in plan.items() if k != "plan_id"} + require(plan.get("plan_id") == digest(content), "Plan changed after freezing; generate a new campaign plan") + validate_protocol(plan["specification"]) + ids = [c["candidate_id"] for c in plan["candidates"]] + require(len(ids) == len(set(ids)), "Duplicate candidate IDs") + for candidate in plan["candidates"]: + require(digest(normalize_map(candidate["tensor_types"])) == candidate["candidate_id"], + "Candidate identity does not match its exact map") + return plan + + +def evaluation_id(plan, partition, fidelity): + require(partition in PARTITIONS, "Unknown data partition") + context = dict(plan["specification"]["evaluation_contexts"][partition]) + positive_int(fidelity, "fidelity_tokens", maximum=context["token_budget"]) + require(fidelity == context["token_budget"] or context["sample_policy"] == "nested_prefix", + "Partial evaluation requires a declared nested_prefix protocol") + context["token_budget"] = fidelity + return digest(context) + + +def clone_manifest(plan, ids=None): + selected = set(ids) if ids is not None else None + artifacts = [] + for candidate in plan["candidates"]: + if selected is not None and candidate["candidate_id"] not in selected: + continue + artifacts.append({ + "FileName": candidate["file_name"], "DisplayName": "Experiment " + candidate["candidate_id"][:12], + "ShortName": "EXP-" + candidate["candidate_id"][:12], "Provider": "MagicQuant experiment", + "QuantFamily": plan["base_quant"], "BaseQuant": plan["base_quant"], "IsHybrid": True, + "UsedImatrix": plan["specification"]["artifact_context"]["imatrix_sha256"] is not None, + "SourceKld": None, "SourcePpl": None, "SourceSizeBytes": None, + "TensorTypes": candidate["tensor_types"], + }) + require(selected is None or len(artifacts) == len(selected), "Unknown selected candidate") + return {"SchemaVersion": 1, "Generator": "MagicQuant discovery_lab", "SourceRepository": None, + "SourceModelId": plan["source_model_id"], "SourceArchitectureFamily": plan["source_architecture_family"], + "Notes": f"Unmeasured experimental recipes. Frozen plan {plan['plan_id']}.", "Artifacts": artifacts} + + +def measurement_template(plan, partition="discovery"): + fidelity = plan["specification"]["evaluation_contexts"][partition]["token_budget"] + return [{"schema_version": VERSION, "plan_id": plan["plan_id"], + "candidate_id": c["candidate_id"], "artifact_context_id": plan["artifact_context_id"], + "artifact_sha256": None, "evaluation_context_id": evaluation_id(plan, partition, fidelity), + "partition": partition, "fidelity_tokens": fidelity, "replicate": "0", "status": "pending", + "size_bytes": None, "kld": None, "build_seconds": 0, "evaluation_seconds": 0, + "blocks": []} for c in plan["candidates"]] + + +def load_measurements(plan, path): + known = {c["candidate_id"] for c in plan["candidates"]} + rows, keys, artifacts, block_partitions = [], set(), {}, {} + with Path(path).open(encoding="utf-8") as stream: + for line_no, line in enumerate(stream, 1): + if not line.strip(): + continue + row = parse_json(line) + prefix = f"measurement line {line_no}" + require(row.get("schema_version") == VERSION and row.get("plan_id") == plan["plan_id"], + f"{prefix}: wrong schema or campaign plan") + cid, partition, fidelity = row.get("candidate_id"), row.get("partition"), row.get("fidelity_tokens") + require(cid in known, f"{prefix}: unknown candidate") + require(row.get("artifact_context_id") == plan["artifact_context_id"], f"{prefix}: wrong artifact context") + require(row.get("evaluation_context_id") == evaluation_id(plan, partition, fidelity), + f"{prefix}: wrong evaluation identity or fidelity") + require(isinstance(row.get("replicate", "0"), str), "replicate must be a string") + key = cid, partition, fidelity, row.get("replicate", "0") + require(key not in keys, f"{prefix}: duplicate measurement; assign explicit replicate IDs") + keys.add(key) + status = row.get("status") + require(status in ("pending", "measured", "build_failed", "evaluation_failed"), f"{prefix}: unknown status") + for cost in ("build_seconds", "evaluation_seconds"): + number(row.get(cost, 0), cost) + if status == "measured": + number(row.get("kld"), "kld") + positive_int(row.get("size_bytes"), "size_bytes") + sha(row.get("artifact_sha256"), "artifact_sha256") + signature = row["artifact_sha256"], row["size_bytes"] + require(cid not in artifacts or artifacts[cid] == signature, + f"{prefix}: same recipe yielded different artifacts; use a separate campaign") + artifacts[cid] = signature + block_ids = set() + for block in row.get("blocks", []): + require(isinstance(block.get("id"), str) and block["id"] and block["id"] not in block_ids, + "Block IDs must be unique content/chunk identities") + block_ids.add(block["id"]) + require(block["id"] not in block_partitions or block_partitions[block["id"]] == partition, + f"{prefix}: block identity reused across data partitions") + block_partitions[block["id"]] = partition + positive_int(block.get("tokens"), "block tokens") + number(block.get("kld_sum"), "block kld_sum") + if row.get("blocks"): + block_tokens = sum(b["tokens"] for b in row["blocks"]) + require(block_tokens <= fidelity, + "Block token counts exceed evaluation fidelity") + if block_tokens == fidelity: + block_mean = sum(b["kld_sum"] for b in row["blocks"]) / block_tokens + require(math.isclose(block_mean, row["kld"], rel_tol=1e-9, abs_tol=1e-12), + "Full-coverage block KLD disagrees with the recorded scalar") + else: + require(row.get("kld") is None, f"{prefix}: a process failure/pending run cannot have a quality label") + require(not row.get("blocks"), f"{prefix}: non-measurements cannot supply quality blocks") + rows.append(row) + return rows + + +def measurements_at(plan, rows, partition, fidelity=None): + fidelity = fidelity or plan["specification"]["evaluation_contexts"][partition]["token_budget"] + grouped = defaultdict(list) + for row in rows: + if row["partition"] == partition and row["fidelity_tokens"] == fidelity and row["status"] == "measured": + grouped[row["candidate_id"]].append(row) + return {cid: {"candidate_id": cid, "kld": statistics.mean(x["kld"] for x in group), + "size_bytes": group[0]["size_bytes"], "replicates": len(group), + "evaluation_seconds": sum(x.get("evaluation_seconds", 0) for x in group), + "build_seconds": sum(x.get("build_seconds", 0) for x in group)} + for cid, group in grouped.items()} + + +def frontier(points): + groups = defaultdict(list) + for point in points: + groups[point["size_bytes"]].append(point) + best, result = math.inf, [] + for size in sorted(groups): + minimum = min(x["kld"] for x in groups[size]) + if minimum < best: + result.extend(sorted((x for x in groups[size] if x["kld"] == minimum), key=lambda x: x["candidate_id"])) + best = minimum + return result + + +def best_under(points, ceilings): + points = list(points) + return [{"byte_ceiling": cap, "best": min((p for p in points if p["size_bytes"] <= cap), + key=lambda p: (p["kld"], p["size_bytes"], p["candidate_id"]), + default=None)} for cap in sorted(set(ceilings))] + + +def interactions(plan, measured): + dimensions = plan["dimensions"] + names = [d["name"] for d in dimensions] + cell_map = {tuple(a[n] for n in names): c["candidate_id"] + for c in plan["candidates"] for a in c["assignments"]} + results, missing = [], 0 + for i, j in itertools.combinations(range(len(dimensions)), 2): + others = [k for k in range(len(dimensions)) if k not in (i, j)] + for context in itertools.product(*(dimensions[k]["states"] for k in others)): + base_cell = [d["states"][0]["name"] for d in dimensions] + for k, state in zip(others, context): + base_cell[k] = state["name"] + for si, sj in itertools.product(dimensions[i]["states"][1:], dimensions[j]["states"][1:]): + cells = [] + for ai, aj in ((False, False), (True, False), (False, True), (True, True)): + cell = list(base_cell) + if ai: cell[i] = si["name"] + if aj: cell[j] = sj["name"] + cells.append(cell_map[tuple(cell)]) + if not all(cid in measured for cid in cells): + missing += 1 + continue + values = [measured[cid]["kld"] for cid in cells] + results.append({"dimensions": [names[i], names[j]], "states": [si["name"], sj["name"]], + "context": {names[k]: base_cell[k] for k in others}, + "cells_00_10_01_11": cells, "kld_00_10_01_11": values, + "interaction_kld": values[3] - values[1] - values[2] + values[0]}) + return {"complete_contrasts": sorted(results, key=lambda r: (r["interaction_kld"], r["cells_00_10_01_11"])), + "incomplete_contrasts": missing, + "interpretation": "Negative contrast means less damage than the sum of these two local moves; it is not a universal group interaction or a significance test."} + + +def analyze(plan, rows, partition): + measured = measurements_at(plan, rows, partition) + return {"schema_version": VERSION, "plan_id": plan["plan_id"], "partition": partition, + "coverage": {"planned_unique_maps": len(plan["candidates"]), "fully_measured_maps": len(measured), + "missing_candidate_ids": sorted({c["candidate_id"] for c in plan["candidates"]} - set(measured)), + "status_counts": {status: sum(r["partition"] == partition and r["status"] == status for r in rows) + for status in ("pending", "measured", "build_failed", "evaluation_failed")}}, + "full_measured_frontier": frontier(measured.values()), + "best_under_byte_ceilings": best_under(measured.values(), plan["specification"]["byte_ceilings"]), + "interactions": interactions(plan, measured), + "scope": "Only compatible observations at full declared fidelity; no spacing or release curation."} + + +def load_scores(plan, document): + require(document.get("plan_id") == plan["plan_id"], "Score plan identity mismatch") + expected = evaluation_id(plan, "discovery", plan["specification"]["evaluation_contexts"]["discovery"]["token_budget"]) + require(document.get("training_evaluation_context_id") == expected, + "Score training context must be the declared discovery context") + known = {c["candidate_id"] for c in plan["candidates"]} + training = document.get("training_candidate_ids", []) + require(isinstance(training, list) and len(training) == len(set(training)) and set(training) <= known, + "Declare unique known training_candidate_ids") + scores = {} + for row in document.get("scores", []): + cid = row.get("candidate_id") + require(cid in known and cid not in scores, "Score candidate missing, unknown, or duplicated") + require(type(row.get("eligible")) is bool, "Each score must declare eligibility") + if row["eligible"]: + positive_int(row.get("predicted_size_bytes"), "predicted_size_bytes") + number(row.get("raw_kld"), "raw_kld") + number(row.get("projected_kld"), "projected_kld") + else: + require(bool(row.get("exclusion_reason")), "Ineligible rows need an exclusion_reason") + scores[cid] = row + return scores, set(training) + + +def features(plan): + dimensions = plan["dimensions"] + terms = [(d["name"], s["name"]) for d in dimensions for s in d["states"][1:]] + # A regularized first-order residual is deliberately small. Pair effects are + # measured separately; this does not fit an unconstrained pair matrix. + require(len(terms) <= 128, "Residual model exceeds the bounded feature budget") + return {c["candidate_id"]: [1.0] + [float(c["assignments"][0][name] == state) for name, state in terms] + for c in plan["candidates"]} + + +def solve(matrix, vector): + augmented = [list(row) + [value] for row, value in zip(matrix, vector)] + n = len(vector) + for column in range(n): + pivot = max(range(column, n), key=lambda row: abs(augmented[row][column])) + require(abs(augmented[pivot][column]) > 1e-15, "Singular residual fit; increase regularization") + augmented[column], augmented[pivot] = augmented[pivot], augmented[column] + scale = augmented[column][column] + augmented[column] = [v / scale for v in augmented[column]] + for row in range(n): + if row == column: + continue + scale = augmented[row][column] + augmented[row] = [v - scale * p for v, p in zip(augmented[row], augmented[column])] + return [row[-1] for row in augmented] + + +def residual_predictions(feature_map, acquired, scores, regularization): + number(regularization, "regularization", minimum=1e-12) + known = [cid for cid in sorted(acquired) if cid in scores and scores[cid]["eligible"]] + if not known: + return {cid: row["raw_kld"] for cid, row in scores.items() if row["eligible"]} + n = len(next(iter(feature_map.values()))) + matrix = [[0.0] * n for _ in range(n)] + vector = [0.0] * n + for cid in known: + x = feature_map[cid] + y = acquired[cid]["kld"] - scores[cid]["raw_kld"] + for i in range(n): + vector[i] += x[i] * y + for j in range(n): + matrix[i][j] += x[i] * x[j] + for i in range(n): matrix[i][i] += regularization + weights = solve(matrix, vector) + return {cid: max(0.0, row["raw_kld"] + sum(a * b for a, b in zip(feature_map[cid], weights))) + for cid, row in scores.items() if row["eligible"]} + + +def rank_batch(plan, scores, excluded, policy, count, *, acquired=None, seed=0, regularization=0.001): + require(policy in ("projected", "raw", "disagreement", "random", "sequential_residual"), "Unknown policy") + pool = [cid for cid, row in scores.items() if row["eligible"] and cid not in excluded] + rng = random.Random(seed) + # Keep one seeded permutation of the frozen population. Re-drawing the same + # RNG prefix over a shrinking pool makes later choices depend on hash order + # and batch size instead of merely removing already requested candidates. + random_rank = {cid: rng.random() for cid in sorted(c["candidate_id"] for c in plan["candidates"])} + residual = residual_predictions(features(plan), acquired or {}, scores, regularization) if policy == "sequential_residual" else {} + def priority(cid): + row = scores[cid] + value = {"projected": row["projected_kld"], "raw": row["raw_kld"], + "disagreement": -abs(row["raw_kld"] - row["projected_kld"]), + "random": random_rank[cid], "sequential_residual": residual.get(cid, row["raw_kld"])}[policy] + return value, row["predicted_size_bytes"], cid + ordered = sorted(pool, key=priority) + caps = sorted(set(plan["specification"]["byte_ceilings"])) + selected = [] + while len(selected) < count: + before = len(selected) + for cap in caps: + cid = next((c for c in ordered if c not in selected and scores[c]["predicted_size_bytes"] <= cap), None) + if cid is not None: + selected.append(cid) + if len(selected) == count: break + if len(selected) == before: break + return selected + + +def replay(plan, rows, score_document, *, budget, batch_size=3, seed=0, regularization=0.001): + positive_int(budget, "budget", maximum=MAX_RECIPES) + positive_int(batch_size, "batch_size", maximum=budget) + scores, training = load_scores(plan, score_document) + discovery = measurements_at(plan, rows, "discovery") + validation = measurements_at(plan, rows, "validation") + require(training <= set(discovery), "Initial training labels must have valid full-fidelity discovery measurements") + caps = plan["specification"]["byte_ceilings"] + oracle = best_under(validation.values(), caps) + results = [] + for policy in ("projected", "raw", "disagreement", "random", "sequential_residual"): + acquired = {cid: discovery[cid] for cid in training} + selected, trace = [], [] + while len(selected) < budget: + batch = rank_batch(plan, scores, training | set(selected), policy, min(batch_size, budget - len(selected)), + acquired=acquired, seed=seed, regularization=regularization) + if not batch: break + labels_before = sorted(acquired) + selected.extend(batch) + # A proposed candidate's discovery outcome is revealed only AFTER selection. + # Validation and holdout observations are never used to select or fit. + for cid in batch: + if cid in discovery: acquired[cid] = discovery[cid] + trace.append({"batch": len(trace) + 1, "available_labels_before": labels_before, + "requested_candidate_ids": batch, + "new_valid_discovery_labels": [cid for cid in batch if cid in discovery]}) + # A request that failed or has no discovery result consumes budget but + # cannot earn a winner through a validation label from another run. + available = set(acquired) + visible = [validation[cid] for cid in sorted(available) if cid in validation] + achieved = best_under(visible, caps) + regrets = [{"byte_ceiling": actual["byte_ceiling"], + "kld_regret_to_observed_oracle": (actual["best"]["kld"] - ideal["best"]["kld"]) + if actual["best"] is not None and ideal["best"] is not None else None} + for actual, ideal in zip(achieved, oracle)] + oracle_frontier = {p["candidate_id"] for p in frontier(validation.values())} + costs = [r for r in rows if r["partition"] == "discovery" and r["candidate_id"] in selected + and r["status"] != "pending"] + results.append({"policy": policy, "requested_new_recipes": len(selected), "trace": trace, + "selected_candidate_ids": selected, "best_under_byte_ceilings": achieved, + "successful_new_discovery_recipes": len(set(selected) & available), + "validation_eligible_candidate_ids": sorted(available), + "regret": regrets, "observed_frontier_recall": len(available & oracle_frontier) / len(oracle_frontier) + if oracle_frontier else None, + "requests_without_full_discovery_label": sorted(set(selected) - set(discovery)), + "requests_without_validation_label": sorted(set(selected) - set(validation)), + "recorded_build_seconds": sum(r.get("build_seconds", 0) for r in costs), + "recorded_evaluation_seconds": sum(r.get("evaluation_seconds", 0) for r in costs)}) + return {"schema_version": VERSION, "plan_id": plan["plan_id"], "seed": seed, "budget": budget, + "batch_size": batch_size, "regularization": regularization, + "score_document_sha256": digest(score_document), "initial_training_candidate_ids": sorted(training), + "exclusions": [{"candidate_id": c["candidate_id"], "reason": "missing_score" if c["candidate_id"] not in scores + else scores[c["candidate_id"]].get("exclusion_reason", "eligible")} + for c in plan["candidates"] if c["candidate_id"] not in scores or not scores[c["candidate_id"]]["eligible"]], + "known_validation_maps": len(validation), "planned_maps": len(plan["candidates"]), "policies": results, + "scope": "Observed-pool replay with declared frozen external scores, not the full production selector. Missing/rejected maps remain visible. Costs are recorded logical requests, not a matched-compute experiment. External score training provenance must be independently audited."} + + +def screening(plan, rows, partition, low_tokens, keep_fraction): + require(0 < keep_fraction <= 1, "keep_fraction must be in (0,1]") + context = plan["specification"]["evaluation_contexts"][partition] + positive_int(low_tokens, "low_tokens", maximum=context["token_budget"] - 1) + require(context["sample_policy"] == "nested_prefix" and low_tokens < context["token_budget"], + "Screening needs a shorter declared nested-prefix fidelity") + low, full = measurements_at(plan, rows, partition, low_tokens), measurements_at(plan, rows, partition) + common = set(low) & set(full) + # Size strata prevent a global low-KLD screen from discarding the low-byte frontier. + caps = sorted(set(plan["specification"]["byte_ceilings"])) + retained = set() + for cap in caps: + eligible = sorted((cid for cid in low if low[cid]["size_bytes"] <= cap), key=lambda cid: (low[cid]["kld"], cid)) + retained.update(eligible[:math.ceil(len(eligible) * keep_fraction)]) + full_frontier = {p["candidate_id"] for p in frontier(full.values())} + return {"schema_version": VERSION, "plan_id": plan["plan_id"], "partition": partition, + "low_tokens": low_tokens, "keep_fraction": keep_fraction, + "common_maps": len(common), "full_maps": len(full), "low_maps": len(low), + "retained_candidate_ids": sorted(retained), + "frontier_recall": len(retained & full_frontier) / len(full_frontier) if full_frontier else None, + "dropped_frontier_candidate_ids": sorted(full_frontier - retained), + "frontier_without_low_fidelity": sorted(full_frontier - set(low)), + "scope": "Retrospective screening audit; overlapping size strata can retain more than keep_fraction globally. No inferred wall-time speedup."} + + +def paired_comparison(plan, rows, left, right, partition, *, replicate="0", resamples=2000, seed=0): + require(left != right, "Choose different candidates") + positive_int(resamples, "resamples", maximum=100000) + full = plan["specification"]["evaluation_contexts"][partition]["token_budget"] + selected_rows = {} + def pick(cid): + selected = [r for r in rows if r["candidate_id"] == cid and r["partition"] == partition + and r["fidelity_tokens"] == full and r.get("replicate", "0") == replicate and r["status"] == "measured"] + require(len(selected) == 1 and selected[0].get("blocks"), "Both candidates need one measured replicate with block data") + selected_rows[cid] = selected[0] + return {b["id"]: b for b in selected[0]["blocks"]} + a, b = pick(left), pick(right) + require(set(a) == set(b), "Paired comparison requires identical block identities, without silently dropping blocks") + require(all(a[k]["tokens"] == b[k]["tokens"] for k in a), "Paired block token counts differ") + blocks = [(b[k]["kld_sum"] - a[k]["kld_sum"], a[k]["tokens"]) for k in sorted(a)] + block_tokens = sum(x[1] for x in blocks) + require(block_tokens <= full, "Block token counts exceed evaluation fidelity") + complete_coverage = block_tokens == full + if complete_coverage: + for cid, supplied in ((left, a), (right, b)): + require(math.isclose(sum(x["kld_sum"] for x in supplied.values()) / block_tokens, + selected_rows[cid]["kld"], rel_tol=1e-9, abs_tol=1e-12), + "Full-coverage block KLD disagrees with the recorded scalar") + def average(sample): + return sum(x[0] for x in sample) / sum(x[1] for x in sample) + interval = None + if len(blocks) >= 2: + rng = random.Random(seed) + bootstrap = sorted(average(rng.choices(blocks, k=len(blocks))) for _ in range(resamples)) + interval = [bootstrap[int((resamples - 1) * .025)], bootstrap[int((resamples - 1) * .975)]] + return {"schema_version": VERSION, "plan_id": plan["plan_id"], "partition": partition, + "left": left, "right": right, "right_minus_left_kld": average(blocks), + "right_minus_left_block_kld": average(blocks), + "right_minus_left_scalar_kld": selected_rows[right]["kld"] - selected_rows[left]["kld"], + "contrast_scope": "full_evaluation" if complete_coverage else "supplied_blocks_only", + "block_coverage_fraction": block_tokens / full, + "paired_block_bootstrap_interval_95": interval, "blocks": len(blocks), + "block_tokens": block_tokens, "evaluation_tokens": full, + "resamples": resamples, "seed": seed, + "scope": "The contrast and interval describe only the supplied independent blocks; partial coverage does not establish the full scalar difference. The scalar difference is reported separately without an interval. Negative difference favors right. One block cannot estimate sampling uncertainty; this is not hardware uncertainty or a universal task-quality guarantee."} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("plan", help="Freeze a bounded exact-map factorial and clone manifest") + p.add_argument("--source-manifest", required=True); p.add_argument("--spec", required=True); p.add_argument("--output", required=True) + for command in ("analyze", "replay", "screen", "paired", "propose"): + p = sub.add_parser(command) + p.add_argument("--plan", required=True); p.add_argument("--output", required=True) + if command != "propose": p.add_argument("--measurements", required=True) + if command in ("analyze", "screen", "paired"): + p.add_argument("--partition", choices=PARTITIONS, required=True) + if command in ("replay", "propose"): + p.add_argument("--scores", required=True); p.add_argument("--budget", type=int, required=True) + p.add_argument("--seed", type=int, default=0) + if command == "replay": + p.add_argument("--batch-size", type=int, default=3); p.add_argument("--regularization", type=float, default=.001) + if command == "propose": p.add_argument("--policy", choices=("projected", "raw", "disagreement", "random"), required=True) + if command == "screen": + p.add_argument("--low-tokens", type=int, required=True); p.add_argument("--keep-fraction", type=float, default=.5) + if command == "paired": + p.add_argument("--left", required=True); p.add_argument("--right", required=True) + p.add_argument("--replicate", default="0"); p.add_argument("--resamples", type=int, default=2000); p.add_argument("--seed", type=int, default=0) + args = parser.parse_args(argv) + try: + output = Path(args.output) + require(not output.exists(), f"Output already exists: {output}; use a new path to preserve evidence") + if args.command == "plan": + plan = plan_experiment(read_json(args.source_manifest), read_json(args.spec)) + output.mkdir(parents=True) + write_json(output / "plan.json", plan) + write_json(output / "magicquant.clone-configs.json", clone_manifest(plan)) + (output / "measurements.template.jsonl").write_text("".join(canonical(r) + "\n" for r in measurement_template(plan)), encoding="utf-8") + print(f"{plan['factorial_cells']} cells, {plan['unique_maps']} unique exact maps; plan {plan['plan_id']}") + return 0 + plan = validate_plan(read_json(args.plan)) + if args.command == "propose": + positive_int(args.budget, "budget", maximum=MAX_RECIPES) + document = read_json(args.scores) + scores, training = load_scores(plan, document) + ids = rank_batch(plan, scores, training, args.policy, args.budget, seed=args.seed) + output.mkdir(parents=True) + write_json(output / "magicquant.clone-configs.json", clone_manifest(plan, ids)) + write_json(output / "proposal.json", {"schema_version": VERSION, "plan_id": plan["plan_id"], + "policy": args.policy, "seed": args.seed, "budget": args.budget, + "score_document_sha256": digest(document), "selected_candidate_ids": ids, + "scope": "No measurement file was loaded during proposal selection."}) + return 0 + rows = load_measurements(plan, args.measurements) + if args.command == "analyze": result = analyze(plan, rows, args.partition) + elif args.command == "replay": result = replay(plan, rows, read_json(args.scores), budget=args.budget, + batch_size=args.batch_size, seed=args.seed, regularization=args.regularization) + elif args.command == "screen": result = screening(plan, rows, args.partition, args.low_tokens, args.keep_fraction) + else: result = paired_comparison(plan, rows, args.left, args.right, args.partition, + replicate=args.replicate, resamples=args.resamples, seed=args.seed) + output.parent.mkdir(parents=True, exist_ok=True) + write_json(output, result) + print(output) + return 0 + except (ProtocolError, ValueError, KeyError, TypeError, OSError) as exc: + print(f"discovery_lab: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test_discovery_lab.py b/scripts/test_discovery_lab.py new file mode 100644 index 0000000..b984c5d --- /dev/null +++ b/scripts/test_discovery_lab.py @@ -0,0 +1,337 @@ +"""Behavioral experiments for the offline lab; these use synthetic data, never model scores.""" +import copy +import json +import math +import tempfile +import unittest +from pathlib import Path + +import discovery_lab as lab + + +def fixture(dimensions=3, states=3): + names = ["blk.0.attn_q.weight", "blk.0.ffn_down.weight", "output.weight"] + artifacts = [] + for name, kind in (("base.gguf", "Q8_0"), ("small.gguf", "Q4_K"), ("middle.gguf", "Q6_K")): + artifacts.append({"FileName": name, "BaseQuant": "Q8_0", "SourceKld": 99, + "TensorTypes": {**{n: kind for n in names}, "blk.0.norm.weight": "F32"}}) + source = {"SchemaVersion": 1, "Artifacts": artifacts, "SourceModelId": "synthetic-fixture"} + spec = { + "schema_version": 1, "campaign_id": "synthetic-fixture", "base_artifact": "base.gguf", + "max_recipes": 27, "byte_ceilings": [160, 240, 310], + "artifact_context": {"source_weights_sha256": lab.digest("source"), + "quantizer_sha256": lab.digest("quantizer"), "imatrix_sha256": None, + "quantizer_options": {}}, + "evaluation_contexts": { + p: {"chunks_sha256": lab.digest(p), "tokenizer_sha256": lab.digest("tokenizer"), + "reference_sha256": lab.digest("reference-" + p), "evaluator_sha256": lab.digest("evaluator"), + "context_length": 2048, "token_budget": 8192, "sample_policy": "nested_prefix", + "numerical_topology": "synthetic-no-device"} for p in lab.PARTITIONS}, + "dimensions": [{"name": f"group-{i}", "tensor_patterns": [names[i]], + "states": [{"name": label, "donor_artifact": donor} + for label, donor in (("base", "$base"), ("small", "small.gguf"), + ("middle", "middle.gguf"))][:states]} + for i in range(dimensions)]} + return source, spec + + +def synthetic_rows(plan): + rows = [] + for partition in lab.PARTITIONS: + for row, candidate in zip(lab.measurement_template(plan, partition), plan["candidates"]): + a = candidate["assignments"][0] + changes = sum(state != "base" for state in a.values()) + small = sum(state == "small" for state in a.values()) + row.update(status="measured", artifact_sha256=lab.digest("artifact-" + candidate["candidate_id"]), + size_bytes=300 - changes * 30 - small * 20, + kld=.001 + changes * .001 + small * .0003, + build_seconds=2, evaluation_seconds=5) + rows.append(row) + return rows + + +def score_document(plan, rows): + observed = lab.measurements_at(plan, rows, "discovery") + first = plan["candidates"][0]["candidate_id"] + return {"plan_id": plan["plan_id"], "training_evaluation_context_id": lab.evaluation_id(plan, "discovery", 8192), + "training_candidate_ids": [first], + "scores": [{"candidate_id": cid, "eligible": True, "predicted_size_bytes": point["size_bytes"], + "raw_kld": point["kld"] * 1.1, "projected_kld": point["kld"] * 1.2} + for cid, point in observed.items()]} + + +class DiscoveryLabTests(unittest.TestCase): + def setUp(self): + self.source, self.spec = fixture() + self.plan = lab.plan_experiment(self.source, self.spec) + + def load(self, rows, plan=None): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "measurements.jsonl" + path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + return lab.load_measurements(plan or self.plan, path) + + def test_factorial_exact_maps_preserve_protected_and_unselected_tensors(self): + self.assertEqual(27, self.plan["factorial_cells"]) + self.assertEqual(27, self.plan["unique_maps"]) + self.assertEqual(self.plan, lab.plan_experiment(self.source, self.spec)) + for candidate in self.plan["candidates"]: + self.assertEqual("F32", candidate["tensor_types"]["blk.0.norm.weight"]) + self.assertEqual(candidate["candidate_id"], lab.digest(candidate["tensor_types"])) + clone = lab.clone_manifest(self.plan) + self.assertTrue(all(a["SourceKld"] is None and a["SourceSizeBytes"] is None for a in clone["Artifacts"])) + + def test_random_priority_is_stable_across_batches_and_exclusions(self): + # All recipes fit every ceiling, isolating random priority from the + # intentionally separate round-robin allocation among size ceilings. + scores = {c["candidate_id"]: {"eligible": True, "predicted_size_bytes": 1, + "raw_kld": .01, "projected_kld": .01} + for c in self.plan["candidates"]} + for seed in (0, 17, 101): + whole = lab.rank_batch(self.plan, scores, set(), "random", len(scores), seed=seed) + initially_excluded = {whole[0], whole[4]} + expected = [cid for cid in whole if cid not in initially_excluded] + for batch_size in (1, 2, 3, 7, len(scores)): + with self.subTest(seed=seed, batch_size=batch_size): + selected = [] + while len(selected) < len(expected): + batch = lab.rank_batch(self.plan, scores, initially_excluded | set(selected), + "random", min(batch_size, len(expected) - len(selected)), + seed=seed) + self.assertTrue(batch) + selected.extend(batch) + self.assertEqual(expected, selected) + + def test_duplicate_effective_maps_keep_design_aliases(self): + source, spec = fixture(1, 3) + source["Artifacts"][2]["TensorTypes"] = dict(source["Artifacts"][0]["TensorTypes"]) + plan = lab.plan_experiment(source, spec) + self.assertEqual(3, plan["factorial_cells"]) + self.assertEqual(2, plan["unique_maps"]) + self.assertEqual(2, len(plan["candidates"][0]["assignments"])) + + def test_plan_mutation_does_not_silently_change_an_experiment(self): + lab.validate_plan(self.plan) + changed = copy.deepcopy(self.plan) + changed["specification"]["byte_ceilings"] = [123] + with self.assertRaisesRegex(lab.ProtocolError, "changed after freezing"): + lab.validate_plan(changed) + + def test_excessive_factorial_fails_before_output(self): + self.spec["max_recipes"] = 26 + with self.assertRaisesRegex(lab.ProtocolError, "27 cells"): + lab.plan_experiment(self.source, self.spec) + + def test_overlapping_empty_and_protected_groups_are_rejected(self): + for patterns in (["output.weight"], ["missing.*"]): + spec = copy.deepcopy(self.spec) + spec["dimensions"][0]["tensor_patterns"] = patterns + with self.assertRaises(lab.ProtocolError): lab.plan_experiment(self.source, spec) + source, spec = fixture(1, 2) + source["Artifacts"][1]["TensorTypes"]["blk.0.norm.weight"] = "F16" + spec["dimensions"][0]["tensor_patterns"] = ["blk.0.norm.weight"] + with self.assertRaisesRegex(lab.ProtocolError, "protected"): + lab.plan_experiment(source, spec) + + def test_partition_labels_cannot_hide_reused_data(self): + self.spec["evaluation_contexts"]["holdout"]["chunks_sha256"] = self.spec["evaluation_contexts"]["validation"]["chunks_sha256"] + with self.assertRaisesRegex(lab.ProtocolError, "distinct chunk"): + lab.plan_experiment(self.source, self.spec) + + def test_actual_identity_fidelity_and_finite_quality_are_required(self): + original = synthetic_rows(self.plan)[0] + for change in ({"evaluation_context_id": "wrong"}, {"artifact_context_id": "wrong"}, + {"fidelity_tokens": 32768}, {"artifact_sha256": "unverified"}, + {"kld": float("nan")}, {"size_bytes": 0}): + with self.subTest(change=change), self.assertRaises(lab.ProtocolError): + self.load([dict(original, **change)]) + + def test_failures_are_not_negative_quality_labels(self): + row = synthetic_rows(self.plan)[0] + row["status"] = "build_failed" + with self.assertRaisesRegex(lab.ProtocolError, "cannot have a quality label"): + self.load([row]) + row["kld"] = None + loaded = self.load([row]) + result = lab.analyze(self.plan, loaded, "discovery") + self.assertEqual(0, result["coverage"]["fully_measured_maps"]) + self.assertEqual(1, result["coverage"]["status_counts"]["build_failed"]) + + def test_duplicate_replicates_and_different_artifacts_are_rejected(self): + row = synthetic_rows(self.plan)[0] + with self.assertRaisesRegex(lab.ProtocolError, "duplicate measurement"): + self.load([row, row]) + second = dict(row, replicate="1", artifact_sha256=lab.digest("changed-bytes")) + with self.assertRaisesRegex(lab.ProtocolError, "different artifacts"): + self.load([row, second]) + + def test_full_fidelity_and_partial_fidelity_remain_separate(self): + row = synthetic_rows(self.plan)[0] + low = dict(row, fidelity_tokens=2048, evaluation_context_id=lab.evaluation_id(self.plan, "discovery", 2048)) + loaded = self.load([low]) + self.assertFalse(lab.measurements_at(self.plan, loaded, "discovery")) + self.assertEqual(1, len(lab.measurements_at(self.plan, loaded, "discovery", 2048))) + + def test_contextual_interaction_uses_all_four_measured_cells(self): + plan = lab.plan_experiment(*fixture(2, 2)) + rows = [r for r in synthetic_rows(plan) if r["partition"] == "validation"] + for row, kld in zip(rows, (.010, .030, .020, .025)): row["kld"] = kld + measured = lab.measurements_at(plan, self.load(rows, plan), "validation") + result = lab.interactions(plan, measured) + self.assertEqual(1, len(result["complete_contrasts"])) + self.assertAlmostEqual(-.015, result["complete_contrasts"][0]["interaction_kld"]) + measured.pop(rows[-1]["candidate_id"]) + self.assertEqual(1, lab.interactions(plan, measured)["incomplete_contrasts"]) + + def test_frontier_keeps_close_points_and_equal_metric_aliases(self): + points = [{"candidate_id": name, "size_bytes": size, "kld": kld} + for name, size, kld in (("a", 100, .1), ("b", 101, .09), ("c", 200, .01), + ("alias", 101, .09), ("dominated", 150, .11))] + self.assertEqual({"a", "b", "c", "alias"}, {p["candidate_id"] for p in lab.frontier(points)}) + + def test_replay_does_not_use_validation_or_holdout_labels_to_select(self): + rows = self.load(synthetic_rows(self.plan)) + scores = score_document(self.plan, rows) + first = lab.replay(self.plan, rows, scores, budget=6, batch_size=2) + changed = [dict(r, kld=1000-r["kld"]) if r["partition"] != "discovery" else r for r in rows] + second = lab.replay(self.plan, changed, scores, budget=6, batch_size=2) + self.assertEqual([p["trace"] for p in first["policies"]], [p["trace"] for p in second["policies"]]) + for policy in first["policies"]: + acquired = set(scores["training_candidate_ids"]) + for batch in policy["trace"]: + self.assertEqual(acquired, set(batch["available_labels_before"])) + self.assertFalse(acquired.intersection(batch["requested_candidate_ids"])) + acquired.update(batch["new_valid_discovery_labels"]) + + def test_missing_scores_and_unmeasured_requests_remain_visible(self): + rows = synthetic_rows(self.plan) + scores = score_document(self.plan, rows) + scores["scores"].pop() + initial = scores["training_candidate_ids"][0] + limited = [r for r in rows if r["partition"] != "discovery" or r["candidate_id"] == initial] + result = lab.replay(self.plan, limited, scores, budget=3) + self.assertEqual("missing_score", result["exclusions"][0]["reason"]) + self.assertTrue(all(p["requests_without_full_discovery_label"] for p in result["policies"])) + + def test_failed_or_unobserved_discovery_request_cannot_earn_validation_credit(self): + plan = lab.plan_experiment(*fixture(1, 2)) + original = synthetic_rows(plan) + scores = score_document(plan, original) + initial = scores["training_candidate_ids"][0] + requested = next(c["candidate_id"] for c in plan["candidates"] if c["candidate_id"] != initial) + for status in ("build_failed", "evaluation_failed", None): + rows = [copy.deepcopy(r) for r in original + if r["partition"] != "discovery" or r["candidate_id"] == initial] + for row in rows: + if row["partition"] == "validation": + row["kld"] = .5 if row["candidate_id"] == initial else .01 + if status: + failed = next(copy.deepcopy(r) for r in original + if r["partition"] == "discovery" and r["candidate_id"] == requested) + failed.update(status=status, kld=None) + rows.append(failed) + result = lab.replay(plan, self.load(rows, plan), scores, budget=1, batch_size=1) + for policy in result["policies"]: + self.assertEqual([requested], policy["selected_candidate_ids"]) + self.assertEqual(1, policy["requested_new_recipes"]) + self.assertEqual(0, policy["successful_new_discovery_recipes"]) + self.assertEqual([initial], policy["validation_eligible_candidate_ids"]) + self.assertEqual(0, policy["observed_frontier_recall"]) + best = next(x["best"] for x in policy["best_under_byte_ceilings"] if x["byte_ceiling"] == 310) + self.assertEqual(initial, best["candidate_id"]) + + def test_heldout_context_cannot_be_declared_score_training_context(self): + rows = synthetic_rows(self.plan) + scores = score_document(self.plan, rows) + scores["training_evaluation_context_id"] = lab.evaluation_id(self.plan, "holdout", 8192) + with self.assertRaisesRegex(lab.ProtocolError, "discovery context"): + lab.load_scores(self.plan, scores) + + def test_residual_fit_updates_only_acquired_finite_labels(self): + feature_map = {"a": [1, 0], "b": [1, 1], "c": [1, 2]} + scores = {cid: {"eligible": True, "raw_kld": .01} for cid in feature_map} + result = lab.residual_predictions(feature_map, {"a": {"kld": .01}, "b": {"kld": .02}}, scores, 1e-8) + self.assertAlmostEqual(.03, result["c"], places=7) + self.assertEqual(.01, lab.residual_predictions(feature_map, {}, scores, .001)["c"]) + + def test_screening_counts_final_winners_missing_from_short_run(self): + rows = synthetic_rows(self.plan) + baseline = rows[0] + low = dict(baseline, fidelity_tokens=2048, evaluation_context_id=lab.evaluation_id(self.plan, "discovery", 2048)) + result = lab.screening(self.plan, rows + [low], "discovery", 2048, .5) + self.assertTrue(result["frontier_without_low_fidelity"]) + self.assertLess(result["frontier_recall"], 1) + + def test_paired_block_comparison_matches_identity_and_weights_tokens(self): + rows = [r for r in synthetic_rows(self.plan) if r["partition"] == "validation"][:2] + rows[0]["blocks"] = [{"id": "doc-a", "tokens": 100, "kld_sum": 1}, + {"id": "doc-b", "tokens": 300, "kld_sum": 3}] + rows[1]["blocks"] = [{"id": "doc-a", "tokens": 100, "kld_sum": .5}, + {"id": "doc-b", "tokens": 300, "kld_sum": 1.5}] + rows = self.load(rows) + a, b = [r["candidate_id"] for r in rows] + result = lab.paired_comparison(self.plan, rows, a, b, "validation", resamples=100) + self.assertAlmostEqual(-.005, result["right_minus_left_kld"]) + self.assertEqual([-.005, -.005], result["paired_block_bootstrap_interval_95"]) + rows[1]["blocks"][0]["id"] = "different-document" + with self.assertRaisesRegex(lab.ProtocolError, "identical block"): + lab.paired_comparison(self.plan, rows, a, b, "validation") + + def test_one_block_does_not_produce_false_precision(self): + rows = [r for r in synthetic_rows(self.plan) if r["partition"] == "validation"][:2] + for r in rows: r["blocks"] = [{"id": "one", "tokens": 100, "kld_sum": 1}] + result = lab.paired_comparison(self.plan, rows, rows[0]["candidate_id"], rows[1]["candidate_id"], "validation") + self.assertIsNone(result["paired_block_bootstrap_interval_95"]) + + def test_partial_paired_blocks_are_not_presented_as_the_whole_evaluation_difference(self): + rows = [r for r in synthetic_rows(self.plan) if r["partition"] == "validation"][:2] + rows[0]["blocks"] = [{"id": "document", "tokens": 100, "kld_sum": 2}] + rows[1]["blocks"] = [{"id": "document", "tokens": 100, "kld_sum": 1}] + result = lab.paired_comparison(self.plan, self.load(rows), + rows[0]["candidate_id"], rows[1]["candidate_id"], "validation") + self.assertEqual("supplied_blocks_only", result["contrast_scope"]) + self.assertAlmostEqual(100 / 8192, result["block_coverage_fraction"]) + self.assertAlmostEqual(-.01, result["right_minus_left_block_kld"]) + self.assertGreater(result["right_minus_left_scalar_kld"], 0) + + def test_full_coverage_blocks_must_agree_with_scalar_measurement(self): + row = synthetic_rows(self.plan)[0] + row["blocks"] = [{"id": "all-evaluated-tokens", "tokens": 8192, "kld_sum": row["kld"] * 8192}] + self.load([row]) + row["blocks"][0]["kld_sum"] *= 2 + with self.assertRaisesRegex(lab.ProtocolError, "Full-coverage block KLD"): + self.load([row]) + + def test_observed_block_overlap_across_partitions_is_rejected(self): + rows = synthetic_rows(self.plan) + selected = [next(r for r in rows if r["partition"] == partition) + for partition in ("discovery", "holdout")] + for row in selected: + row["blocks"] = [{"id": "same-content-block", "tokens": 100, "kld_sum": .1}] + with self.assertRaisesRegex(lab.ProtocolError, "reused across data partitions"): + self.load(selected) + + def test_screening_rejects_zero_or_negative_fidelity(self): + for low_tokens in (0, -1): + with self.assertRaisesRegex(lab.ProtocolError, "positive integer"): + lab.screening(self.plan, synthetic_rows(self.plan), "discovery", low_tokens, .5) + + def test_cli_generates_usable_clone_manifest_and_preserves_existing_output(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + lab.write_json(root / "source.json", self.source); lab.write_json(root / "spec.json", self.spec) + args = ["plan", "--source-manifest", str(root / "source.json"), "--spec", str(root / "spec.json"), "--output", str(root / "plan")] + self.assertEqual(0, lab.main(args)) + written = lab.validate_plan(lab.read_json(root / "plan/plan.json")) + self.assertEqual(self.plan, written) + self.assertEqual(27, len(lab.read_json(root / "plan/magicquant.clone-configs.json")["Artifacts"])) + self.assertEqual(27, len(lab.load_measurements(written, root / "plan/measurements.template.jsonl"))) + self.assertEqual(2, lab.main(args)) + + def test_json_rejects_duplicate_identity_fields(self): + with self.assertRaisesRegex(lab.ProtocolError, "Duplicate JSON key"): + lab.parse_json('{"artifact_context_id":"a","artifact_context_id":"b"}') + + +if __name__ == "__main__": + unittest.main() diff --git a/src/MQ.DB/Migrations/20261201000000_BenchmarkEvidenceIdentity.Designer.cs b/src/MQ.DB/Migrations/20261201000000_BenchmarkEvidenceIdentity.Designer.cs new file mode 100644 index 0000000..faed573 --- /dev/null +++ b/src/MQ.DB/Migrations/20261201000000_BenchmarkEvidenceIdentity.Designer.cs @@ -0,0 +1,1741 @@ +// +using System; +using MQ.DB.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace MQ.DB.Migrations +{ + [DbContext(typeof(MagicQuantContext))] + [Migration("20261201000000_BenchmarkEvidenceIdentity")] + partial class BenchmarkEvidenceIdentity + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AiBenchmark", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("EvidenceIdentityHash") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ImatrixDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("Ngl") + .HasColumnType("INTEGER"); + + b.Property("SizeBytes") + .HasColumnType("INTEGER"); + + b.Property("TensorComboId") + .HasColumnType("TEXT"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.Property("TokensPerSecond") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("ImatrixDefinitionId"); + + b.HasIndex("TensorComboId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "TensorComboId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "AiModelHashId", "ImatrixDefinitionId", "TensorComboId") + .IsUnique(); + + b.ToTable("AiBenchmarks"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AiBenchmarkLearnedSource", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiBenchmarkId") + .HasColumnType("TEXT"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("BaselineCanonicalKey") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("BaselineQuantDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("SourceLearningBenchmarkId") + .HasColumnType("TEXT"); + + b.Property("TensorComboId") + .HasColumnType("TEXT"); + + b.Property("TensorGroupId") + .HasColumnType("INTEGER"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("BaselineQuantDefinitionId"); + + b.HasIndex("SourceLearningBenchmarkId"); + + b.HasIndex("TensorComboId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("AiBenchmarkId", "TensorGroupId") + .IsUnique(); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "BaselineQuantDefinitionId"); + + b.ToTable("AiBenchmarkLearnedSources"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AiModelHash", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("UniqueHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UniqueHash"); + + b.ToTable("AiModelHashes"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyInteractionRule", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("AppliedPredictionSpaceAdjustmentKld") + .HasColumnType("REAL"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("BenchmarkCategory") + .HasColumnType("INTEGER"); + + b.Property("BestActualGainVsTwin") + .HasColumnType("REAL"); + + b.Property("BestPredictionSpaceGap") + .HasColumnType("REAL"); + + b.Property("CandidateDisplayName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("CandidateEffectiveGroupsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CandidateInternalName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Confidence") + .HasColumnType("REAL"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("EvidenceCount") + .HasColumnType("INTEGER"); + + b.Property("FullTensorConfigKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("GroupCount") + .HasColumnType("INTEGER"); + + b.Property("GroupSetHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ImatrixDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("InactiveGroupsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("MeanActualGainVsTwin") + .HasColumnType("REAL"); + + b.Property("MeanPredictionSpaceGap") + .HasColumnType("REAL"); + + b.Property("MetadataJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("MovementClassification") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ReferenceContextKey") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("ReferenceDisplayName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("ReferenceEffectiveGroupsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReferenceInternalName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("ReferenceQuantId") + .HasColumnType("INTEGER"); + + b.Property("RuleDirection") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RuleStatus") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RuleType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ShrinkFactor") + .HasColumnType("REAL"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.Property("UpdatedUtc") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("FullTensorConfigKey"); + + b.HasIndex("ImatrixDefinitionId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "AiModelHashId", "ImatrixDefinitionId", "BenchmarkCategory", "RuleDirection", "RuleStatus"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "AiModelHashId", "ImatrixDefinitionId", "BenchmarkCategory", "ReferenceQuantId", "ReferenceContextKey", "GroupSetHash", "RuleDirection") + .IsUnique(); + + b.ToTable("AnomalyInteractionRules"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyInteractionRuleGroupState", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("CandidateQuantId") + .HasColumnType("INTEGER"); + + b.Property("Movement") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ReferenceQuantId") + .HasColumnType("INTEGER"); + + b.Property("RuleId") + .HasColumnType("TEXT"); + + b.Property("SortOrder") + .HasColumnType("INTEGER"); + + b.Property("TensorGroupId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("RuleId", "TensorGroupId") + .IsUnique(); + + b.ToTable("AnomalyInteractionRuleGroupStates"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyProbeObservation", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("Accepted") + .HasColumnType("INTEGER"); + + b.Property("ActualGainVsTwin") + .HasColumnType("REAL"); + + b.Property("ActualKld") + .HasColumnType("REAL"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("AllActiveGroupsExplicit") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("BenchmarkCategory") + .HasColumnType("INTEGER"); + + b.Property("CandidateEffectiveGroupsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CandidateQuantsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ChangedGroupSetHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ChangedGroupsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Classification") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("DowngradeCount") + .HasColumnType("INTEGER"); + + b.Property("FailureCode") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("HypothesisLabel") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ImatrixDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("InactiveGroupsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IsContextualAnomalyProbe") + .HasColumnType("INTEGER"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("MovementClassification") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("NetBitDelta") + .HasColumnType("INTEGER"); + + b.Property("OldBf16Isolation") + .HasColumnType("INTEGER"); + + b.Property("PredictedKld") + .HasColumnType("REAL"); + + b.Property("PredictionSpaceGapVsTwin") + .HasColumnType("REAL"); + + b.Property("ProbeDisplayName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("ProbeInternalName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("ProbePlanClass") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ProbeTensorComboId") + .HasColumnType("TEXT"); + + b.Property("ProbeTensorConfigKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProbeType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ReferenceActualKld") + .HasColumnType("REAL"); + + b.Property("ReferenceDisplayName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("ReferenceEffectiveGroupsJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReferenceInternalName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("ReferencePredictedKld") + .HasColumnType("REAL"); + + b.Property("ReferenceQuantId") + .HasColumnType("INTEGER"); + + b.Property("ReferenceTensorComboId") + .HasColumnType("TEXT"); + + b.Property("ReferenceTensorConfigKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RuleDirection") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SameCount") + .HasColumnType("INTEGER"); + + b.Property("SeedClass") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SeedPriority") + .HasColumnType("INTEGER"); + + b.Property("SessionId") + .HasColumnType("TEXT"); + + b.Property("SizeSavingsBytes") + .HasColumnType("INTEGER"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.Property("UnknownCount") + .HasColumnType("INTEGER"); + + b.Property("UpgradeCount") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("ImatrixDefinitionId"); + + b.HasIndex("ProbeTensorComboId"); + + b.HasIndex("ProbeTensorConfigKey"); + + b.HasIndex("ReferenceTensorComboId"); + + b.HasIndex("ReferenceTensorConfigKey"); + + b.HasIndex("SessionId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "AiModelHashId", "ImatrixDefinitionId", "BenchmarkCategory", "ChangedGroupSetHash"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "AiModelHashId", "ImatrixDefinitionId", "BenchmarkCategory", "ReferenceTensorComboId", "ProbeTensorComboId", "ProbeType"); + + b.ToTable("AnomalyProbeObservations"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyProbeSession", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("BenchmarkCategory") + .HasColumnType("INTEGER"); + + b.Property("CompletedUtc") + .HasColumnType("TEXT"); + + b.Property("ConfigJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ImatrixDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("SourceRunLabel") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("TEXT"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("ImatrixDefinitionId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "AiModelHashId", "ImatrixDefinitionId", "BenchmarkCategory", "StartedUtc"); + + b.ToTable("AnomalyProbeSessions"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.ArchitectureFamily", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("TensorCount") + .HasColumnType("INTEGER"); + + b.Property("TensorSignatureHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique(); + + b.HasIndex("TensorSignatureHash", "TensorCount"); + + b.ToTable("ArchitectureFamilies"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.ArchitectureFamilyModelHash", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("IsCanonical") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiModelHashId") + .IsUnique(); + + b.HasIndex("ArchitectureFamilyId", "AiModelHashId") + .IsUnique(); + + b.ToTable("ArchitectureFamilyModelHashes"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.BaselineQuantDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("BaselineFamily") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("BaselineName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("BitRange") + .HasColumnType("INTEGER"); + + b.Property("CanonicalKey") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("DefaultTensorSchemeId") + .HasColumnType("INTEGER"); + + b.Property("DefaultTensorSchemeName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExplicitCandidateSortOrder") + .HasColumnType("INTEGER"); + + b.Property("FirstSeenUtc") + .HasColumnType("TEXT"); + + b.Property("IsActiveInCurrentConfig") + .HasColumnType("INTEGER"); + + b.Property("IsCombinationCarrierCandidate") + .HasColumnType("INTEGER"); + + b.Property("IsCustomBaseline") + .HasColumnType("INTEGER"); + + b.Property("IsExplicitGroupCombinationCandidate") + .HasColumnType("INTEGER"); + + b.Property("IsLearningBaseline") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("TEXT"); + + b.Property("LastUpdatedUtc") + .HasColumnType("TEXT"); + + b.Property("NormalizedCanonicalKey") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("NormalizedSourceFileName") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("NormalizedSourceRepository") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("QuantizeBaseArgumentName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RequiresImatrix") + .HasColumnType("INTEGER"); + + b.Property("RuntimeBaselineId") + .HasColumnType("INTEGER"); + + b.Property("ShortSourceName") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SourceFileName") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("SourceKind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SourceOwner") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("SourceRepository") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("IsActiveInCurrentConfig"); + + b.HasIndex("ArchitectureFamilyId", "NormalizedCanonicalKey") + .IsUnique(); + + b.HasIndex("ArchitectureFamilyId", "RuntimeBaselineId") + .IsUnique(); + + b.HasIndex("RuntimeBaselineId", "ArchitectureFamilyId"); + + b.HasIndex("ArchitectureFamilyId", "NormalizedSourceRepository", "NormalizedSourceFileName") + .IsUnique(); + + b.ToTable("BaselineQuantDefinitions"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.BenchmarkRun", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiBenchmarkId") + .HasColumnType("TEXT"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("Category") + .HasColumnType("INTEGER"); + + b.Property("CategoryBenchmarkId") + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("Error") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("ImatrixDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("StartedUtc") + .HasColumnType("TEXT"); + + b.Property("Succeeded") + .HasColumnType("INTEGER"); + + b.Property("TensorComboId") + .HasColumnType("TEXT"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiBenchmarkId"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("ArchitectureFamilyId"); + + b.HasIndex("CategoryBenchmarkId"); + + b.HasIndex("ImatrixDefinitionId"); + + b.HasIndex("StartedUtc"); + + b.HasIndex("TensorComboId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("AiBenchmarkId", "Category"); + + b.ToTable("BenchmarkRuns"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.CategoryBenchmark", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiBenchmarkId") + .HasColumnType("TEXT"); + + b.Property("Category") + .HasColumnType("INTEGER"); + + b.Property("Kld") + .HasColumnType("REAL"); + + b.Property("Ppl") + .HasColumnType("REAL"); + + b.Property("PplError") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("AiBenchmarkId"); + + b.ToTable("CategoryBenchmark"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.ExecutionPlanProbeCache", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("DiscoveryTokenTarget") + .HasColumnType("INTEGER"); + + b.Property("GpuMemoryLimitsJson") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("GroupSize") + .HasColumnType("INTEGER"); + + b.Property("HardwareFingerprint") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("ImatrixDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("MaxCandidateNgl") + .HasColumnType("INTEGER"); + + b.Property("NativeModelSizeBytes") + .HasColumnType("INTEGER"); + + b.Property("NativeQuantizationKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("NativeStableNgl") + .HasColumnType("INTEGER"); + + b.Property("ProbeSchemaVersion") + .HasColumnType("INTEGER"); + + b.Property("Q8ModelSizeBytes") + .HasColumnType("INTEGER"); + + b.Property("Q8StableNgl") + .HasColumnType("INTEGER"); + + b.Property("QuantizationKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("QuantizedModelFingerprint") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("SlotsJson") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("TEXT"); + + b.Property("StaticNgl") + .HasColumnType("INTEGER"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.Property("TensorSplitJson") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("TEXT"); + + b.Property("UsesGpu") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("ArchitectureFamilyId"); + + b.HasIndex("ImatrixDefinitionId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "AiModelHashId", "ImatrixDefinitionId", "HardwareFingerprint", "QuantizedModelFingerprint", "QuantizationKey", "DiscoveryTokenTarget") + .IsUnique(); + + b.ToTable("ExecutionPlanProbeCaches"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.ImatrixDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("BuildFingerprint") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("CanonicalPath") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("IdentityHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("MetadataJson") + .HasMaxLength(8000) + .HasColumnType("TEXT"); + + b.Property("SourceKind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("TokenCount") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiModelHashId", "IdentityHash") + .IsUnique(); + + b.ToTable("ImatrixDefinitions"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.LearnedBaselineTensorQuant", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiBenchmarkId") + .HasColumnType("TEXT"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("BaselineCanonicalKey") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("BaselineQuantDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("BaselineQuantId") + .HasColumnType("INTEGER"); + + b.Property("BaselineSourceFileName") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("BaselineSourceKind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("BaselineSourceRepository") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("FinalQuantType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("TensorComboId") + .HasColumnType("TEXT"); + + b.Property("TensorGroupId") + .HasColumnType("INTEGER"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.Property("TensorName") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("TensorWeightSchemeId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiBenchmarkId"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("BaselineQuantDefinitionId"); + + b.HasIndex("TensorComboId"); + + b.HasIndex("TensorGroupProfileId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "BaselineQuantDefinitionId", "TensorGroupId"); + + b.HasIndex("ArchitectureFamilyId", "TensorGroupProfileId", "BaselineQuantDefinitionId", "TensorWeightSchemeId", "TensorName") + .IsUnique(); + + b.ToTable("LearnedBaselineTensorQuants"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.QuantizationRun", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AiBenchmarkId") + .HasColumnType("TEXT"); + + b.Property("AiModelHashId") + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("CompletedUtc") + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("Error") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("ImatrixDefinitionId") + .HasColumnType("INTEGER"); + + b.Property("OutputModelPath") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("TEXT"); + + b.Property("Succeeded") + .HasColumnType("INTEGER"); + + b.Property("TensorComboId") + .HasColumnType("TEXT"); + + b.Property("TensorGroupProfileId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AiBenchmarkId"); + + b.HasIndex("AiModelHashId"); + + b.HasIndex("ArchitectureFamilyId"); + + b.HasIndex("ImatrixDefinitionId"); + + b.HasIndex("StartedUtc"); + + b.HasIndex("TensorComboId"); + + b.HasIndex("TensorGroupProfileId"); + + b.ToTable("QuantizationRuns"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.TensorCombo", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AttnKV") + .HasColumnType("INTEGER"); + + b.Property("AttnOutput") + .HasColumnType("INTEGER"); + + b.Property("AttnQ") + .HasColumnType("INTEGER"); + + b.Property("BaseQuant") + .HasColumnType("INTEGER"); + + b.Property("Embeddings") + .HasColumnType("INTEGER"); + + b.Property("FfnDown") + .HasColumnType("INTEGER"); + + b.Property("FfnUpGate") + .HasColumnType("INTEGER"); + + b.Property("LmHead") + .HasColumnType("INTEGER"); + + b.Property("MoeExperts") + .HasColumnType("INTEGER"); + + b.Property("MoeRouter") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("BaseQuant", "Embeddings", "LmHead", "AttnQ", "AttnKV", "AttnOutput", "FfnUpGate", "FfnDown", "MoeExperts", "MoeRouter") + .IsUnique(); + + b.ToTable("TensorCombos"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.TensorGroupProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ArchitectureFamilyId") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("TEXT"); + + b.Property("FingerprintHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("IsActive") + .HasColumnType("INTEGER"); + + b.Property("SnapshotJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ArchitectureFamilyId", "FingerprintHash") + .IsUnique(); + + b.HasIndex("ArchitectureFamilyId", "IsActive"); + + b.ToTable("TensorGroupProfiles"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AiBenchmark", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ImatrixDefinition", "ImatrixDefinition") + .WithMany() + .HasForeignKey("ImatrixDefinitionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorCombo", "TensorCombo") + .WithMany() + .HasForeignKey("TensorComboId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("ImatrixDefinition"); + + b.Navigation("TensorCombo"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AiBenchmarkLearnedSource", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiBenchmark", "AiBenchmark") + .WithMany("LearnedSources") + .HasForeignKey("AiBenchmarkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.BaselineQuantDefinition", "BaselineQuantDefinition") + .WithMany() + .HasForeignKey("BaselineQuantDefinitionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.AiBenchmark", "SourceLearningBenchmark") + .WithMany() + .HasForeignKey("SourceLearningBenchmarkId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("MQ.DB.Models.DbModels.TensorCombo", "TensorCombo") + .WithMany() + .HasForeignKey("TensorComboId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AiBenchmark"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("BaselineQuantDefinition"); + + b.Navigation("SourceLearningBenchmark"); + + b.Navigation("TensorCombo"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyInteractionRule", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ImatrixDefinition", "ImatrixDefinition") + .WithMany() + .HasForeignKey("ImatrixDefinitionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("ImatrixDefinition"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyInteractionRuleGroupState", b => + { + b.HasOne("MQ.DB.Models.DbModels.AnomalyInteractionRule", "Rule") + .WithMany("GroupStates") + .HasForeignKey("RuleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Rule"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyProbeObservation", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ImatrixDefinition", "ImatrixDefinition") + .WithMany() + .HasForeignKey("ImatrixDefinitionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorCombo", "ProbeTensorCombo") + .WithMany() + .HasForeignKey("ProbeTensorComboId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorCombo", "ReferenceTensorCombo") + .WithMany() + .HasForeignKey("ReferenceTensorComboId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.AnomalyProbeSession", "Session") + .WithMany("Observations") + .HasForeignKey("SessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("ImatrixDefinition"); + + b.Navigation("ProbeTensorCombo"); + + b.Navigation("ReferenceTensorCombo"); + + b.Navigation("Session"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyProbeSession", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ImatrixDefinition", "ImatrixDefinition") + .WithMany() + .HasForeignKey("ImatrixDefinitionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("ImatrixDefinition"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.ArchitectureFamilyModelHash", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.BaselineQuantDefinition", b => + { + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("ArchitectureFamily"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.BenchmarkRun", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiBenchmark", "AiBenchmark") + .WithMany() + .HasForeignKey("AiBenchmarkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.CategoryBenchmark", "CategoryBenchmark") + .WithMany() + .HasForeignKey("CategoryBenchmarkId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("MQ.DB.Models.DbModels.ImatrixDefinition", "ImatrixDefinition") + .WithMany() + .HasForeignKey("ImatrixDefinitionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorCombo", "TensorCombo") + .WithMany() + .HasForeignKey("TensorComboId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiBenchmark"); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("CategoryBenchmark"); + + b.Navigation("ImatrixDefinition"); + + b.Navigation("TensorCombo"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.CategoryBenchmark", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiBenchmark", "AiBenchmark") + .WithMany("CategorBenchmarks") + .HasForeignKey("AiBenchmarkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AiBenchmark"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.ExecutionPlanProbeCache", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ImatrixDefinition", "ImatrixDefinition") + .WithMany() + .HasForeignKey("ImatrixDefinitionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("ImatrixDefinition"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.ImatrixDefinition", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AiModelHash"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.LearnedBaselineTensorQuant", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiBenchmark", "AiBenchmark") + .WithMany() + .HasForeignKey("AiBenchmarkId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.BaselineQuantDefinition", "BaselineQuantDefinition") + .WithMany() + .HasForeignKey("BaselineQuantDefinitionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.TensorCombo", "TensorCombo") + .WithMany() + .HasForeignKey("TensorComboId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiBenchmark"); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("BaselineQuantDefinition"); + + b.Navigation("TensorCombo"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.QuantizationRun", b => + { + b.HasOne("MQ.DB.Models.DbModels.AiBenchmark", "AiBenchmark") + .WithMany() + .HasForeignKey("AiBenchmarkId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("MQ.DB.Models.DbModels.AiModelHash", "AiModelHash") + .WithMany() + .HasForeignKey("AiModelHashId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.ImatrixDefinition", "ImatrixDefinition") + .WithMany() + .HasForeignKey("ImatrixDefinitionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("MQ.DB.Models.DbModels.TensorCombo", "TensorCombo") + .WithMany() + .HasForeignKey("TensorComboId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("MQ.DB.Models.DbModels.TensorGroupProfile", "TensorGroupProfile") + .WithMany() + .HasForeignKey("TensorGroupProfileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AiBenchmark"); + + b.Navigation("AiModelHash"); + + b.Navigation("ArchitectureFamily"); + + b.Navigation("ImatrixDefinition"); + + b.Navigation("TensorCombo"); + + b.Navigation("TensorGroupProfile"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.TensorGroupProfile", b => + { + b.HasOne("MQ.DB.Models.DbModels.ArchitectureFamily", "ArchitectureFamily") + .WithMany() + .HasForeignKey("ArchitectureFamilyId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchitectureFamily"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AiBenchmark", b => + { + b.Navigation("CategorBenchmarks"); + + b.Navigation("LearnedSources"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyInteractionRule", b => + { + b.Navigation("GroupStates"); + }); + + modelBuilder.Entity("MQ.DB.Models.DbModels.AnomalyProbeSession", b => + { + b.Navigation("Observations"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/MQ.DB/Migrations/20261201000000_BenchmarkEvidenceIdentity.cs b/src/MQ.DB/Migrations/20261201000000_BenchmarkEvidenceIdentity.cs new file mode 100644 index 0000000..55c486c --- /dev/null +++ b/src/MQ.DB/Migrations/20261201000000_BenchmarkEvidenceIdentity.cs @@ -0,0 +1,15 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MQ.DB.Migrations; + +public partial class BenchmarkEvidenceIdentity : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + => migrationBuilder.AddColumn( + name: "EvidenceIdentityHash", table: "AiBenchmarks", type: "TEXT", maxLength: 64, nullable: true); + + protected override void Down(MigrationBuilder migrationBuilder) + => migrationBuilder.DropColumn(name: "EvidenceIdentityHash", table: "AiBenchmarks"); +} diff --git a/src/MQ.DB/Migrations/MagicQuantContextModelSnapshot.cs b/src/MQ.DB/Migrations/MagicQuantContextModelSnapshot.cs index 421ccef..856224a 100644 --- a/src/MQ.DB/Migrations/MagicQuantContextModelSnapshot.cs +++ b/src/MQ.DB/Migrations/MagicQuantContextModelSnapshot.cs @@ -28,6 +28,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("ArchitectureFamilyId") .HasColumnType("INTEGER"); + b.Property("EvidenceIdentityHash") + .HasMaxLength(64) + .HasColumnType("TEXT"); + b.Property("ImatrixDefinitionId") .HasColumnType("INTEGER"); diff --git a/src/MQ.DB/Models/BenchmarkResult.cs b/src/MQ.DB/Models/BenchmarkResult.cs index f5281d1..e4743e1 100644 --- a/src/MQ.DB/Models/BenchmarkResult.cs +++ b/src/MQ.DB/Models/BenchmarkResult.cs @@ -2,6 +2,11 @@ namespace MQ.DB.Models; public class BenchmarkResult { + /// Content identity of the artifact and evaluation that produced these metrics. + /// Legacy files without this envelope are deliberately not reusable. + public BenchmarkEvidenceManifest? Evidence { get; set; } + /// Observed elapsed stage times; process totals include model loading and fallback attempts. + public Dictionary StageMilliseconds { get; set; } = new(StringComparer.Ordinal); public LlamaBenchMetrics? LlamaBench { get; set; } public Dictionary Perplexity { get; set; } = @@ -12,4 +17,32 @@ public class BenchmarkResult /// even if the temporary GGUF has already been deleted. /// public ulong? ModelSizeBytes { get; set; } -} \ No newline at end of file +} + +public sealed class BenchmarkEvidenceManifest +{ + public int SchemaVersion { get; set; } = 1; + public string IdentityHash { get; set; } = string.Empty; + public string RecipeHash { get; set; } = string.Empty; + public string NativeSourceSha256 { get; set; } = string.Empty; + public string EvaluatorHash { get; set; } = string.Empty; + public string ExecutionPolicyHash { get; set; } = string.Empty; + /// CPU thread budget supplied to quantization concurrency planning, not process elapsed work. + public int QuantizerThreadCount { get; set; } + public int ScratchWriterCapacity { get; set; } + public bool ImatrixApplied { get; set; } + public string ModelSha256 { get; set; } = string.Empty; + public string? EquivalentSourceEvidenceHash { get; set; } + public int TokenTarget { get; set; } + public bool SaveLogits { get; set; } + public bool CompareLogits { get; set; } + public bool AllowIndependentGpuTopology { get; set; } + public Dictionary Domains { get; set; } = new(StringComparer.Ordinal); +} + +public sealed class BenchmarkDomainEvidence +{ + public string CorpusSha256 { get; set; } = string.Empty; + public string ReferenceDefinitionHash { get; set; } = string.Empty; + public string? ReferenceLogitsSha256 { get; set; } +} diff --git a/src/MQ.DB/Models/DbModels/AiBenchmark.cs b/src/MQ.DB/Models/DbModels/AiBenchmark.cs index b97c32f..b700a09 100644 --- a/src/MQ.DB/Models/DbModels/AiBenchmark.cs +++ b/src/MQ.DB/Models/DbModels/AiBenchmark.cs @@ -27,6 +27,10 @@ public class AiBenchmark : ISQLiteEntity public double TokensPerSecond { get; set; } + /// Identity of the measured artifact/evaluation envelope. Null means legacy, + /// unproven evidence, which must not be used as current measured truth. + public string? EvidenceIdentityHash { get; set; } + public int ArchitectureFamilyId { get; set; } public ArchitectureFamily ArchitectureFamily { get; set; } = default!; @@ -60,6 +64,8 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.Id) .ValueGeneratedNever(); + builder.Property(x => x.EvidenceIdentityHash).HasMaxLength(64); + builder.HasIndex(x => new { x.ArchitectureFamilyId, x.TensorGroupProfileId, x.AiModelHashId, x.ImatrixDefinitionId, x.TensorComboId }) .IsUnique(); diff --git a/src/MagicQuant/Commands/CloneRepositoryQuants.cs b/src/MagicQuant/Commands/CloneRepositoryQuants.cs index 18fdc18..66396e2 100644 --- a/src/MagicQuant/Commands/CloneRepositoryQuants.cs +++ b/src/MagicQuant/Commands/CloneRepositoryQuants.cs @@ -1,5 +1,6 @@ using System.Text.Json; using System.Text.Json.Nodes; +using System.Diagnostics; using MagicQuant.Configuration; using MagicQuant.Helpers; using MagicQuant.Models; @@ -50,6 +51,15 @@ public async Task Run(List args) bool allowMissingManifestTensors = args.Any(a => string.Equals(a.Name, CloneManifestTensorMapBuildService.AllowMissingManifestTensorsFlag, StringComparison.OrdinalIgnoreCase)); string? missingManifestBaseQuantName = Get(args, CloneManifestTensorMapBuildService.MissingManifestBaseQuantFlag); bool hasMissingManifestBaseQuantOverride = !string.IsNullOrWhiteSpace(missingManifestBaseQuantName); + string? benchmarkCorpus = Get(args, "benchmark-corpus"); + if (benchmarkCorpus != null) + { + benchmarkCorpus = Path.GetFullPath(benchmarkCorpus); + if (!File.Exists(benchmarkCorpus) || new FileInfo(benchmarkCorpus).Length == 0) + throw new ArgumentException("--benchmark-corpus must name an existing nonempty frozen text file."); + } + IReadOnlyDictionary? corpusOverrides = benchmarkCorpus == null + ? null : new Dictionary { ["general"] = benchmarkCorpus }; string? modelDirRaw = Get(args, "model-dir"); if (string.IsNullOrWhiteSpace(modelDirRaw)) @@ -86,6 +96,8 @@ public async Task Run(List args) Directory.CreateDirectory(Cache.ModelMagicQuantDirectory); Cache.OutputDirectory = ResolveAndValidateOutputDirectory(args); + if (benchmarkCorpus != null && PathSafety.Contains(Cache.OutputDirectory!, benchmarkCorpus)) + throw new ArgumentException("--benchmark-corpus must be outside the export directory, which clone mode cleans."); AnsiConsole.Write(new Rule("[yellow]Repository Quant Clone Mode[/]") { Justification = Justify.Left }); AnsiConsole.MarkupLine($"Model Path: [blue]{Markup.Escape(Cache.ModelDirectory)}[/]"); @@ -161,16 +173,6 @@ public async Task Run(List args) var imatrixEnsureResult = await imatrixService.EnsureImatrixAsync(imatrixRequest); RuntimeSearchSpace.SetImatrixAvailability(imatrixEnsureResult.Available); - var preCleanBenchmarkCache = Config.ReuseExistingFinalArtifacts - ? LoadReusableCloneBenchmarkRows(Cache.OutputDirectory!) - : new Dictionary(StringComparer.OrdinalIgnoreCase); - - bool canReuseEverything = TryLoadFullyReusableCloneRecords( - outputDirectory: Cache.OutputDirectory!, - manifest: manifest, - benchmarkCache: preCleanBenchmarkCache, - records: out var reusableRecords); - MagicQuant.Runtime.RunCancellation.Token.ThrowIfCancellationRequested(); await CleanOutputDirectoryAsync(Cache.OutputDirectory!, Config.ReuseExistingFinalArtifacts); @@ -193,19 +195,10 @@ public async Task Run(List args) var cloneBuildResults = new Dictionary(StringComparer.OrdinalIgnoreCase); - var records = canReuseEverything - ? reusableRecords - : new List(); - - if (records.Count == manifest.Artifacts.Count) - { - AnsiConsole.MarkupLine($"[green]Reused clone artifacts and benchmark summary:[/] all {records.Count:N0} artifact(s) matched existing GGUF byte sizes and {MagicQuantManifestPathService.CloneBenchmarksFileName}."); - } - else + var records = new List(); + // Always enter the evidence-aware evaluator. The release summary is an output, + // not a cache key; exact build proof and evaluation proof are separate checks. { - records.Clear(); - var benchmarkCache = preCleanBenchmarkCache; - string q8QuantizationKey = BaselineQuants.Q8_0.Names[0]; string nativeQuantizationKey = (Cache.TorchType ?? Cache.MainTorchType.BF16).ToString(); string cloneBenchmarkRootDir = Path.Combine(Cache.ModelMagicQuantDirectory!, "CloneBenchmarks"); @@ -245,7 +238,8 @@ await EnsureCloneNativeBenchmarkArtifactsReadyAsync( nativeModelPath: baseModelGgufPath, nativeBenchDir: nativeBenchDir, nativeLogitsDir: nativeLogitsDir, - pplCorporaDir: pplCorporaDir); + pplCorporaDir: pplCorporaDir, + corpusOverrides: corpusOverrides); foreach (var artifact in manifest.Artifacts) { @@ -265,41 +259,54 @@ await EnsureCloneNativeBenchmarkArtifactsReadyAsync( AnsiConsole.Write(new Rule($"[yellow]Clone Artifact: {Markup.Escape(artifact.FileName)}[/]") { Justification = Justify.Left }); - if (TryReuseExistingCloneArtifactAndBenchmark(outputFile, artifact, benchmarkCache, out var cachedRecord)) - { - AnsiConsole.MarkupLine($"[green]Reused existing clone artifact + benchmark:[/] {Markup.Escape(outputFile)}"); - records.Add(cachedRecord); - continue; - } - - bool artifactExists = Config.ReuseExistingFinalArtifacts && File.Exists(outputFile) && new FileInfo(outputFile).Length > 0; + string artifactBenchDir = Path.Combine(cloneBenchmarkRootDir, Path.GetFileNameWithoutExtension(artifact.FileName)); + string proofPath = Path.Combine(artifactBenchDir, "clone-artifact-evidence.json"); + string requestHash = await CloneArtifactEvidenceService.CreateRequestHashAsync( + artifact.TensorTypes, baseQuantName, artifactAllowMissingManifestTensors, + artifactMissingManifestBaseQuantName, MagicQuant.Runtime.RunCancellation.Token); + bool artifactExists = Config.ReuseExistingFinalArtifacts && await CloneArtifactEvidenceService.CanReuseAsync( + outputFile, proofPath, requestHash, MagicQuant.Runtime.RunCancellation.Token); + double buildSeconds = 0; if (artifactExists) { - AnsiConsole.MarkupLine($"[green]Reused existing clone GGUF:[/] {Markup.Escape(outputFile)} [grey](benchmark cache missing/stale; rebenchmarking only)[/]"); + AnsiConsole.MarkupLine($"[green]Verified existing clone GGUF build identity:[/] {Markup.Escape(outputFile)}"); } else { + var buildTimer = Stopwatch.StartNew(); var cloneBuildResult = await cloneBuildService.BuildAsync( tensorTypes: artifact.TensorTypes, outputPath: outputFile, baseQuantName: baseQuantName, allowMissingManifestTensors: artifactAllowMissingManifestTensors, missingManifestBaseQuantName: artifactMissingManifestBaseQuantName, - forceRebuild: true); + forceRebuild: true, + ct: MagicQuant.Runtime.RunCancellation.Token); cloneBuildResults[artifact.FileName] = cloneBuildResult; + buildSeconds = buildTimer.Elapsed.TotalSeconds; + string completedRequestHash = await CloneArtifactEvidenceService.CreateRequestHashAsync( + artifact.TensorTypes, baseQuantName, artifactAllowMissingManifestTensors, + artifactMissingManifestBaseQuantName, MagicQuant.Runtime.RunCancellation.Token); + if (!string.Equals(requestHash, completedRequestHash, StringComparison.Ordinal)) + throw new InvalidOperationException("Clone build inputs changed during quantization; no reusable build proof was recorded."); + await CloneArtifactEvidenceService.WriteAsync(outputFile, proofPath, requestHash, + MagicQuant.Runtime.RunCancellation.Token); } var benchmarkBaseline = ResolveCloneBenchmarkBaseline(baseQuantName, artifact.QuantFamily); var quantForBenchmark = HybridQuant.CreatePureBaseline(benchmarkBaseline); - bool benchmarkRequiresKld = benchmarkBaseline.UniqueId != BaselineQuants.NativeSourceUniqueId; + var evaluationTimer = Stopwatch.StartNew(); var bench = await benchmarkService.RunAllBenchmarksAsync( quantConfig: quantForBenchmark, modelPath: outputFile, - benchDir: Path.Combine(cloneBenchmarkRootDir, Path.GetFileNameWithoutExtension(artifact.FileName)), - klLogitsDir: benchmarkRequiresKld ? nativeLogitsDir : null, - domainsOverride: CloneBenchmarkDomains); + benchDir: artifactBenchDir, + // The carrier name does not identify the actual exact-map artifact. + // Even a float-carrier clone must be compared with the native logits. + klLogitsDir: nativeLogitsDir, + domainsOverride: CloneBenchmarkDomains, + corpusOverrides: corpusOverrides); var general = bench.Perplexity.TryGetValue("general", out var ppl) ? ppl : null; @@ -310,7 +317,11 @@ await EnsureCloneNativeBenchmarkArtifactsReadyAsync( ActualSizeBytes = File.Exists(outputFile) ? (ulong)new FileInfo(outputFile).Length : 0UL, Kld = general?.Kld, Ppl = general?.Ppl, - PplDeltaPercent = null + PplDeltaPercent = null, + ArtifactSha256 = bench.Evidence?.ModelSha256, + EvidenceIdentityHash = bench.Evidence?.IdentityHash, + BuildSeconds = buildSeconds, + EvaluationSeconds = evaluationTimer.Elapsed.TotalSeconds }); } } @@ -357,12 +368,20 @@ private static async Task EnsureCloneNativeBenchmarkArtifactsReadyAsync( string nativeModelPath, string nativeBenchDir, string nativeLogitsDir, - string pplCorporaDir) + string pplCorporaDir, + IReadOnlyDictionary? corpusOverrides = null) { + // RunAll validates content identity and reference sidecars before any reuse. + // A directory containing old logs is not sufficient proof of compatibility. + await benchmarkService.RunAllBenchmarksAsync( + quantConfig: nativeModelQuant, modelPath: nativeModelPath, benchDir: nativeBenchDir, + klLogitsDir: nativeLogitsDir, saveLogits: true, domainsOverride: CloneBenchmarkDomains, + corpusOverrides: corpusOverrides); var status = ValidateCloneNativeBenchmarkEnvironment( nativeBenchDir: nativeBenchDir, nativeLogitsDir: nativeLogitsDir, - pplCorporaDir: pplCorporaDir); + pplCorporaDir: pplCorporaDir, + corpusOverrides: corpusOverrides); if (status.IsValid) { @@ -379,12 +398,14 @@ await ForceRegenerateCloneNativeBenchmarkArtifactsAsync( nativeModelQuant: nativeModelQuant, nativeModelPath: nativeModelPath, nativeBenchDir: nativeBenchDir, - nativeLogitsDir: nativeLogitsDir); + nativeLogitsDir: nativeLogitsDir, + corpusOverrides: corpusOverrides); status = ValidateCloneNativeBenchmarkEnvironment( nativeBenchDir: nativeBenchDir, nativeLogitsDir: nativeLogitsDir, - pplCorporaDir: pplCorporaDir); + pplCorporaDir: pplCorporaDir, + corpusOverrides: corpusOverrides); if (!status.IsValid) { @@ -407,13 +428,16 @@ private static async Task ForceRegenerateCloneNativeBenchmarkArtifactsAsync( HybridQuant nativeModelQuant, string nativeModelPath, string nativeBenchDir, - string nativeLogitsDir) + string nativeLogitsDir, + IReadOnlyDictionary? corpusOverrides = null) { if (Directory.Exists(nativeBenchDir)) { AnsiConsole.MarkupLine( $"[grey]Clearing incomplete/stale clone native benchmark directory:[/] {Markup.Escape(nativeBenchDir)}"); + await BenchmarkEvidenceService.ArchiveForNativeRepairAsync( + nativeBenchDir, MagicQuant.Runtime.RunCancellation.Token); Directory.Delete(nativeBenchDir, recursive: true); } @@ -432,7 +456,8 @@ await benchmarkService.RunAllBenchmarksAsync( benchDir: nativeBenchDir, klLogitsDir: nativeLogitsDir, saveLogits: true, - domainsOverride: CloneBenchmarkDomains); + domainsOverride: CloneBenchmarkDomains, + corpusOverrides: corpusOverrides); } finally { @@ -443,7 +468,8 @@ await benchmarkService.RunAllBenchmarksAsync( private static CloneNativeBenchmarkEnvironmentStatus ValidateCloneNativeBenchmarkEnvironment( string nativeBenchDir, string nativeLogitsDir, - string pplCorporaDir) + string pplCorporaDir, + IReadOnlyDictionary? corpusOverrides = null) { var issues = new List(); @@ -457,12 +483,13 @@ private static CloneNativeBenchmarkEnvironmentStatus ValidateCloneNativeBenchmar else if (!Directory.Exists(nativeLogitsDir)) issues.Add($"Clone native KLD logits directory does not exist: {nativeLogitsDir}"); - if (string.IsNullOrWhiteSpace(pplCorporaDir)) - issues.Add("Clone _ppl_corpora directory path is null/empty."); - else if (!Directory.Exists(pplCorporaDir)) - issues.Add($"Clone _ppl_corpora directory does not exist: {pplCorporaDir}"); - else if (!Directory.EnumerateFiles(pplCorporaDir, "*", SearchOption.AllDirectories).Any()) - issues.Add($"Clone _ppl_corpora directory exists but contains no files: {pplCorporaDir}"); + foreach (var domain in CloneBenchmarkDomains) + { + string corpus = corpusOverrides?.GetValueOrDefault(domain) + ?? Path.Combine(pplCorporaDir, $"ppl_corpus_{domain}.txt"); + if (!File.Exists(corpus) || new FileInfo(corpus).Length == 0) + issues.Add($"Missing or empty clone corpus for '{domain}': {corpus}"); + } foreach (var domain in CloneBenchmarkDomains.OrderBy(x => x, StringComparer.Ordinal)) { @@ -624,92 +651,6 @@ private static bool IsCloneQ8ReferenceRecord(CloneArtifactBuildRecord record) return false; } - private static bool TryLoadFullyReusableCloneRecords( - string outputDirectory, - MagicQuantCloneManifest manifest, - IReadOnlyDictionary benchmarkCache, - out List records) - { - records = new List(); - - if (!Config.ReuseExistingFinalArtifacts || benchmarkCache.Count == 0) - return false; - - foreach (var artifact in manifest.Artifacts) - { - string outputFile = Path.Combine(outputDirectory, artifact.FileName); - if (!TryReuseExistingCloneArtifactAndBenchmark(outputFile, artifact, benchmarkCache, out var record)) - { - records.Clear(); - return false; - } - - records.Add(record); - } - - return records.Count == manifest.Artifacts.Count; - } - - private static bool TryReuseExistingCloneArtifactAndBenchmark( - string outputFile, - MagicQuantCloneArtifact artifact, - IReadOnlyDictionary benchmarkCache, - out CloneArtifactBuildRecord record) - { - record = default!; - - if (!Config.ReuseExistingFinalArtifacts) - return false; - - if (!File.Exists(outputFile)) - return false; - - var info = new FileInfo(outputFile); - if (info.Length <= 0) - return false; - - if (!benchmarkCache.TryGetValue(artifact.FileName, out var cached)) - return false; - - if (cached.SizeBytes != (ulong)info.Length) - return false; - - record = new CloneArtifactBuildRecord - { - ManifestArtifact = artifact, - OutputPath = outputFile, - ActualSizeBytes = cached.SizeBytes, - Kld = cached.Kld, - Ppl = cached.Ppl, - PplDeltaPercent = cached.PplDeltaPercent - }; - - return true; - } - - private static Dictionary LoadReusableCloneBenchmarkRows(string outputDirectory) - { - string path = MagicQuantManifestPathService.GetManifestFilePath(outputDirectory, MagicQuantManifestPathService.CloneBenchmarksFileName); - if (!File.Exists(path)) - return new Dictionary(StringComparer.OrdinalIgnoreCase); - - try - { - var rows = JsonSerializer.Deserialize>(File.ReadAllText(path), JsonOptions) - ?? new List(); - - return rows - .Where(x => !string.IsNullOrWhiteSpace(x.FileName) && x.SizeBytes > 0) - .GroupBy(x => x.FileName, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); - } - catch (Exception ex) - { - AnsiConsole.MarkupLine($"[yellow]Existing clone benchmark summary could not be reused:[/] {Markup.Escape(ex.Message)}"); - return new Dictionary(StringComparer.OrdinalIgnoreCase); - } - } - private static Dictionary LoadCloneArtifactPolicies(string manifestPath) { var policies = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -960,7 +901,11 @@ private static async Task WriteCloneBenchmarkSummaryAsync(string outputDirectory SizeGiB = x.ActualSizeBytes / 1024d / 1024d / 1024d, SourceKld = x.ManifestArtifact.SourceKld, SourcePpl = x.ManifestArtifact.SourcePpl, - SourceSizeBytes = x.ManifestArtifact.SourceSizeBytes + SourceSizeBytes = x.ManifestArtifact.SourceSizeBytes, + ArtifactSha256 = x.ArtifactSha256, + EvidenceIdentityHash = x.EvidenceIdentityHash, + BuildSeconds = x.BuildSeconds, + EvaluationSeconds = x.EvaluationSeconds }) .ToList(); @@ -1069,6 +1014,7 @@ private static void ShowHelp() AnsiConsole.MarkupLine($" --source-repo Hugging Face repo containing {MagicQuantManifestPathService.RelativeManifestPath(MagicQuantManifestPathService.CloneConfigsFileName)} or legacy root {MagicQuantManifestPathService.CloneConfigsFileName}"); AnsiConsole.MarkupLine(" --source-json Local or http(s) path to magicquant.clone-configs.json"); AnsiConsole.MarkupLine(" --use-imatrix Use configured/provided imatrix for the cloned model"); + AnsiConsole.MarkupLine(" --benchmark-corpus Frozen General text corpus; both native references and candidates use these exact bytes"); AnsiConsole.MarkupLine(" --reuse-existing-final-artifacts Reuse matching existing GGUFs and matching clone benchmark JSON rows"); AnsiConsole.MarkupLine(" --allow-missing-manifest-tensors Allow clone manifests that are strict subsets of the current model tensor list; extra source tensors receive no explicit --tensor-type override and fall through to base quantization"); AnsiConsole.MarkupLine(" --missing-manifest-base-quant Allow strict-subset clone manifests and use this llama.cpp base quant for tensors absent from the manifest, e.g. Q8_0"); @@ -1099,5 +1045,9 @@ private sealed class CloneBenchmarkCacheRow public double? SourceKld { get; set; } public double? SourcePpl { get; set; } public ulong? SourceSizeBytes { get; set; } + public string? ArtifactSha256 { get; set; } + public string? EvidenceIdentityHash { get; set; } + public double BuildSeconds { get; set; } + public double EvaluationSeconds { get; set; } } } diff --git a/src/MagicQuant/Commands/InitializeLlamaCpp.cs b/src/MagicQuant/Commands/InitializeLlamaCpp.cs index d8602d2..b825ae5 100644 --- a/src/MagicQuant/Commands/InitializeLlamaCpp.cs +++ b/src/MagicQuant/Commands/InitializeLlamaCpp.cs @@ -156,12 +156,12 @@ async Task EnsurePackage(string name, string installCmd, Dictionary= 12.0) { @@ -234,23 +234,30 @@ await EnsurePackage("llama-cpp-python", llamaEnv); AnsiConsole.MarkupLine("[bold green]Initialization Complete![/]"); - AnsiConsole.MarkupLine($"Llama Binaries: [grey]{builder.GetLlamaBinPath()}[/]"); + AnsiConsole.MarkupLine($"Llama Binaries: [grey]{Markup.Escape(builder.GetLlamaBinPath())}[/]"); } private static SystemInfo DetectAndCacheSystemInfo() { var sysInfo = HardwareHelper.GetSystemInfo(); Cache.SysInfo = sysInfo; - - AnsiConsole.Write(new Rule("[yellow]System Detection[/]") { Justification = Justify.Left }); - AnsiConsole.MarkupLine( - $"Detected GPU: [green]{sysInfo.GpuInfo.FirstOrDefault()?.GpuVendor}[/] " + - $"([blue]{sysInfo.GpuInfo.FirstOrDefault()?.GpuName}[/] - {sysInfo.GpuInfo.Sum(x => x.VramGb):F1} GB)"); - AnsiConsole.MarkupLine($"Detected RAM: [blue]{sysInfo.RamGb:F1} GB[/]"); - + WriteSystemInfo(AnsiConsole.Console, sysInfo); return sysInfo; } + internal static void WriteSystemInfo(IAnsiConsole console, SystemInfo sysInfo) + { + var gpu = sysInfo.GpuInfo.FirstOrDefault(); + string vendor = Markup.Escape(gpu?.GpuVendor.ToString() ?? string.Empty); + string name = Markup.Escape(gpu?.GpuName ?? string.Empty); + string vram = Markup.Escape(sysInfo.GpuInfo.Sum(x => x.VramGb).ToString("F1")); + string ram = Markup.Escape(sysInfo.RamGb.ToString("F1")); + + console.Write(new Rule("[yellow]System Detection[/]") { Justification = Justify.Left }); + console.MarkupLine($"Detected GPU: [green]{vendor}[/] ([blue]{name}[/] - {vram} GB)"); + console.MarkupLine($"Detected RAM: [blue]{ram} GB[/]"); + } + // --- Helpers --- private static async Task RunSimpleProcess(string exe, string args) diff --git a/src/MagicQuant/Commands/QuantizationPipeline.cs b/src/MagicQuant/Commands/QuantizationPipeline.cs index 8f97f6e..713933e 100644 --- a/src/MagicQuant/Commands/QuantizationPipeline.cs +++ b/src/MagicQuant/Commands/QuantizationPipeline.cs @@ -568,6 +568,7 @@ private static async Task ForceRegenerateNativeBenchmarkArtifactsAsync( { if (Directory.Exists(baseBenchDir)) { + await BenchmarkEvidenceService.ArchiveForNativeRepairAsync(baseBenchDir, MagicQuant.Runtime.RunCancellation.Token); AnsiConsole.MarkupLine( $"[grey]Clearing incomplete/stale native benchmark directory:[/] {Markup.Escape(baseBenchDir)}"); @@ -581,14 +582,8 @@ private static async Task ForceRegenerateNativeBenchmarkArtifactsAsync( try { - // This is intentional. - // - // If persisted native BF16 benchmark rows already exist in SQLite, the normal - // BenchmarkService path may return DB truth without actually running llama-perplexity, - // which means missing KLD logits would stay missing forever. - // - // Transient mode forces this artifact-repair pass to rely on disk execution instead - // of DB benchmark truth. The native tensor truth is learned separately below. + // Repair native files without writing learning truth until all required + // domains/references have completed and the normal hydration pass verifies them. Cache.SuppressBenchmarkPersistence = true; await benchmarkService.RunAllBenchmarksAsync( diff --git a/src/MagicQuant/Commands/ValidatePredictions.cs b/src/MagicQuant/Commands/ValidatePredictions.cs index eead297..7cc32bb 100644 --- a/src/MagicQuant/Commands/ValidatePredictions.cs +++ b/src/MagicQuant/Commands/ValidatePredictions.cs @@ -1,9 +1,8 @@ using MagicQuant.Helpers; +using System.Text.Json; using MagicQuant.Models; using MagicQuant.Services; -using Microsoft.EntityFrameworkCore; using MQ.DB; -using MQ.DB.Data; using Spectre.Console; namespace MagicQuant.Commands; @@ -45,7 +44,7 @@ public async Task Run(List args) JsonHelper.DetectAndSetTorchType(Cache.ModelDirectory); MagicQuant.Runtime.RunCancellation.Token.ThrowIfCancellationRequested(); - await ResolveArchitectureFamilyFromConfigAsync(); + await PredictionDiagnosticContextService.InitializeAsync(MagicQuant.Runtime.RunCancellation.Token); ApplyOptionalImatrixContext(args); @@ -58,31 +57,20 @@ public async Task Run(List args) var validator = new PredictionValidationService(repository, prediction); MagicQuant.Runtime.RunCancellation.Token.ThrowIfCancellationRequested(); - await validator.ExportAsync(outputDir); + using var evidenceRead = BenchmarkEvidenceService.BeginRecordedDiagnosticRead(); + await validator.ExportAsync(outputDir, MagicQuant.Runtime.RunCancellation.Token, ReadHoldoutKeys(args)); } - private static async Task ResolveArchitectureFamilyFromConfigAsync() + internal static IReadOnlyCollection? ReadHoldoutKeys(IReadOnlyList args) { - Cache.CurrentArchitectureFamilyId = null; - - if (string.IsNullOrWhiteSpace(Cache.CurrentArchitectureFamilyName)) - return; - - string normalized = Cache.CurrentArchitectureFamilyNormalizedName; - - await using var db = new MagicQuantContext(); - var family = await db.ArchitectureFamilies - .AsNoTracking() - .FirstOrDefaultAsync(x => x.NormalizedName == normalized); - - if (family == null) - { - AnsiConsole.MarkupLine($"[yellow]Warning:[/] Architecture family '{Markup.Escape(Cache.CurrentArchitectureFamilyName)}' was configured but not found in SQLite. Validation will use the raw model hash scope."); - return; - } - - Cache.CurrentArchitectureFamilyId = family.Id; - AnsiConsole.MarkupLine($"[green]Architecture family scope:[/] {Markup.Escape(family.DisplayName)} (Id={family.Id})"); + string? path = args.FirstOrDefault(a => string.Equals(a.Name, "prediction-holdout-keys", StringComparison.OrdinalIgnoreCase))?.Value; + if (string.IsNullOrWhiteSpace(path)) + return null; + + var keys = JsonSerializer.Deserialize>(File.ReadAllText(Path.GetFullPath(path))); + if (keys == null || keys.Count == 0 || keys.Any(string.IsNullOrWhiteSpace)) + throw new InvalidOperationException("--prediction-holdout-keys requires a nonempty JSON array of existing configuration-key strings."); + return keys.Distinct(StringComparer.Ordinal).ToList(); } private static void ApplyOptionalImatrixContext(IReadOnlyList args) @@ -133,17 +121,20 @@ private static string ResolveOutputDirectory(IReadOnlyList args) private static void ShowHelp() { AnsiConsole.MarkupLine("[bold]validate-predictions[/]"); - AnsiConsole.MarkupLine("Validates rank-safe isolation KLD predictions against existing SQLite category=General benchmark truth."); + AnsiConsole.MarkupLine("Exports in-sample reconstruction diagnostics for existing SQLite General truth. This is not production discovery replay."); AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("[yellow]Required:[/]"); AnsiConsole.MarkupLine(" --model-dir HuggingFace source model directory, or set paths.model_dir in YAML"); AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("[yellow]Optional:[/]"); - AnsiConsole.MarkupLine(" --architecture-family Uses configured family scope if present in SQLite"); + AnsiConsole.MarkupLine(" --architecture-family Must match the model's existing family; uses its matching YAML profile"); AnsiConsole.MarkupLine(" --imatrix-path Hash this imatrix and validate that exact bucket"); AnsiConsole.MarkupLine(" --imatrix-identity-hash Validate an already-known imatrix bucket"); AnsiConsole.MarkupLine(" --output-dir Report output directory"); + AnsiConsole.MarkupLine(" --prediction-holdout-keys Exclude listed hybrid config keys from coefficient fitting; score only that measured subset"); AnsiConsole.WriteLine(); - AnsiConsole.MarkupLine("[grey]Outputs prediction_validation_general.csv and prediction_validation_general.md.[/]"); + AnsiConsole.MarkupLine("[grey]Outputs prediction_validation_general.csv, .md and .json, including raw/projected scores and all requested rows.[/]"); + AnsiConsole.MarkupLine("[grey]Holdout mode cannot exclude pure/base-only/isolation feature inputs. It is a coefficient-holdout diagnostic, with subset PAVA and no anomaly or eligibility replay.[/]"); + AnsiConsole.MarkupLine("[grey]Requires existing native GGUF, campaign evidence and matching YAML tensor rules. Restores persisted custom IDs and actual active groups without downloading baselines or running benchmarks.[/]"); } } diff --git a/src/MagicQuant/Config.cs b/src/MagicQuant/Config.cs index b815286..7acc86c 100644 --- a/src/MagicQuant/Config.cs +++ b/src/MagicQuant/Config.cs @@ -48,6 +48,8 @@ public static void SetResolvedCustomBaselines(IEnumerable Math.Max(1, Current.CandidateSelection.MaxCandidatesPerInteriorWindow); + public static bool SelectionCompleteInteriorCoverage => Current.CandidateSelection.CompleteInteriorCoverage; + public static int SelectionMaxFallbackAttemptsPerAnchor => Math.Max(1, Current.CandidateSelection.MaxFallbackAttemptsPerAnchor); diff --git a/src/MagicQuant/Configuration/CliOptionValidator.cs b/src/MagicQuant/Configuration/CliOptionValidator.cs index 9a3fbd3..9b56b71 100644 --- a/src/MagicQuant/Configuration/CliOptionValidator.cs +++ b/src/MagicQuant/Configuration/CliOptionValidator.cs @@ -40,6 +40,7 @@ public static class CliOptionValidator private static readonly HashSet Values = new(StringComparer.OrdinalIgnoreCase) { "architecture-family", + "benchmark-corpus", "clone-json", "clone-repo", "config", @@ -62,6 +63,7 @@ public static class CliOptionValidator "prediction-bit-stress-threshold-candidates", "prediction-default-bit-stress-threshold", "prediction-minimum-fit-rows", + "prediction-holdout-keys", "selection-diversify-validation-candidates", "selection-diversity-low-bit-only", "selection-diversity-scan-max-candidates", diff --git a/src/MagicQuant/Configuration/MagicQuantYamlConfig.cs b/src/MagicQuant/Configuration/MagicQuantYamlConfig.cs index a8c93fd..7389d35 100644 --- a/src/MagicQuant/Configuration/MagicQuantYamlConfig.cs +++ b/src/MagicQuant/Configuration/MagicQuantYamlConfig.cs @@ -70,10 +70,25 @@ public sealed class RuntimeIsolationPruningConfig public double BadTradePplMultiplier { get; set; } = 3.5d; public double FloatingPointEpsilon { get; set; } = 1e-8d; public double MinimumMeaningfulBaseOnlyReductionRatio { get; set; } = 0.01d; + + /// + /// Opt-in contextual tests of isolated size/KLD Pareto improvements removed by + /// the bad-trade heuristic. Does not unban any global Cartesian choices. + /// + public bool KldSizeRescueEnabled { get; set; } = false; + public int KldSizeRescueMaxCandidatesPerGroup { get; set; } = 1; + public int KldSizeRescueMaxContextProbesPerRun { get; set; } = 3; } public sealed class RuntimePredictionConfig { + /// + /// Stream the complete materialized candidate population and a fingerprinted + /// fit/context manifest for offline experiments. Scores are before anomaly + /// rules; this does not change prediction or selection behavior. + /// + public bool ExportCandidateScores { get; set; } = false; + /// /// Legacy emergency ceiling. Keep at 0 for the rank-safe isolation predictor. /// @@ -134,6 +149,12 @@ public sealed class RuntimeCandidateSelectionConfig 0.35d ]; + /// + /// Extend the last ordinary interior window to its larger anchor. Keeps the + /// same number of windows and the same configured attempts per window. + /// + public bool CompleteInteriorCoverage { get; set; } = false; + public int MaxCandidatesPerInteriorWindow { get; set; } = 1; public int MaxFallbackAttemptsPerAnchor { get; set; } = 5; diff --git a/src/MagicQuant/Configuration/MagicQuantYamlLoader.cs b/src/MagicQuant/Configuration/MagicQuantYamlLoader.cs index 83e96c9..a156a2c 100644 --- a/src/MagicQuant/Configuration/MagicQuantYamlLoader.cs +++ b/src/MagicQuant/Configuration/MagicQuantYamlLoader.cs @@ -153,6 +153,9 @@ private static void NormalizeAndApply(MagicQuantYamlConfig config) config.CandidateSelection.DiversityScanMinCandidates = Math.Max(1, config.CandidateSelection.DiversityScanMinCandidates); config.CandidateSelection.DiversityScanMaxCandidates = Math.Max(config.CandidateSelection.DiversityScanMinCandidates, config.CandidateSelection.DiversityScanMaxCandidates); + config.IsolationPruning.KldSizeRescueMaxCandidatesPerGroup = Math.Clamp(config.IsolationPruning.KldSizeRescueMaxCandidatesPerGroup, 0, 16); + config.IsolationPruning.KldSizeRescueMaxContextProbesPerRun = Math.Clamp(config.IsolationPruning.KldSizeRescueMaxContextProbesPerRun, 0, 128); + config.AnomalyDetection ??= new RuntimeAnomalyDetectionConfig(); config.SynergyDetection ??= new RuntimeSynergyDetectionConfig(); NormalizeSynergyDetection(config); diff --git a/src/MagicQuant/Models/HybridFinalizationModels.cs b/src/MagicQuant/Models/HybridFinalizationModels.cs index 67276d8..8c50485 100644 --- a/src/MagicQuant/Models/HybridFinalizationModels.cs +++ b/src/MagicQuant/Models/HybridFinalizationModels.cs @@ -137,6 +137,7 @@ public void AddRemoval(string reason, long count) public sealed class BenchmarkSnapshotRecord { + public string? EvidenceIdentityHash { get; init; } public TensorConfig Config { get; init; } public HybridQuant Quant { get; init; } = default!; public string DisplayName { get; init; } = string.Empty; diff --git a/src/MagicQuant/Models/PredictionSelectionModels.cs b/src/MagicQuant/Models/PredictionSelectionModels.cs index 494063e..2d9fad6 100644 --- a/src/MagicQuant/Models/PredictionSelectionModels.cs +++ b/src/MagicQuant/Models/PredictionSelectionModels.cs @@ -5,11 +5,14 @@ namespace MagicQuant.Models; public sealed class RankSafePredictionRow { public TensorConfig Config { get; init; } + // Synthetic coordinate used by the predictor. Keep the real artifact key separate. + public TensorConfig PredictionConfig { get; init; } public HybridQuant Quant { get; init; } = default!; public ulong PredictedSizeBytes { get; set; } public bool IsSizePredictable { get; set; } = true; public double AdditiveKld { get; set; } public double InteractionKld { get; set; } + public double ProjectedKld { get; set; } public double PredictedKld { get; set; } public double PredictionConfidence { get; set; } = 1.0d; public double PredictedPpl { get; set; } @@ -27,6 +30,7 @@ public sealed class RankSafePredictionRow public int? ActualRank { get; set; } public ulong? PredictedRank { get; set; } public double AnomalyAdjustmentKld { get; set; } + public double ProjectionAdjustmentKld => ProjectedKld - InteractionKld; public double AbsoluteKldError => double.IsNaN(ActualKld) ? double.NaN : Math.Abs(PredictedKld - ActualKld); @@ -39,6 +43,7 @@ public sealed class RankSafePredictionSet { public IReadOnlyList Rows { get; init; } = Array.Empty(); public RankSafePredictionFit Fit { get; init; } = new(); + public IReadOnlyList FitTrainingConfigKeys { get; init; } = Array.Empty(); public IReadOnlyList Notes { get; init; } = Array.Empty(); public IReadOnlyList PredictableRows => @@ -152,11 +157,19 @@ public sealed class RankSafeValidationSummary { public int RowCount { get; init; } public int PredictableCount { get; init; } - public double Mae { get; init; } - public double Rmse { get; init; } - public double MaxAbsoluteError { get; init; } - public double MeanSignedError { get; init; } - public double PairwiseAccuracyPercent { get; init; } + public int UnpredictableCount => RowCount - PredictableCount; + public int SizePredictableCount { get; init; } + public double? Mae { get; init; } + public double? Rmse { get; init; } + public double? MaxAbsoluteError { get; init; } + public double? MeanSignedError { get; init; } + // Among actual-distinct pairs, predicted ties earn half credit. Null means + // no actual-distinct pairs, not perfect discrimination. + public double? PairwiseAccuracyPercent { get; init; } + public double? KendallTauB { get; init; } + public long OrderableActualPairs { get; init; } + public long TiedActualPairs { get; init; } + public long TiedBothPairs { get; init; } public long ConcordantPairs { get; init; } public long DiscordantPairs { get; init; } public long TiedPredictedPairs { get; init; } @@ -173,6 +186,8 @@ public sealed class PredictionValidationExportResult public RankSafeValidationSummary Summary { get; init; } = new(); public string CsvPath { get; init; } = string.Empty; public string MarkdownPath { get; init; } = string.Empty; + public string JsonPath { get; init; } = string.Empty; + public string Mode { get; init; } = "in_sample_reconstruction"; public IReadOnlyList Rows { get; init; } = Array.Empty(); } @@ -185,6 +200,8 @@ public sealed class PhaseValidationResult public sealed class PredictionGuidedSelectionResult { public IReadOnlyList Survivors { get; init; } = Array.Empty(); + public IReadOnlyList MeasuredSnapshots { get; init; } = Array.Empty(); + public IReadOnlyList UnspacedFrontier { get; init; } = Array.Empty(); public IReadOnlyList Eliminations { get; init; } = Array.Empty(); public IReadOnlyList ValidationFailures { get; init; } = Array.Empty(); -} \ No newline at end of file +} diff --git a/src/MagicQuant/Models/RepositoryCloneModels.cs b/src/MagicQuant/Models/RepositoryCloneModels.cs index c2dd59e..9db418b 100644 --- a/src/MagicQuant/Models/RepositoryCloneModels.cs +++ b/src/MagicQuant/Models/RepositoryCloneModels.cs @@ -49,4 +49,8 @@ public sealed class CloneArtifactBuildRecord public double? Kld { get; set; } public double? Ppl { get; set; } public double? PplDeltaPercent { get; set; } + public string? ArtifactSha256 { get; set; } + public string? EvidenceIdentityHash { get; set; } + public double BuildSeconds { get; set; } + public double EvaluationSeconds { get; set; } } diff --git a/src/MagicQuant/Services/BenchmarkEvidenceService.cs b/src/MagicQuant/Services/BenchmarkEvidenceService.cs new file mode 100644 index 0000000..f87bda2 --- /dev/null +++ b/src/MagicQuant/Services/BenchmarkEvidenceService.cs @@ -0,0 +1,433 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using MagicQuant.Helpers; +using Microsoft.EntityFrameworkCore; +using MQ.DB; +using MQ.DB.Data; +using MQ.DB.Models; +using MQ.DB.Models.DbModels; + +namespace MagicQuant.Services; + +/// +/// Fail-closed, content-based benchmark reuse. File hashes are memoized only in this process, +/// by path/length/write/creation time, after reading the complete contents once. Artifacts +/// must not be modified in place while a campaign is running. +/// +public static class BenchmarkEvidenceService +{ + public const int SchemaVersion = 1; + public const int DefaultTokenTarget = 32768; + // Bump when tensor resolution, quantizer arguments or materialization semantics change. + // Predictor/CLI-only rebuilds must not invalidate expensive inference evidence. + private const string QuantizationRecipeContract = "mq-quantization-recipe-v1"; + private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true }; + private static readonly ConcurrentDictionary>> FileHashes = new(StringComparer.Ordinal); + private static readonly AsyncLocal RecordedDiagnosticRead = new(); + + /// Explicit offline diagnostics may select an already measured imatrix bucket + /// by hash. Live search still checks the active quantizer's imatrix application policy. + public static IDisposable BeginRecordedDiagnosticRead() + { + bool previous = RecordedDiagnosticRead.Value; + RecordedDiagnosticRead.Value = true; + return new RecordedReadScope(() => RecordedDiagnosticRead.Value = previous); + } + + private sealed class RecordedReadScope(Action restore) : IDisposable + { + private bool _disposed; + public void Dispose() + { + if (_disposed) return; + _disposed = true; + restore(); + } + } + + public static async Task HashFileAsync(string path, CancellationToken ct = default) + { + string fullPath = Path.GetFullPath(path); + var before = new FileInfo(fullPath); + if (!before.Exists || before.Length == 0) + throw new FileNotFoundException("Evidence input is absent or empty.", fullPath); + string stamp = $"{fullPath}|{before.Length}|{before.LastWriteTimeUtc.Ticks}|{before.CreationTimeUtc.Ticks}"; + var task = FileHashes.GetOrAdd(stamp, _ => new Lazy>(async () => + { + await using var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, + 1024 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan); + var hash = await SHA256.HashDataAsync(stream, ct); + var after = new FileInfo(fullPath); + if (!after.Exists || after.Length != before.Length || after.LastWriteTimeUtc != before.LastWriteTimeUtc) + throw new IOException($"Evidence input changed while hashing: {fullPath}"); + return Convert.ToHexString(hash).ToLowerInvariant(); + })).Value; + try { return await task.WaitAsync(ct); } + catch { FileHashes.TryRemove(stamp, out _); throw; } + } + + internal static string HashJson(T value) => Convert.ToHexString( + SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value)))).ToLowerInvariant(); + + public static string ComputeIdentityHash(BenchmarkEvidenceManifest manifest) => HashJson(new + { + manifest.SchemaVersion, manifest.RecipeHash, manifest.NativeSourceSha256, + manifest.EvaluatorHash, manifest.ExecutionPolicyHash, manifest.ModelSha256, manifest.TokenTarget, manifest.SaveLogits, manifest.CompareLogits, + manifest.QuantizerThreadCount, manifest.ScratchWriterCapacity, manifest.ImatrixApplied, + manifest.AllowIndependentGpuTopology, manifest.EquivalentSourceEvidenceHash, + Domains = manifest.Domains.OrderBy(x => x.Key, StringComparer.Ordinal).Select(x => new + { + Domain = x.Key, x.Value.CorpusSha256, x.Value.ReferenceDefinitionHash, x.Value.ReferenceLogitsSha256 + }).ToArray() + }); + + /// Subset domains may reuse a completed superset; an output digest is checked whenever + /// the output exists. Missing identity, changed budget or changed contents always miss. + public static bool IsCompatible(BenchmarkEvidenceManifest? stored, BenchmarkEvidenceManifest expected) + { + if (stored == null || stored.Domains == null || stored.Domains.Values.Any(x => x == null) || stored.SchemaVersion != SchemaVersion || + !IsSha256(stored.ModelSha256) || !IsSha256(stored.RecipeHash) || + stored.IdentityHash != ComputeIdentityHash(stored) || + stored.RecipeHash != expected.RecipeHash || stored.NativeSourceSha256 != expected.NativeSourceSha256 || + stored.EvaluatorHash != expected.EvaluatorHash || stored.TokenTarget != expected.TokenTarget || + stored.ExecutionPolicyHash != expected.ExecutionPolicyHash || + stored.SaveLogits != expected.SaveLogits || + stored.CompareLogits != expected.CompareLogits || + stored.AllowIndependentGpuTopology != expected.AllowIndependentGpuTopology || + (!string.IsNullOrEmpty(expected.ModelSha256) && stored.ModelSha256 != expected.ModelSha256)) + return false; + return expected.Domains.All(x => stored.Domains.TryGetValue(x.Key, out var actual) && + actual.CorpusSha256 == x.Value.CorpusSha256 && + actual.ReferenceDefinitionHash == x.Value.ReferenceDefinitionHash && + actual.ReferenceLogitsSha256 == x.Value.ReferenceLogitsSha256); + } + + public static bool HasValidMetrics(BenchmarkResult result, IEnumerable domains, bool requireKld) => + result.ModelSizeBytes > 0 && result.Perplexity != null && domains.All(domain => result.Perplexity.TryGetValue(domain, out var p) && p != null && + double.IsFinite(p.Ppl) && p.Ppl > 0 && double.IsFinite(p.PplError) && p.PplError >= 0 && + (!requireKld || p.Kld is { } kld && double.IsFinite(kld) && kld >= 0)); + + public static bool RequiresComparison(HybridQuant quant, string? logitsDir, bool saveLogits) + => !saveLogits && (quant.BaseQuant.UniqueId != BaselineQuants.NativeSourceUniqueId || + quant.Tensors.Count > 0 || + !string.IsNullOrWhiteSpace(logitsDir)); + + public static async Task TryReadCompatibleResultAsync( + HybridQuant quant, string modelPath, string benchDir, string? klLogitsDir, + IReadOnlyCollection domains, int tokenTarget = DefaultTokenTarget, + bool saveLogits = false, bool allowIndependentGpuTopology = true, CancellationToken ct = default, + IReadOnlyDictionary? corpusOverrides = null) + { + try + { + string metricsPath = Path.Combine(benchDir, "bench_metrics.json"); + if (!File.Exists(metricsPath)) return null; + var result = JsonSerializer.Deserialize(await File.ReadAllTextAsync(metricsPath, ct)); + if (result?.Evidence == null || !HasValidMetrics(result, domains, + RequiresComparison(quant, klLogitsDir, saveLogits))) return null; + var expected = await CreateAsync(quant, modelPath, benchDir, klLogitsDir, domains, + tokenTarget, saveLogits, allowIndependentGpuTopology, ct, corpusOverrides); + if (!IsCompatible(result.Evidence, expected)) return null; + if (saveLogits && !await ReferencesAreCompatibleAsync(expected, klLogitsDir, ct)) return null; + return result; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException) + { + return null; + } + } + + /// Gate for DB snapshots/training. The DB hash must point at an independently compatible + /// disk envelope; nullable legacy hashes and missing artifacts never become current evidence. + public static async Task IsCurrentAsync(HybridQuant quant, string? evidenceIdentityHash, + CancellationToken ct = default, IReadOnlyCollection? domains = null) + { + if (!IsSha256(evidenceIdentityHash)) return false; + var requestedDomains = domains ?? new[] { "general" }; + var paths = new ModelArtifactPathService(); + bool native = quant.BaseQuant.UniqueId == BaselineQuants.NativeSourceUniqueId && quant.Tensors.Count == 0; + string benchDir = native + ? Path.Combine(paths.BenchDir, (Cache.TorchType ?? Cache.MainTorchType.BF16).ToString()) + : paths.GetBenchmarkDir(QuantizationService.GetHybridName(quant)); + try + { + string metricsPath = Path.Combine(benchDir, "bench_metrics.json"); + if (!File.Exists(metricsPath)) return false; + var stored = JsonSerializer.Deserialize(await File.ReadAllTextAsync(metricsPath, ct)); + if (stored?.Evidence is not { } recorded || recorded.IdentityHash != evidenceIdentityHash || + !HasValidMetrics(stored, requestedDomains, requireKld: !native)) return false; + // Reading known evidence does not require rediscovering hardware or recreating + // the quantizer's old CPU allocation. Re-execution reuse still checks today's policy. + var expected = await CreateCoreAsync(quant, string.Empty, benchDir, paths.GetBaseLogitsDirectory(), + requestedDomains, DefaultTokenTarget, native, recorded.AllowIndependentGpuTopology, ct, null, recorded); + return IsCompatible(recorded, expected) && + (!native || await ReferencesAreCompatibleAsync(expected, paths.GetBaseLogitsDirectory(), ct)); + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException or InvalidOperationException) { return false; } + } + + public static Task CreateAsync(HybridQuant quant, string modelPath, + string benchDir, string? klLogitsDir, IReadOnlyCollection domains, + int tokenTarget = DefaultTokenTarget, bool saveLogits = false, + bool allowIndependentGpuTopology = true, CancellationToken ct = default, + IReadOnlyDictionary? corpusOverrides = null) + => CreateCoreAsync(quant, modelPath, benchDir, klLogitsDir, domains, tokenTarget, + saveLogits, allowIndependentGpuTopology, ct, corpusOverrides, recordedPolicy: null); + + private static async Task CreateCoreAsync(HybridQuant quant, string modelPath, + string benchDir, string? klLogitsDir, IReadOnlyCollection domains, int tokenTarget, bool saveLogits, + bool allowIndependentGpuTopology, CancellationToken ct, IReadOnlyDictionary? corpusOverrides, + BenchmarkEvidenceManifest? recordedPolicy) + { + if (tokenTarget <= 0) throw new ArgumentOutOfRangeException(nameof(tokenTarget)); + var paths = new ModelArtifactPathService(); + string nativeHash = await HashFileAsync(paths.GetNativeBaseGgufPath(), ct); + string evaluatorHash = await ToolchainHashAsync("llama-perplexity", ct); + string executionPolicyHash = recordedPolicy?.ExecutionPolicyHash ?? HashJson(new + { + Platform = System.Runtime.InteropServices.RuntimeInformation.OSDescription, + Architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), + Hardware = Cache.SysInfo, + GpuMemoryLimits = Cache.GpuMemoryLimitsGb.OrderBy(x => x.Key).ToArray(), + Plan = BenchmarkService.CurrentExecutionPlanFingerprint() + }); + string? imatrixHash = null; + if (Cache.IsImatrixAvailable) + imatrixHash = recordedPolicy != null + ? await ImatrixIdentityService.EnsureActiveImatrixIdentityHashAsync(ct) + : await HashFileAsync(Cache.ActiveImatrixPath ?? throw new InvalidOperationException( + "New measurements need --imatrix-path (actual calibration bytes); a hash-only context is read-only."), ct); + if (Cache.IsImatrixAvailable && string.IsNullOrWhiteSpace(imatrixHash)) + throw new InvalidOperationException("Active imatrix context has no proven artifact or explicit identity."); + // Keep the DB's imatrix identity in agreement with actual bytes, including an in-process replacement. + Cache.ActiveImatrixIdentityHash = imatrixHash; + bool native = quant.BaseQuant.UniqueId == BaselineQuants.NativeSourceUniqueId; + bool compareLogits = RequiresComparison(quant, klLogitsDir, saveLogits); + if (saveLogits && (!native || quant.Tensors.Count > 0)) + throw new InvalidOperationException("Native reference logits must be generated from the unmodified native source."); + int threadCount = recordedPolicy?.QuantizerThreadCount ?? (Cache.SysInfo?.ThreadCount ?? Environment.ProcessorCount); + int writerCapacity = recordedPolicy?.ScratchWriterCapacity ?? Math.Max(1, Cache.ScratchRoots?.Count ?? 0); + bool imatrixApplied = recordedPolicy != null && RecordedDiagnosticRead.Value + ? recordedPolicy.ImatrixApplied + : new ImatrixService().ShouldUseImatrixForQuant(quant); + var recipe = new + { + NativeSource = nativeHash, + Imatrix = imatrixHash ?? "off", + ImatrixApplied = imatrixApplied, + Quantizer = native && saveLogits ? "native-source" : await ToolchainHashAsync("llama-quantize", ct), + CpuThreads = threadCount, + ScratchWriterCapacity = writerCapacity, + RecipeContract = QuantizationRecipeContract, + Base = new { quant.BaseQuant.CanonicalKey, quant.BaseQuant.QuantizeBaseArgumentName, + quant.BaseQuant.SourceRepository, quant.BaseQuant.SourceFileName }, + Groups = quant.Tensors.OrderBy(x => x.TGroup.UniqueId).Select(x => new + { + Group = x.TGroup.Name, Mode = x.OverrideMode.ToString(), + Candidate = x.CandidateBaseline?.CanonicalKey, + Exact = x.ExactTensorScheme?.Names.FirstOrDefault() + }).ToArray(), + Rules = TReg.All.Select(x => new { x.Name, Patterns = x.Tensors.ToArray() }).ToArray(), + Exceptions = TReg.GetBaseQuantExceptionPatterns().ToArray(), + Learned = await LearnedRecipeInputsAsync(quant, ct) + }; + var manifest = new BenchmarkEvidenceManifest + { + RecipeHash = HashJson(recipe), NativeSourceSha256 = nativeHash, + EvaluatorHash = evaluatorHash, TokenTarget = tokenTarget, SaveLogits = saveLogits, + CompareLogits = compareLogits, + ExecutionPolicyHash = executionPolicyHash, + QuantizerThreadCount = threadCount, ScratchWriterCapacity = writerCapacity, ImatrixApplied = imatrixApplied, + AllowIndependentGpuTopology = allowIndependentGpuTopology, + ModelSha256 = string.IsNullOrWhiteSpace(modelPath) ? string.Empty : await HashFileAsync(modelPath, ct) + }; + if (saveLogits && !string.IsNullOrEmpty(manifest.ModelSha256) && manifest.ModelSha256 != nativeHash) + throw new InvalidOperationException("Native reference generation was given an artifact different from the native source GGUF."); + foreach (var domain in domains.OrderBy(x => x, StringComparer.Ordinal)) + { + string corpus = ResolveCorpusPath(benchDir, domain, corpusOverrides); + string corpusHash = await HashFileAsync(corpus, ct); + var evidence = new BenchmarkDomainEvidence + { + CorpusSha256 = corpusHash, + ReferenceDefinitionHash = HashJson(new { SchemaVersion, NativeSource = nativeHash, + Corpus = corpusHash, Evaluator = evaluatorHash, Execution = executionPolicyHash, Context = 2048, Threads = 4, + Policy = "llama-perplexity-stored-logits-v1" }) + }; + if (compareLogits) + { + if (string.IsNullOrWhiteSpace(klLogitsDir)) + throw new InvalidOperationException("Non-native measurements require identified native reference logits."); + evidence.ReferenceLogitsSha256 = await ReadCompatibleReferenceAsync(klLogitsDir, domain, evidence, ct) + ?? throw new InvalidOperationException($"Native logits for '{domain}' have missing or incompatible evidence. Regenerate native benchmarks first."); + } + manifest.Domains.Add(domain, evidence); + } + manifest.IdentityHash = ComputeIdentityHash(manifest); + return manifest; + } + + private static async Task LearnedRecipeInputsAsync(HybridQuant quant, CancellationToken ct) + { + if (quant.Tensors.Count == 0 && !quant.BaseQuant.IsExternalRepositoryBaseline) return []; + var keys = quant.Tensors.Where(x => x.CandidateBaseline != null).Select(x => x.CandidateBaseline!.CanonicalKey) + .Append(quant.BaseQuant.CanonicalKey).Distinct(StringComparer.Ordinal).ToArray(); + await using var db = new MagicQuantContext(); + int family = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); + int profile = TensorGroupProfileService.RequireCurrentProfileId(); + var rows = await db.LearnedBaselineTensorQuants.AsNoTracking() + .Where(x => x.ArchitectureFamilyId == family && x.TensorGroupProfileId == profile && + keys.Contains(x.BaselineCanonicalKey)).ToListAsync(ct); + return rows.OrderBy(x => x.BaselineCanonicalKey, StringComparer.Ordinal).ThenBy(x => x.TensorWeightSchemeId) + .ThenBy(x => x.TensorGroupId).ThenBy(x => x.TensorName, StringComparer.Ordinal) + .Select(x => (object)new { x.BaselineCanonicalKey, x.TensorWeightSchemeId, + x.TensorGroupId, x.TensorName, x.FinalQuantType }).ToArray(); + } + + public static async Task ToolchainHashAsync(string executable, CancellationToken ct = default) + { + string bin = Cache.LlamaBin ?? Path.Combine(Cache.LlamaRoot ?? throw new InvalidOperationException("llama.cpp path is unset."), "build", "bin"); + string exe = Path.Combine(bin, executable + (OperatingSystem.IsWindows() ? ".exe" : "")); + var files = new SortedDictionary(StringComparer.Ordinal) + { + [Path.GetFileName(exe)] = await HashFileAsync(exe, ct) + }; + foreach (string path in Directory.EnumerateFiles(bin).Where(p => + Path.GetFileName(p).Contains("ggml", StringComparison.OrdinalIgnoreCase) || + Path.GetFileName(p).StartsWith("libllama", StringComparison.OrdinalIgnoreCase) || + Path.GetFileName(p).Equals("llama.dll", StringComparison.OrdinalIgnoreCase))) + if (new FileInfo(path).Length > 0) files[Path.GetFileName(path)] = await HashFileAsync(path, ct); + return HashJson(files); + } + + public static string ResolveCorpusPath(string benchDir, string domain, + IReadOnlyDictionary? overrides = null) + { + if (overrides != null) + { + foreach (var key in overrides.Keys) + if (key is not ("general" or "code" or "math")) + throw new ArgumentException($"Unknown frozen corpus domain '{key}'.", nameof(overrides)); + if (overrides.TryGetValue(domain, out var path)) + { + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException($"Frozen corpus path for '{domain}' is empty."); + return Path.GetFullPath(path); + } + } + return Path.Combine(Path.GetDirectoryName(benchDir)!, "_ppl_corpora", $"ppl_corpus_{domain}.txt"); + } + + public static async Task WriteReferenceEvidenceAsync(BenchmarkEvidenceManifest manifest, + string logitsDir, string domain, CancellationToken ct = default) + { + var reference = new NativeReferenceEvidence + { + DefinitionHash = manifest.Domains[domain].ReferenceDefinitionHash, + LogitsSha256 = await HashFileAsync(Path.Combine(logitsDir, $"kld_logits_{domain}.bin"), ct) + }; + await AtomicWriteAsync(Path.Combine(logitsDir, $"kld_logits_{domain}.evidence.json"), reference, ct); + } + + internal static async Task ValidateExecutionInputsAsync(BenchmarkEvidenceManifest started, + HybridQuant quant, string modelPath, string benchDir, string? logitsDir, + IReadOnlyCollection domains, IReadOnlyDictionary? corpusOverrides, + CancellationToken ct) + { + var completed = await CreateAsync(quant, modelPath, benchDir, logitsDir, domains, + started.TokenTarget, started.SaveLogits, started.AllowIndependentGpuTopology, ct, corpusOverrides); + if (!IsCompatible(started, completed)) + throw new InvalidOperationException("Artifact or evaluation inputs changed during measurement. No current evidence was saved."); + } + + private static async Task ReadCompatibleReferenceAsync(string logitsDir, string domain, + BenchmarkDomainEvidence expected, CancellationToken ct) + { + string path = Path.Combine(logitsDir, $"kld_logits_{domain}.evidence.json"); + if (!File.Exists(path)) return null; + var reference = JsonSerializer.Deserialize(await File.ReadAllTextAsync(path, ct)); + if (reference?.DefinitionHash != expected.ReferenceDefinitionHash || !IsSha256(reference.LogitsSha256)) return null; + string actual = await HashFileAsync(Path.Combine(logitsDir, $"kld_logits_{domain}.bin"), ct); + return actual == reference.LogitsSha256 ? actual : null; + } + + private static async Task ReferencesAreCompatibleAsync(BenchmarkEvidenceManifest expected, + string? logitsDir, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(logitsDir)) return false; + foreach (var (domain, evidence) in expected.Domains) + if (await ReadCompatibleReferenceAsync(logitsDir, domain, evidence, ct) == null) return false; + return true; + } + + public static async Task ArchiveExistingMetricsAsync(string benchDir, CancellationToken ct = default, + string? archiveRootOverride = null) + { + string path = Path.Combine(benchDir, "bench_metrics.json"); + if (!Directory.Exists(benchDir)) return; + string? contents = File.Exists(path) ? await File.ReadAllTextAsync(path, ct) : null; + var logs = Directory.GetFiles(benchDir, "perplexity_*.log"); + string logitsDir = Path.Combine(benchDir, "logits"); + var sidecars = Directory.Exists(logitsDir) ? Directory.GetFiles(logitsDir, "kld_logits_*.evidence.json") : []; + if (contents == null && logs.Length == 0 && sidecars.Length == 0) return; + string archive = Path.Combine(archiveRootOverride ?? Path.Combine(benchDir, "history"), + contents == null ? "partial-" + Guid.NewGuid().ToString("N") : HashJson(contents)); + Directory.CreateDirectory(archive); + string destination = Path.Combine(archive, "bench_metrics.json"); + if (contents != null && !File.Exists(destination)) await File.WriteAllTextAsync(destination, contents, ct); + foreach (string log in logs.Concat(sidecars)) + { + string archivedLog = Path.Combine(archive, Path.GetFileName(log)); + if (!File.Exists(archivedLog)) File.Copy(log, archivedLog); + } + } + + public static async Task ArchiveForNativeRepairAsync(string benchDir, CancellationToken ct = default) + { + string archiveRoot = Path.Combine(Path.GetDirectoryName(benchDir)!, "_evidence_history", "native-repair", + Path.GetFileName(benchDir)); + await ArchiveExistingMetricsAsync(benchDir, ct, archiveRoot); + string priorHistory = Path.Combine(benchDir, "history"); + if (Directory.Exists(priorHistory)) + { + Directory.CreateDirectory(archiveRoot); + Directory.Move(priorHistory, Path.Combine(archiveRoot, "prior-history-" + Guid.NewGuid().ToString("N"))); + } + } + + internal static async Task ArchiveDbEvidenceAsync(AiBenchmark benchmark, CancellationToken ct = default) + { + var archived = new + { + SchemaVersion, Kind = "historical-database-evidence", benchmark.Id, + benchmark.ArchitectureFamilyId, benchmark.TensorGroupProfileId, benchmark.AiModelHashId, + benchmark.ImatrixDefinitionId, benchmark.TensorComboId, benchmark.EvidenceIdentityHash, + benchmark.SizeBytes, benchmark.Ngl, benchmark.TokensPerSecond, + Categories = benchmark.CategorBenchmarks.OrderBy(x => x.Category) + .Select(x => new { x.Category, x.Kld, x.Ppl, x.PplError }).ToArray() + }; + string path = Path.Combine(new ModelArtifactPathService().BenchDir, "_evidence_history", "database", + benchmark.Id.ToString("N"), HashJson(archived) + ".json"); + if (!File.Exists(path)) await AtomicWriteAsync(path, archived, ct); + } + + public static async Task AtomicWriteAsync(string path, T value, CancellationToken ct = default) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + await File.WriteAllTextAsync(temp, JsonSerializer.Serialize(value, JsonOptions), ct); + File.Move(temp, path, overwrite: true); + } + finally { if (File.Exists(temp)) File.Delete(temp); } + } + + private static bool IsSha256(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit); + private sealed class NativeReferenceEvidence + { + public string DefinitionHash { get; set; } = string.Empty; + public string LogitsSha256 { get; set; } = string.Empty; + } +} diff --git a/src/MagicQuant/Services/BenchmarkService.cs b/src/MagicQuant/Services/BenchmarkService.cs index 29a1ad9..9a07757 100644 --- a/src/MagicQuant/Services/BenchmarkService.cs +++ b/src/MagicQuant/Services/BenchmarkService.cs @@ -54,6 +54,17 @@ public class BenchmarkService private static string _currentPlanQuantizationKey = "Q8_0"; private static GpuResourceScheduler _resourceScheduler = new(); + internal static string CurrentExecutionPlanFingerprint() + { + lock (SlotSync) + return _currentPlan == null ? "undiscovered" : BenchmarkEvidenceService.HashJson(new + { + _currentPlan.Q8ModelSizeBytes, _currentPlan.NativeModelSizeBytes, + _currentPlan.Q8StableNgl, _currentPlan.NativeStableNgl, + _currentPlan.SharedProfile, _currentPlan.IndependentProfile + }); + } + public int CurrentParallelSlotCount { get @@ -1167,7 +1178,7 @@ private async Task ProbePerplexityAtFixedNglAsync( private static bool IsNativeBaseModel(HybridQuant quantConfig) { - return quantConfig.BaseQuant.UniqueId == BaselineQuants.NativeSourceUniqueId; + return quantConfig.BaseQuant.UniqueId == BaselineQuants.NativeSourceUniqueId && quantConfig.Tensors.Count == 0; } private static IReadOnlyCollection ResolveRequestedDomains( @@ -1186,11 +1197,6 @@ private static IReadOnlyCollection ResolveRequestedDomains( return IsNativeBaseModel(quantConfig) ? BaseDomains : SampleDomains; } - private static bool RequiresKld(HybridQuant quantConfig) - { - return !IsNativeBaseModel(quantConfig); - } - private static ulong TryGetModelSize(string modelPath) { return File.Exists(modelPath) ? (ulong)new FileInfo(modelPath).Length : 0UL; @@ -1253,14 +1259,11 @@ private static List BuildNglFallbackList(int startNgl) return result.Distinct().ToList(); } - private const double KldEpsilon = 1e-8; - private static bool HasMeaningfulKld(double? kld) { return kld.HasValue && - !double.IsNaN(kld.Value) && - !double.IsInfinity(kld.Value) && - Math.Abs(kld.Value) > KldEpsilon; + double.IsFinite(kld.Value) && + kld.Value >= 0; } public async Task TryReuseExistingBenchmarksAsync( @@ -1268,16 +1271,17 @@ public async Task TryReuseExistingBenchmarksAsync( string modelPath, string benchDir, string? klLogitsDir, - IReadOnlyCollection? domainsOverride = null) + IReadOnlyCollection? domainsOverride = null, + bool allowIndependentGpuTopology = true) { var requestedDomains = ResolveRequestedDomains(quantConfig, domainsOverride); - bool requireKld = RequiresKld(quantConfig); + bool requireKld = BenchmarkEvidenceService.RequiresComparison(quantConfig, klLogitsDir, saveLogits: false); - if (!TryReadExistingBenchmarkArtifacts( - benchDir: benchDir, - requestedDomains: requestedDomains, - requireKld: requireKld, - result: out var reused)) + var reused = await BenchmarkEvidenceService.TryReadCompatibleResultAsync( + quantConfig, modelPath, benchDir, klLogitsDir, requestedDomains, + saveLogits: false, allowIndependentGpuTopology: allowIndependentGpuTopology, + ct: MagicQuant.Runtime.RunCancellation.Token); + if (reused == null) { return false; } @@ -1322,12 +1326,16 @@ public async Task RunAllBenchmarksAsync( string? klLogitsDir = null, bool saveLogits = false, IReadOnlyCollection? domainsOverride = null, - bool allowIndependentGpuTopology = true) + bool allowIndependentGpuTopology = true, + bool forceRebenchmark = false, + IReadOnlyDictionary? corpusOverrides = null) { Directory.CreateDirectory(benchDir); var requestedDomains = ResolveRequestedDomains(quantConfig, domainsOverride); - bool requireKld = RequiresKld(quantConfig); + bool requireKld = BenchmarkEvidenceService.RequiresComparison(quantConfig, klLogitsDir, saveLogits); + var evidence = await PrepareBenchmarkEvidenceAsync(quantConfig, modelPath, benchDir, + klLogitsDir, requestedDomains, tokenTarget, saveLogits, allowIndependentGpuTopology, corpusOverrides); if (Cache.SuppressBenchmarkPersistence) { @@ -1340,7 +1348,10 @@ public async Task RunAllBenchmarksAsync( saveLogits: saveLogits, requestedDomains: requestedDomains, requireKld: requireKld, - allowIndependentGpuTopology: allowIndependentGpuTopology); + allowIndependentGpuTopology: allowIndependentGpuTopology, + evidence: evidence, + forceRebenchmark: forceRebenchmark, + corpusOverrides: corpusOverrides); } using var db = new MagicQuantContext(); @@ -1349,61 +1360,20 @@ public async Task RunAllBenchmarksAsync( var aiModelHash = identity.AiModelHash; var tensorCombo = identity.TensorCombo; - var existingBench = await db.AiBenchmarks - .Include(x => x.CategorBenchmarks) - .AsNoTracking() - .FirstOrDefaultAsync(b => b.ArchitectureFamilyId == TensorGroupProfileService.RequireCurrentArchitectureFamilyId() && b.TensorGroupProfileId == TensorGroupProfileService.RequireCurrentProfileId() && b.AiModelHashId == aiModelHash.Id && b.ImatrixDefinitionId == identity.ImatrixDefinitionId && b.TensorComboId == tensorCombo.Id); - - // 1. DB truth first - if (existingBench != null && HasRequiredCategories(existingBench, requestedDomains, requireKld)) + // A DB row alone does not identify a corpus, evaluator or artifact. Only a + // compatible content envelope may hydrate the current DB identity. + var reused = forceRebenchmark ? null : await BenchmarkEvidenceService.TryReadCompatibleResultAsync( + quantConfig, modelPath, benchDir, klLogitsDir, requestedDomains, tokenTarget, + saveLogits, allowIndependentGpuTopology, MagicQuant.Runtime.RunCancellation.Token, corpusOverrides); + if (reused != null) { - if (existingBench.SizeBytes == 0) - { - var repairedSize = TryGetModelSize(modelPath); - if (repairedSize > 0) - { - var trackedRepair = await db.AiBenchmarks - .FirstOrDefaultAsync(x => x.Id == existingBench.Id); - - if (trackedRepair != null) - { - trackedRepair.SizeBytes = repairedSize; - await db.SaveChangesAsync(); - existingBench.SizeBytes = repairedSize; - } - } - } - - if (TryReadExistingBenchmarkArtifacts(benchDir, requestedDomains, requireKld, out var diskResult)) - { - if (!diskResult.ModelSizeBytes.HasValue || diskResult.ModelSizeBytes.Value == 0) - diskResult.ModelSizeBytes = existingBench.SizeBytes > 0 - ? existingBench.SizeBytes - : TryGetModelSize(modelPath); - - return diskResult; - } - - return BuildResultFromDb(existingBench, requestedDomains); - } - - // 2. Disk truth second - if (TryReadExistingBenchmarkArtifacts(benchDir, requestedDomains, requireKld, out var reused)) - { - reused.ModelSizeBytes ??= TryGetModelSize(modelPath); - await SaveBenchmarkToDbAsync( - db: db, - model: aiModelHash, - combo: tensorCombo, - imatrixDefinitionId: identity.ImatrixDefinitionId, - res: reused, - modelPath: modelPath, - executedRunTimings: new List()); - - await WriteMetricsJsonAsync(benchDir, reused); + await SaveBenchmarkToDbAsync(db, aiModelHash, tensorCombo, identity.ImatrixDefinitionId, + reused, modelPath, new List()); return reused; } + await BenchmarkEvidenceService.ArchiveExistingMetricsAsync(benchDir, MagicQuant.Runtime.RunCancellation.Token); + // 3. Real execution: fixed slot + fixed ngl if (_currentPlan == null) { @@ -1435,9 +1405,11 @@ await SaveBenchmarkToDbAsync( } ulong modelSizeBytes = TryGetModelSize(modelPath); + var gpuQueueClock = Stopwatch.StartNew(); await using var slotLease = await AcquireBenchmarkSlotAsync( modelSizeBytes, allowIndependentGpuTopology); + gpuQueueClock.Stop(); var slot = slotLease.Slot; int initialNgl = ResolveDynamicNglForModel(modelSizeBytes, slot); @@ -1451,6 +1423,8 @@ await SaveBenchmarkToDbAsync( var result = new BenchmarkResult { + Evidence = evidence, + StageMilliseconds = new Dictionary { ["gpu_queue_wait"] = gpuQueueClock.Elapsed.TotalMilliseconds }, ModelSizeBytes = modelSizeBytes }; @@ -1474,19 +1448,7 @@ await SaveBenchmarkToDbAsync( foreach (var domain in requestedDomains) { - if (TryReadExistingPplLog( - benchDir: benchDir, - domain: domain, - allowMissingKld: !requireKld, - requirePositiveKld: requireKld, - metrics: out var existingPpl)) - { - result.Perplexity[domain] = existingPpl; - continue; - } - - string corpusPath = Path.Combine(corporaRoot, $"ppl_corpus_{domain}.txt"); - await PreparePplCorpusAsync(domain, corpusPath, tokenTarget); + string corpusPath = BenchmarkEvidenceService.ResolveCorpusPath(benchDir, domain, corpusOverrides); DateTime startedUtc = DateTime.UtcNow; var sw = Stopwatch.StartNew(); @@ -1510,11 +1472,15 @@ await SaveBenchmarkToDbAsync( { throw new InvalidOperationException( $"Non-base benchmark produced invalid KLD for domain '{domain}'. " + - $"KLD must exist and be > 0. Parsed value: {(metrics.Kld.HasValue ? metrics.Kld.Value.ToString(CultureInfo.InvariantCulture) : "null")}"); + $"KLD must be finite and nonnegative. Parsed value: {(metrics.Kld.HasValue ? metrics.Kld.Value.ToString(CultureInfo.InvariantCulture) : "null")}"); } sw.Stop(); + result.StageMilliseconds[$"perplexity_{domain}_process_total"] = sw.Elapsed.TotalMilliseconds; + if (saveLogits && !string.IsNullOrWhiteSpace(klLogitsDir)) + await BenchmarkEvidenceService.WriteReferenceEvidenceAsync(evidence, klLogitsDir, domain, + MagicQuant.Runtime.RunCancellation.Token); result.Perplexity[domain] = metrics; result.LlamaBench.Ngl = runtimeNgl.LastSuccessfulNgl; @@ -1550,6 +1516,8 @@ await PersistFailedBenchmarkRunAsync( } } + await BenchmarkEvidenceService.ValidateExecutionInputsAsync(evidence, quantConfig, modelPath, + benchDir, klLogitsDir, requestedDomains, corpusOverrides, MagicQuant.Runtime.RunCancellation.Token); await WriteMetricsJsonAsync(benchDir, result); await SaveBenchmarkToDbAsync( @@ -1574,14 +1542,16 @@ private async Task RunAllBenchmarksTransientAsync( bool saveLogits, IReadOnlyCollection requestedDomains, bool requireKld, - bool allowIndependentGpuTopology) + bool allowIndependentGpuTopology, + BenchmarkEvidenceManifest evidence, + bool forceRebenchmark, + IReadOnlyDictionary? corpusOverrides) { - if (TryReadExistingBenchmarkArtifacts(benchDir, requestedDomains, requireKld, out var reused)) - { - reused.ModelSizeBytes ??= TryGetModelSize(modelPath); - await WriteMetricsJsonAsync(benchDir, reused); - return reused; - } + var reused = forceRebenchmark ? null : await BenchmarkEvidenceService.TryReadCompatibleResultAsync( + quantConfig, modelPath, benchDir, klLogitsDir, requestedDomains, tokenTarget, + saveLogits, allowIndependentGpuTopology, MagicQuant.Runtime.RunCancellation.Token, corpusOverrides); + if (reused != null) return reused; + await BenchmarkEvidenceService.ArchiveExistingMetricsAsync(benchDir, MagicQuant.Runtime.RunCancellation.Token); if (_currentPlan == null) { @@ -1591,9 +1561,11 @@ private async Task RunAllBenchmarksTransientAsync( } ulong modelSizeBytes = TryGetModelSize(modelPath); + var gpuQueueClock = Stopwatch.StartNew(); await using var slotLease = await AcquireBenchmarkSlotAsync( modelSizeBytes, allowIndependentGpuTopology); + gpuQueueClock.Stop(); var slot = slotLease.Slot; int initialNgl = ResolveDynamicNglForModel(modelSizeBytes, slot); @@ -1607,6 +1579,8 @@ private async Task RunAllBenchmarksTransientAsync( var result = new BenchmarkResult { + Evidence = evidence, + StageMilliseconds = new Dictionary { ["gpu_queue_wait"] = gpuQueueClock.Elapsed.TotalMilliseconds }, ModelSizeBytes = modelSizeBytes, LlamaBench = new LlamaBenchMetrics { @@ -1626,23 +1600,12 @@ private async Task RunAllBenchmarksTransientAsync( foreach (var domain in requestedDomains) { - if (TryReadExistingPplLog( - benchDir: benchDir, - domain: domain, - allowMissingKld: !requireKld, - requirePositiveKld: requireKld, - metrics: out var existingPpl)) - { - result.Perplexity[domain] = existingPpl; - continue; - } - - string corpusPath = Path.Combine(corporaRoot, $"ppl_corpus_{domain}.txt"); - await PreparePplCorpusAsync(domain, corpusPath, tokenTarget); + string corpusPath = BenchmarkEvidenceService.ResolveCorpusPath(benchDir, domain, corpusOverrides); AnsiConsole.MarkupLine( $"[yellow]Running transient Perplexity ({Markup.Escape(domain)})[/] [grey]({Markup.Escape(slot.DisplayName)}, ngl={runtimeNgl.CurrentNgl})[/]"); + var processClock = Stopwatch.StartNew(); var metrics = await RunPplBenchmarkWithNglFallbackAsync( modelPath: modelPath, benchDir: benchDir, @@ -1657,13 +1620,19 @@ private async Task RunAllBenchmarksTransientAsync( { throw new InvalidOperationException( $"Non-base transient benchmark produced invalid KLD for domain '{domain}'. " + - $"KLD must exist and be > 0. Parsed value: {(metrics.Kld.HasValue ? metrics.Kld.Value.ToString(CultureInfo.InvariantCulture) : "null")}"); + $"KLD must be finite and nonnegative. Parsed value: {(metrics.Kld.HasValue ? metrics.Kld.Value.ToString(CultureInfo.InvariantCulture) : "null")}"); } + result.StageMilliseconds[$"perplexity_{domain}_process_total"] = processClock.Elapsed.TotalMilliseconds; + if (saveLogits && !string.IsNullOrWhiteSpace(klLogitsDir)) + await BenchmarkEvidenceService.WriteReferenceEvidenceAsync(evidence, klLogitsDir, domain, + MagicQuant.Runtime.RunCancellation.Token); result.Perplexity[domain] = metrics; result.LlamaBench.Ngl = runtimeNgl.LastSuccessfulNgl; } + await BenchmarkEvidenceService.ValidateExecutionInputsAsync(evidence, quantConfig, modelPath, + benchDir, klLogitsDir, requestedDomains, corpusOverrides, MagicQuant.Runtime.RunCancellation.Token); await WriteMetricsJsonAsync(benchDir, result); return result; } @@ -1672,6 +1641,27 @@ private async Task RunAllBenchmarksTransientAsync( // Database helpers // ---------------------------------------------------------------- + /// Prepared tensor-map learning needs an FK before measurement. This row carries + /// no evidence or categories and therefore cannot be consumed as measured truth. + internal async Task EnsureUnmeasuredBenchmarkIdentityAsync(HybridQuant quant, CancellationToken ct) + { + await using var db = new MagicQuantContext(); + var identity = await GetOrCreateBenchmarkIdentityAsync(db, quant, ct); + int family = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); + int profile = TensorGroupProfileService.RequireCurrentProfileId(); + if (await db.AiBenchmarks.AnyAsync(x => x.ArchitectureFamilyId == family && + x.TensorGroupProfileId == profile && x.AiModelHashId == identity.AiModelHash.Id && + x.ImatrixDefinitionId == identity.ImatrixDefinitionId && x.TensorComboId == identity.TensorCombo.Id, ct)) return; + db.AiBenchmarks.Add(new AiBenchmark + { + ArchitectureFamilyId = family, TensorGroupProfileId = profile, + AiModelHashId = identity.AiModelHash.Id, ImatrixDefinitionId = identity.ImatrixDefinitionId, + TensorComboId = identity.TensorCombo.Id + }); + await db.SaveChangesAsync(ct); + } + + private async Task<(AiModelHash AiModelHash, TensorCombo TensorCombo, int? ImatrixDefinitionId)> GetOrCreateBenchmarkIdentityAsync( MagicQuantContext db, HybridQuant quantConfig, @@ -1746,6 +1736,8 @@ private async Task SaveBenchmarkToDbAsync( string modelPath, IReadOnlyCollection executedRunTimings) { + if (res.Evidence == null || res.Evidence.IdentityHash != BenchmarkEvidenceService.ComputeIdentityHash(res.Evidence)) + throw new InvalidOperationException("Refusing to persist benchmark metrics without a complete evidence identity."); using var transaction = await db.Database.BeginTransactionAsync(); try @@ -1794,8 +1786,15 @@ private async Task SaveBenchmarkToDbAsync( await db.SaveChangesAsync(); } + if (bench.CategorBenchmarks.Count > 0 && bench.EvidenceIdentityHash != res.Evidence.IdentityHash) + await BenchmarkEvidenceService.ArchiveDbEvidenceAsync(bench, MagicQuant.Runtime.RunCancellation.Token); + + if (!BenchmarkEvidenceService.HasValidMetrics(res, res.Perplexity.Keys, requireKld: res.Evidence.CompareLogits)) + throw new InvalidOperationException("Refusing to persist nonfinite, negative or incomplete benchmark metrics."); + bench.TokensPerSecond = res.LlamaBench?.Tps ?? 0; bench.Ngl = (byte)(res.LlamaBench?.Ngl ?? 0); + bench.EvidenceIdentityHash = res.Evidence.IdentityHash; if (sizeBytes > 0) { @@ -1824,7 +1823,7 @@ private async Task SaveBenchmarkToDbAsync( byte category = DomainToCategory(domain); double kld; - if (isBaseModel) + if (isBaseModel && !res.Evidence.CompareLogits) { kld = 0d; } @@ -2033,91 +2032,27 @@ private sealed class PendingBenchmarkRunTiming // Artifact reuse helpers // ---------------------------------------------------------------- - private async Task WriteMetricsJsonAsync(string benchDir, BenchmarkResult result) - { - Directory.CreateDirectory(benchDir); - - string jsonPath = Path.Combine(benchDir, "bench_metrics.json"); - await File.WriteAllTextAsync( - jsonPath, - JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true })); - } + private Task WriteMetricsJsonAsync(string benchDir, BenchmarkResult result) + => BenchmarkEvidenceService.AtomicWriteAsync(Path.Combine(benchDir, "bench_metrics.json"), result, + MagicQuant.Runtime.RunCancellation.Token); - private bool TryReadExistingBenchmarkArtifacts( - string benchDir, - IReadOnlyCollection requestedDomains, - bool requireKld, - out BenchmarkResult result) + private async Task PrepareBenchmarkEvidenceAsync( + HybridQuant quant, string modelPath, string benchDir, string? logitsDir, + IReadOnlyCollection domains, int tokenTarget, bool saveLogits, bool allowIndependentGpuTopology, + IReadOnlyDictionary? corpusOverrides) { - result = new BenchmarkResult(); - - string jsonPath = Path.Combine(benchDir, "bench_metrics.json"); - if (File.Exists(jsonPath)) + string corpusRoot = Path.Combine(Path.GetDirectoryName(benchDir)!, "_ppl_corpora"); + Directory.CreateDirectory(corpusRoot); + foreach (string domain in domains) { - try - { - var parsed = JsonSerializer.Deserialize(File.ReadAllText(jsonPath)); - if (parsed != null && IsReusableBenchmarkResult(parsed, requestedDomains, requireKld)) - { - result = parsed; - return true; - } - } - catch - { - // fall through - } - } - - var rebuilt = new BenchmarkResult - { - LlamaBench = new LlamaBenchMetrics - { - LogPath = null, - Backend = "disabled", - Ngl = 0, - Test = "disabled", - Tps = 0 - } - }; - - foreach (var domain in requestedDomains) - { - if (!TryReadExistingPplLog( - benchDir: benchDir, - domain: domain, - allowMissingKld: !requireKld, - requirePositiveKld: requireKld, - metrics: out var ppl)) - { - return false; - } - - rebuilt.Perplexity[domain] = ppl; + string corpus = BenchmarkEvidenceService.ResolveCorpusPath(benchDir, domain, corpusOverrides); + if (corpusOverrides?.ContainsKey(domain) == true) + await BenchmarkEvidenceService.HashFileAsync(corpus, MagicQuant.Runtime.RunCancellation.Token); + else + await PreparePplCorpusAsync(domain, corpus, tokenTarget); } - - result = rebuilt; - return true; - } - - private bool IsReusableBenchmarkResult( - BenchmarkResult result, - IReadOnlyCollection requestedDomains, - bool requireKld) - { - foreach (var domain in requestedDomains) - { - if (!result.Perplexity.TryGetValue(domain, out var ppl)) - return false; - - if (ppl.Ppl <= 0 || ppl.PplError < 0) - return false; - - if (requireKld && !HasMeaningfulKld(ppl.Kld)) - return false; - } - - return true; + return await BenchmarkEvidenceService.CreateAsync(quant, modelPath, benchDir, logitsDir, domains, + tokenTarget, saveLogits, allowIndependentGpuTopology, MagicQuant.Runtime.RunCancellation.Token, corpusOverrides); } private bool TryReadExistingLlamaBenchLog(string logPath, out LlamaBenchMetrics metrics) @@ -2144,111 +2079,6 @@ private bool TryReadExistingLlamaBenchLog(string logPath, out LlamaBenchMetrics return false; } - private bool TryReadExistingPplLog( - string benchDir, - string domain, - bool allowMissingKld, - bool requirePositiveKld, - out PplMetrics metrics) - { - metrics = null!; - - string logPath = Path.Combine(benchDir, $"perplexity_{domain}.log"); - if (!File.Exists(logPath) || new FileInfo(logPath).Length == 0) - return false; - - try - { - var parsed = BenchmarkLogParser.ParsePerplexity(logPath, allowMissingKld); - - if (parsed.Ppl <= 0) - return false; - - if (requirePositiveKld && !HasMeaningfulKld(parsed.Kld)) - return false; - - metrics = parsed; - return true; - } - catch - { - return false; - } - } - - private static bool HasRequiredCategories( - AiBenchmark bench, - IReadOnlyCollection requestedDomains, - bool requireKld) - { - if (bench.CategorBenchmarks == null || bench.CategorBenchmarks.Count == 0) - return false; - - foreach (var domain in requestedDomains) - { - byte category = domain switch - { - "general" => (byte)BenchmarkCategory.General, - "math" => (byte)BenchmarkCategory.Math, - "code" => (byte)BenchmarkCategory.Code, - _ => throw new InvalidOperationException($"Unknown benchmark domain '{domain}'.") - }; - - var existing = bench.CategorBenchmarks.FirstOrDefault(x => x.Category == category); - if (existing == null) - return false; - - if (existing.Ppl <= 0) - return false; - - if (requireKld && existing.Kld <= 0) - return false; - } - - return bench.SizeBytes > 0; - } - - private BenchmarkResult BuildResultFromDb( - AiBenchmark bench, - IReadOnlyCollection requestedDomains) - { - var result = new BenchmarkResult - { - ModelSizeBytes = bench.SizeBytes, - LlamaBench = new LlamaBenchMetrics - { - Ngl = bench.Ngl, - Tps = bench.TokensPerSecond - } - }; - - foreach (var domain in requestedDomains) - { - byte category = domain switch - { - "general" => (byte)BenchmarkCategory.General, - "math" => (byte)BenchmarkCategory.Math, - "code" => (byte)BenchmarkCategory.Code, - _ => throw new InvalidOperationException($"Unknown benchmark domain '{domain}'.") - }; - - var existing = bench.CategorBenchmarks.First(x => x.Category == category); - - result.Perplexity[domain] = new PplMetrics - { - Ppl = existing.Ppl, - PplError = existing.PplError, - Kld = existing.Kld - }; - } - - return result; - } - - // ---------------------------------------------------------------- - // Real benchmark execution (fixed slot + fixed ngl) - // ---------------------------------------------------------------- - private async Task RunLlamaBenchAsync( string modelPath, string benchDir, diff --git a/src/MagicQuant/Services/CloneArtifactEvidenceService.cs b/src/MagicQuant/Services/CloneArtifactEvidenceService.cs new file mode 100644 index 0000000..d34d20b --- /dev/null +++ b/src/MagicQuant/Services/CloneArtifactEvidenceService.cs @@ -0,0 +1,75 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using MagicQuant.Helpers; +using MQ.DB; + +namespace MagicQuant.Services; + +/// Build proof for clone artifacts. A matching file size or release summary +/// does not prove that the requested source, exact tensor recipe and imatrix were built. +public static class CloneArtifactEvidenceService +{ + public sealed record Proof(int SchemaVersion, string RequestHash, string ArtifactSha256); + + public static string ComputeRequestHash(string nativeSha256, string quantizerHash, + string? imatrixSha256, string baseQuant, IReadOnlyDictionary tensorTypes, + bool allowMissingTensors, string? missingBaseQuant, int threadCount) + { + var input = new + { + SchemaVersion = 1, Native = nativeSha256, Quantizer = quantizerHash, + Imatrix = imatrixSha256, BaseQuant = baseQuant.Trim().ToUpperInvariant(), + AllowMissingTensors = allowMissingTensors, + MissingBaseQuant = missingBaseQuant?.Trim().ToUpperInvariant(), ThreadCount = threadCount, + Tensors = tensorTypes.OrderBy(x => x.Key, StringComparer.Ordinal) + .Select(x => new { Name = x.Key, Type = x.Value.Trim().ToUpperInvariant() }).ToArray() + }; + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(input)))).ToLowerInvariant(); + } + + public static async Task CreateRequestHashAsync(IReadOnlyDictionary tensorTypes, + string baseQuant, bool allowMissingTensors, string? missingBaseQuant, + CancellationToken ct = default) + { + var paths = new ModelArtifactPathService(); + var native = await BenchmarkEvidenceService.HashFileAsync(paths.GetNativeBaseGgufPath(), ct); + var quantizer = await BenchmarkEvidenceService.ToolchainHashAsync("llama-quantize", ct); + var imatrix = Cache.IsImatrixAvailable + ? await BenchmarkEvidenceService.HashFileAsync(Cache.ActiveImatrixPath + ?? throw new InvalidOperationException("Active imatrix has no path."), ct) + : null; + return ComputeRequestHash(native, quantizer, imatrix, baseQuant, tensorTypes, + allowMissingTensors, missingBaseQuant, Cache.SysInfo?.ThreadCount ?? Environment.ProcessorCount); + } + + public static async Task CanReuseAsync(string outputPath, string proofPath, + string requestHash, CancellationToken ct = default) + { + if (!File.Exists(outputPath) || !File.Exists(proofPath)) return false; + try + { + var proof = JsonSerializer.Deserialize(await File.ReadAllTextAsync(proofPath, ct)); + return proof is { SchemaVersion: 1 } && proof.RequestHash == requestHash + && proof.ArtifactSha256 == await BenchmarkEvidenceService.HashFileAsync(outputPath, ct); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + return false; + } + } + + public static async Task WriteAsync(string outputPath, string proofPath, string requestHash, + CancellationToken ct = default) + { + var proof = new Proof(1, requestHash, await BenchmarkEvidenceService.HashFileAsync(outputPath, ct)); + Directory.CreateDirectory(Path.GetDirectoryName(proofPath)!); + string temporary = proofPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + await File.WriteAllTextAsync(temporary, JsonSerializer.Serialize(proof), ct); + File.Move(temporary, proofPath, overwrite: true); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } +} diff --git a/src/MagicQuant/Services/CloneManifestTensorMapBuildService.cs b/src/MagicQuant/Services/CloneManifestTensorMapBuildService.cs index 223f581..c361db8 100644 --- a/src/MagicQuant/Services/CloneManifestTensorMapBuildService.cs +++ b/src/MagicQuant/Services/CloneManifestTensorMapBuildService.cs @@ -268,14 +268,13 @@ private async Task> CaptureResolvedTensorTyp .ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal); } } + catch (OperationCanceledException) { throw; } catch (Exception ex) { - AnsiConsole.MarkupLine($"[yellow]Could not capture resolved tensor map from clone GGUF; preserving manifest tensor map:[/] {Markup.Escape(ex.Message)}"); + throw new InvalidOperationException("Cannot verify the clone's emitted tensor map. Requested types must not be published as observed types.", ex); } - return fallbackTensorTypes - .OrderBy(x => x.Key, StringComparer.Ordinal) - .ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal); + throw new InvalidOperationException("The clone GGUF contained no readable tensor types; its exact recipe is unverified."); } private static async Task PersistResolvedTensorTypesToOutputManifestAsync( diff --git a/src/MagicQuant/Services/CombinationDuckDbSchema.cs b/src/MagicQuant/Services/CombinationDuckDbSchema.cs index b99b2af..1d70063 100644 --- a/src/MagicQuant/Services/CombinationDuckDbSchema.cs +++ b/src/MagicQuant/Services/CombinationDuckDbSchema.cs @@ -6,7 +6,7 @@ internal static class CombinationDuckDbSchema { public const string TableName = "tensor_configs"; public const string SlotColumnList = "BaseQuant, Embeddings, LmHead, AttnQ, AttnKV, AttnOutput, FfnUpGate, FfnDown, MoeExperts, MoeRouter"; - public const string PredictionColumnList = "PredictedKld, PredictedSizeBytes, PredictionConfidence, PredictionRank, BaseRankSafeKld, AnomalyAdjustmentKld, FinalPredictedKld, IsProtectedAnchor, IsVirtualPredictionAnchor, AnchorBaselineRuntimeId, AnchorBaselineCanonicalKey, AnchorDisplayName"; + public const string PredictionColumnList = "PredictedKld, PredictedSizeBytes, PredictionConfidence, PredictionRank, BaseRankSafeKld, AnomalyAdjustmentKld, FinalPredictedKld, IsProtectedAnchor, IsVirtualPredictionAnchor, AnchorBaselineRuntimeId, AnchorBaselineCanonicalKey, AnchorDisplayName, AdditiveKld, CrossTerm, RawInteractionKld, ProjectedKld"; public const string ActiveCandidatePredicateSql = "COALESCE(IsProtectedAnchor, FALSE) = FALSE"; public const string VirtualPredictionAnchorPredicateSql = "COALESCE(IsVirtualPredictionAnchor, FALSE) = TRUE"; public const string EffectivePredictedKldSql = "COALESCE(FinalPredictedKld, PredictedKld)"; @@ -31,7 +31,8 @@ internal static class CombinationDuckDbSchema "utinyint","utinyint","utinyint","utinyint","utinyint","utinyint","utinyint","utinyint","utinyint","utinyint", "double","ubigint","double","ubigint", "double","double","double","boolean", - "boolean","utinyint","varchar","varchar" + "boolean","utinyint","varchar","varchar", + "double","double","double","double" ]; public static string CreateTableSql => $@" @@ -73,7 +74,14 @@ internal static class CombinationDuckDbSchema IsVirtualPredictionAnchor BOOLEAN DEFAULT FALSE, AnchorBaselineRuntimeId UTINYINT, AnchorBaselineCanonicalKey VARCHAR, - AnchorDisplayName VARCHAR + AnchorDisplayName VARCHAR, + + -- Unmodified scoring components for replay and challenger experiments. + -- ProjectedKld stays pre-anomaly; FinalPredictedKld may later change. + AdditiveKld DOUBLE, + CrossTerm DOUBLE, + RawInteractionKld DOUBLE, + ProjectedKld DOUBLE );"; public static string BuildSlotEqualityPredicate(string leftAlias, string rightAlias) diff --git a/src/MagicQuant/Services/CombinationSurvivalPipelineService.cs b/src/MagicQuant/Services/CombinationSurvivalPipelineService.cs index 8f3aece..c5f5cef 100644 --- a/src/MagicQuant/Services/CombinationSurvivalPipelineService.cs +++ b/src/MagicQuant/Services/CombinationSurvivalPipelineService.cs @@ -84,7 +84,8 @@ public async Task RunAsync( var selection = await _selectionEngine.RunAsync( pureBaselines, - ct); + ct, + isolationRescueCandidates: isolationOptimizationResult?.KldSizeRescueCandidates); report.EndingCount = selection.Survivors.Count; report.AddRemoval("prediction-guided-non-selected", Math.Max(0L, report.StartingCount - report.EndingCount)); @@ -106,7 +107,8 @@ public async Task RunAsync( ? "model" : new DirectoryInfo(Cache.ModelDirectory!).Name; - var benchmarkOverview = selection.Survivors + var benchmarkOverview = selection.MeasuredSnapshots + .Concat(selection.Survivors) .Concat(pureBaselines) .Concat(selection.ValidationFailures.Select(x => x.Snapshot).OfType()) .DistinctBy(x => TensorConfigIdentity.ToKey(x.Config)) diff --git a/src/MagicQuant/Services/DuckDbPredictionMaterializationService.cs b/src/MagicQuant/Services/DuckDbPredictionMaterializationService.cs index 29fd5b1..9fda11d 100644 --- a/src/MagicQuant/Services/DuckDbPredictionMaterializationService.cs +++ b/src/MagicQuant/Services/DuckDbPredictionMaterializationService.cs @@ -1,8 +1,12 @@ using System.Globalization; using System.Numerics; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; using DuckDB.NET.Data; using MagicQuant.Helpers; using MagicQuant.Models; +using MQ.DB; using MQ.DB.Models; using Spectre.Console; @@ -57,7 +61,11 @@ await ExecuteAsync(c, $@" PredictionRank = NULL, BaseRankSafeKld = NULL, AnomalyAdjustmentKld = 0.0, - FinalPredictedKld = NULL;", ct); + FinalPredictedKld = NULL, + AdditiveKld = NULL, + CrossTerm = NULL, + RawInteractionKld = NULL, + ProjectedKld = NULL;", ct); await BuildLookupTablesAsync(c, model, ct); await PrintLookupDiagnosticsAsync(c, model, ct); @@ -65,6 +73,8 @@ await ExecuteAsync(c, $@" await PrintPredictionWorkDiagnosticsAsync(c, ct); await BuildPavaBlocksAsync(c, ct); await PersistProjectedPredictionsAsync(c, model, ct); + if (Config.Current.Prediction.ExportCandidateScores) + await ExportCandidateScoresAsync(c, model, ct); var status = await _store.GetPredictionStatusAsync(ct); await PrintFinalMaterializationDiagnosticsAsync(c, status, ct); @@ -83,6 +93,104 @@ await ExecuteAsync(c, $@" return status; } + private static async Task ExportCandidateScoresAsync( + DuckDBConnection c, + RankSafeKldPredictionService.RankSafePredictionModel model, + CancellationToken ct) + { + string directory = Path.Combine(Cache.ModelMagicQuantDirectory + ?? throw new InvalidOperationException("Prediction export requires an initialized model work directory."), "PredictionDiagnostics"); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "prediction_candidates_pre_anomaly.jsonl"); + string temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + long count = 0; + long covered = 0; + using var digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + try + { + using (var cmd = c.CreateCommand()) + { + cmd.CommandText = $@" +SELECT {CombinationDuckDbSchema.SlotColumnList}, + AdditiveKld, CrossTerm, RawInteractionKld, ProjectedKld, + PredictedKld, PredictedSizeBytes, PredictionRank, PredictionConfidence, + COALESCE(IsProtectedAnchor, FALSE), COALESCE(IsVirtualPredictionAnchor, FALSE) +FROM {CombinationDuckDbSchema.TableName} +ORDER BY {CombinationDuckDbSchema.SlotColumnList};"; + using var reader = await cmd.ExecuteReaderAsync(ct); + await using var writer = new StreamWriter(temporary, false, new UTF8Encoding(false)) { NewLine = "\n" }; + while (await reader.ReadAsync(ct)) + { + ct.ThrowIfCancellationRequested(); + double? Metric(int index) + { + if (reader.IsDBNull(index)) return null; + double value = ToDouble(reader.GetValue(index)); + return double.IsFinite(value) ? value : null; + } + var raw = Metric(12); + var projected = Metric(13); + bool isCovered = Metric(14).HasValue && !reader.IsDBNull(15); + string json = JsonSerializer.Serialize(new + { + config_key = string.Join(":", Enumerable.Range(0, 10).Select(i => ToByte(reader.GetValue(i)))), + additive_kld = Metric(10), + cross_term = Metric(11), + raw_interaction_kld = raw, + projected_kld = projected, + predicted_kld = Metric(14), + projection_adjustment_kld = projected - raw, + projection_changed_score = projected.HasValue && raw.HasValue && projected.Value != raw.Value, + predicted_size_bytes = reader.IsDBNull(15) ? (ulong?)null : ToUInt64(reader.GetValue(15)), + predicted_rank = reader.IsDBNull(16) ? (ulong?)null : ToUInt64(reader.GetValue(16)), + prediction_support_score = Metric(17), + is_protected_anchor = ToBool(reader.GetValue(18)), + is_virtual_prediction_anchor = ToBool(reader.GetValue(19)), + prediction_coverage = isCovered ? "covered" : "incomplete", + selection_eligible = (bool?)null + }); + await writer.WriteLineAsync(json.AsMemory(), ct); + digest.AppendData(Encoding.UTF8.GetBytes(json + "\n")); + count++; + if (isCovered) covered++; + } + } + File.Move(temporary, path, overwrite: true); + var metadata = new + { + schema_version = 1, + generated_at_utc = DateTime.UtcNow, + mode = "production_materialization_pre_anomaly", + projection_mode = "rank_safe", + records_file = Path.GetFileName(path), + records_sha256 = Convert.ToHexString(digest.GetHashAndReset()).ToLowerInvariant(), + row_count = count, + covered_count = covered, + production_replay = false, + eligibility_scope = "prediction_coverage_only", + note = "Frozen whole-population scores before anomaly rules or selector gates. Actual artifact/label and final decision provenance must be joined separately; support score is not calibrated uncertainty.", + model_id = Cache.CurrentModelId, + architecture_family_id = Cache.CurrentArchitectureFamilyId, + tensor_group_profile_id = Cache.CurrentTensorGroupProfileId, + tensor_group_profile_fingerprint = Cache.CurrentTensorGroupProfileFingerprintHash, + imatrix_identity = Cache.IsImatrixAvailable ? Cache.ActiveImatrixIdentityHash : "off", + fit = model.Fit, + fit_training_config_key_scope = "canonical_prediction_coordinates", + fit_training_config_keys = model.FitTrainingConfigKeys, + active_groups = model.ActiveGroups.Select(x => new { id = x.UniqueId, name = x.Name }), + carrier_baseonly_kld = model.Q8BaseOnly.Kld, + notes = model.Notes + }; + await File.WriteAllTextAsync(Path.ChangeExtension(path, ".metadata.json"), + JsonSerializer.Serialize(metadata, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }), ct); + AnsiConsole.MarkupLine($"[green]Frozen pre-anomaly candidate scores:[/] {Markup.Escape(path)} ({count:N0} rows)"); + } + finally + { + if (File.Exists(temporary)) File.Delete(temporary); + } + } + private static async Task BuildLookupTablesAsync( DuckDBConnection c, RankSafeKldPredictionService.RankSafePredictionModel model, @@ -381,7 +489,7 @@ PredictedSizeBytes ASC FROM temp_projection;", ct); } - private static async Task BuildPavaBlocksAsync(DuckDBConnection c, CancellationToken ct) + internal static async Task BuildPavaBlocksAsync(DuckDBConnection c, CancellationToken ct) { await ExecuteAsync(c, @" DROP TABLE IF EXISTS temp_pava_blocks; @@ -455,7 +563,7 @@ FROM temp_prediction_order tx.Commit(); } - private static async Task PersistProjectedPredictionsAsync( + internal static async Task PersistProjectedPredictionsAsync( DuckDBConnection c, RankSafeKldPredictionService.RankSafePredictionModel model, CancellationToken ct) @@ -469,13 +577,15 @@ CREATE TEMP TABLE temp_projected_prediction AS o.PredictionWorkId, b.ProjectedKld AS PredictedKld, o.InteractionKld, + COALESCE(x.CrossTerm, 0.0) AS CrossTerm, o.PredictedSizeBytes, b.BlockCount, ABS(b.ProjectedKld - o.InteractionKld) / GREATEST(b.ProjectedKld, 1e-9) AS AdjustmentRatio, GREATEST(0.25, 1.0 / SQRT(GREATEST(CAST(b.BlockCount AS DOUBLE), 1.0))) AS PlateauPenalty FROM temp_prediction_order o JOIN temp_pava_blocks b - ON o.PredictionOrdinal BETWEEN b.StartOrdinal AND b.EndOrdinal;", ct); + ON o.PredictionOrdinal BETWEEN b.StartOrdinal AND b.EndOrdinal +LEFT JOIN temp_work_cross_term x ON x.PredictionWorkId = o.PredictionWorkId;", ct); await ExecuteAsync(c, $@" DROP TABLE IF EXISTS temp_ranked_prediction; @@ -484,6 +594,9 @@ CREATE TEMP TABLE temp_ranked_prediction AS w.{CombinationDuckDbSchema.SlotColumnList.Replace(", ", ", w.")}, p.PredictedKld, p.PredictedSizeBytes, + w.AdditiveKld, + p.CrossTerm, + p.InteractionKld AS RawInteractionKld, LEAST(1.0, GREATEST(0.0, CASE WHEN NOT {CombinationDuckDbSchema.QualifyHybridPredicate("w")} THEN 1.0 @@ -523,7 +636,11 @@ await ExecuteAsync(c, $@" PredictionRank = r.PredictionRank, BaseRankSafeKld = r.PredictedKld, AnomalyAdjustmentKld = 0.0, - FinalPredictedKld = r.PredictedKld + FinalPredictedKld = r.PredictedKld, + AdditiveKld = r.AdditiveKld, + CrossTerm = r.CrossTerm, + RawInteractionKld = r.RawInteractionKld, + ProjectedKld = r.PredictedKld FROM temp_ranked_prediction_with_rank r WHERE {CombinationDuckDbSchema.BuildSlotEqualityPredicate("t", "r")};", ct); } diff --git a/src/MagicQuant/Services/HybridBenchmarkRepository.cs b/src/MagicQuant/Services/HybridBenchmarkRepository.cs index 2e56076..3dec222 100644 --- a/src/MagicQuant/Services/HybridBenchmarkRepository.cs +++ b/src/MagicQuant/Services/HybridBenchmarkRepository.cs @@ -36,6 +36,8 @@ public async Task> LoadBenchmarkSnap return null; int? activeImatrixId = await ResolveActiveImatrixIdAsync(db, scopedAiModelHashId.Value, ct); + if (Cache.IsImatrixAvailable && activeImatrixId == null) + return null; int architectureFamilyId = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); int tensorGroupProfileId = TensorGroupProfileService.RequireCurrentProfileId(); @@ -46,6 +48,7 @@ public async Task> LoadBenchmarkSnap .Where(x => x.ArchitectureFamilyId == architectureFamilyId) .Where(x => x.TensorGroupProfileId == tensorGroupProfileId) .Where(x => x.AiModelHashId == scopedAiModelHashId.Value) + .Where(x => x.ImatrixDefinitionId == activeImatrixId) .Where(x => x.TensorCombo.BaseQuant == config.BaseQuant) .Where(x => x.TensorCombo.Embeddings == config.Embeddings) .Where(x => x.TensorCombo.LmHead == config.LmHead) @@ -61,23 +64,21 @@ public async Task> LoadBenchmarkSnap if (rows.Count == 0) return null; - AiBenchmark chosen = rows - .OrderByDescending(x => activeImatrixId != null && x.ImatrixDefinitionId == activeImatrixId.Value) - .ThenByDescending(x => x.ImatrixDefinitionId != null) - .ThenBy(x => x.Id) - .First(); + AiBenchmark chosen = rows.OrderBy(x => x.Id).First(); - var general = chosen.CategorBenchmarks.FirstOrDefault(x => x.Category == (byte)BenchmarkCategory.General) - ?? chosen.CategorBenchmarks.OrderBy(x => x.Category).FirstOrDefault(); + var general = chosen.CategorBenchmarks.FirstOrDefault(x => x.Category == (byte)BenchmarkCategory.General); if (general == null) return null; var quant = (HybridQuant)config; + if (!await BenchmarkEvidenceService.IsCurrentAsync(quant, chosen.EvidenceIdentityHash, ct)) + return null; var sourceBaseline = ResolveSourceBaselineForProvider(quant); return new BenchmarkSnapshotRecord { + EvidenceIdentityHash = chosen.EvidenceIdentityHash, Config = config, Quant = quant, DisplayName = BuildDisplayName(quant), @@ -171,6 +172,8 @@ public async Task> LoadBaseOnlyCarrierSnapshotsAsy return null; int? activeImatrixId = await ResolveActiveImatrixIdAsync(db, scopedAiModelHashId.Value, ct); + if (Cache.IsImatrixAvailable && activeImatrixId == null) + return null; int architectureFamilyId = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); int tensorGroupProfileId = TensorGroupProfileService.RequireCurrentProfileId(); @@ -269,6 +272,8 @@ public async Task> LoadAllBenchmarkSnapshotsForCur return new List(); int? activeImatrixId = await ResolveActiveImatrixIdAsync(db, scopedAiModelHashId.Value, ct); + if (Cache.IsImatrixAvailable && activeImatrixId == null) + return new List(); int architectureFamilyId = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); int tensorGroupProfileId = TensorGroupProfileService.RequireCurrentProfileId(); @@ -280,17 +285,16 @@ public async Task> LoadAllBenchmarkSnapshotsForCur .Where(x => x.TensorGroupProfileId == tensorGroupProfileId) .Where(x => x.AiModelHashId == scopedAiModelHashId.Value); - if (strictImatrixContext) - query = query.Where(x => x.ImatrixDefinitionId == activeImatrixId); + // Current measured truth never falls back to another calibration context. + // The parameter remains for source compatibility; historical comparisons need a distinct API. + query = query.Where(x => x.ImatrixDefinitionId == activeImatrixId); var rows = await query.ToListAsync(ct); var result = new List(); foreach (var benchmark in rows) { - var metric = benchmark.CategorBenchmarks.FirstOrDefault(x => x.Category == category) - ?? benchmark.CategorBenchmarks.FirstOrDefault(x => x.Category == (byte)BenchmarkCategory.General) - ?? benchmark.CategorBenchmarks.OrderBy(x => x.Category).FirstOrDefault(); + var metric = benchmark.CategorBenchmarks.FirstOrDefault(x => x.Category == category); if (metric == null) continue; @@ -309,10 +313,20 @@ public async Task> LoadAllBenchmarkSnapshotsForCur moeRouter: combo.MoeRouter); var quant = (HybridQuant)config; + string domain = (BenchmarkCategory)category switch + { + BenchmarkCategory.General => "general", + BenchmarkCategory.Code => "code", + BenchmarkCategory.Math => "math", + _ => throw new ArgumentOutOfRangeException(nameof(category)) + }; + if (!await BenchmarkEvidenceService.IsCurrentAsync(quant, benchmark.EvidenceIdentityHash, ct, [domain])) + continue; var sourceBaseline = ResolveSourceBaselineForProvider(quant); result.Add(new BenchmarkSnapshotRecord { + EvidenceIdentityHash = benchmark.EvidenceIdentityHash, Config = config, Quant = quant, DisplayName = BuildDisplayName(quant), @@ -496,13 +510,16 @@ public static string BuildDisplayName(HybridQuant quant) private static async Task ResolveActiveImatrixIdAsync(MagicQuantContext db, uint scopedAiModelHashId, CancellationToken ct) { - if (!Cache.IsImatrixAvailable || string.IsNullOrWhiteSpace(Cache.ActiveImatrixIdentityHash)) + if (!Cache.IsImatrixAvailable) return null; + var activeHash = await ImatrixIdentityService.EnsureActiveImatrixIdentityHashAsync(ct); + if (string.IsNullOrWhiteSpace(activeHash)) return null; + return await db.ImatrixDefinitions .AsNoTracking() .Where(x => x.AiModelHashId == scopedAiModelHashId) - .Where(x => x.IdentityHash == Cache.ActiveImatrixIdentityHash) + .Where(x => x.IdentityHash == activeHash) .Select(x => (int?)x.Id) .FirstOrDefaultAsync(ct); } diff --git a/src/MagicQuant/Services/ImatrixIdentityService.cs b/src/MagicQuant/Services/ImatrixIdentityService.cs index d4b8f8a..f210162 100644 --- a/src/MagicQuant/Services/ImatrixIdentityService.cs +++ b/src/MagicQuant/Services/ImatrixIdentityService.cs @@ -10,18 +10,22 @@ public static class ImatrixIdentityService { public static async Task EnsureActiveImatrixIdentityHashAsync(CancellationToken ct = default) { - if (!Cache.IsImatrixAvailable || string.IsNullOrWhiteSpace(Cache.ActiveImatrixPath)) + if (!Cache.IsImatrixAvailable) { Cache.ActiveImatrixIdentityHash = null; return null; } - if (!string.IsNullOrWhiteSpace(Cache.ActiveImatrixIdentityHash)) - return Cache.ActiveImatrixIdentityHash; + if (string.IsNullOrWhiteSpace(Cache.ActiveImatrixPath)) + { + // An explicit hash selects known historical evidence for read-only diagnostics. + // New benchmark creation separately requires the actual calibration bytes. + if (Cache.ActiveImatrixIdentityHash is { Length: 64 } hash && hash.All(Uri.IsHexDigit)) + return Cache.ActiveImatrixIdentityHash = hash.ToLowerInvariant(); + throw new InvalidOperationException("Active imatrix needs an existing --imatrix-path or a valid SHA-256 --imatrix-identity-hash for recorded evidence reads."); + } - await using var stream = File.OpenRead(Cache.ActiveImatrixPath); - var hash = await SHA256.HashDataAsync(stream, ct); - Cache.ActiveImatrixIdentityHash = Convert.ToHexString(hash).ToLowerInvariant(); + Cache.ActiveImatrixIdentityHash = await BenchmarkEvidenceService.HashFileAsync(Cache.ActiveImatrixPath, ct); return Cache.ActiveImatrixIdentityHash; } @@ -44,6 +48,9 @@ public static class ImatrixIdentityService if (!createIfMissing) return null; + if (string.IsNullOrWhiteSpace(Cache.ActiveImatrixPath)) + throw new InvalidOperationException("Cannot create an imatrix definition from a hash-only context. Supply the actual imatrix path."); + var row = new ImatrixDefinition { AiModelHashId = aiModelHashId, diff --git a/src/MagicQuant/Services/IsolationOptimizationService.cs b/src/MagicQuant/Services/IsolationOptimizationService.cs index f47fc04..57fea20 100644 --- a/src/MagicQuant/Services/IsolationOptimizationService.cs +++ b/src/MagicQuant/Services/IsolationOptimizationService.cs @@ -54,6 +54,7 @@ public sealed class IsolationOptimizationResult public List GroupDetails { get; set; } = new(); public List BadTradeDetails { get; set; } = new(); public List SynergySecondChanceDetails { get; set; } = new(); + public IReadOnlyList KldSizeRescueCandidates { get; set; } = Array.Empty(); } public sealed class IsolationBadTradeRecord @@ -367,6 +368,33 @@ public async Task AnalyzeAndApplyFinalAsync( result.GroupDetails.Add(decision); } + // Retain the bounded, favorable size/KLD exclusions as evidence. No runtime + // bans are changed; only the opt-in selection stage may test local swaps. + result.KldSizeRescueCandidates = IsolationRescuePlanner.Select( + retainedBadTradeEliminations + .Where(x => RuntimeSearchSpace.IsCombinationCandidateRuntimeBannedForGroup(x.Group, x.Removed.CandidateBaseline)) + .Where(x => !groupWorkItems.First(w => w.Group.UniqueId == x.Group.UniqueId).Candidates.Any(other => + other.CandidateBaseline.UniqueId != x.Removed.CandidateBaseline.UniqueId && + IsolationRescuePlanner.IsSizeKldImprovement(other.SizeBytes, other.Kld, + x.Removed.SizeBytes, x.Removed.Kld, IsolationPruningConfig.FloatingPointEpsilon))) + .Select(x => new IsolationRescueCandidate + { + GroupId = x.Group.UniqueId, + GroupName = x.Group.Name, + CandidateBaselineId = x.Removed.CandidateBaseline.UniqueId, + CandidateName = x.Removed.CandidateBaseline.Names[0], + AnchorBaselineId = x.Anchor.CandidateBaseline.UniqueId, + AnchorName = x.Anchor.CandidateBaseline.Names[0], + CandidateSizeBytes = x.Removed.SizeBytes, + CandidateKld = x.Removed.Kld, + AnchorSizeBytes = x.Anchor.SizeBytes, + AnchorKld = x.Anchor.Kld, + OriginalRemovalReason = x.Reason + }), + Config.Current.IsolationPruning.KldSizeRescueMaxCandidatesPerGroup, + IsolationPruningConfig.FloatingPointEpsilon); + result.Notes.Add($"Retained {result.KldSizeRescueCandidates.Count} isolated size/KLD rescue candidate(s); global bans unchanged; contextual testing enabled={Config.Current.IsolationPruning.KldSizeRescueEnabled}."); + var baseOnlyPlans = fullPlan.Plans .Where(x => x.Kind == RequiredSampleKind.BaseOnlyIsolation) .Where(x => x.Key.StartsWith("baseonly:", StringComparison.Ordinal)) @@ -1041,6 +1069,8 @@ private static bool ShouldEliminateAsBadTrade(GroupCandidateEvaluation anchor, G return null; var imatrixDefinitionId = await ImatrixIdentityService.ResolveCurrentImatrixDefinitionIdAsync(db, exactAiModelHashId.Value, createIfMissing: false, ct); + if (Cache.IsImatrixAvailable && imatrixDefinitionId == null) + return null; int architectureFamilyId = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); int tensorGroupProfileId = TensorGroupProfileService.RequireCurrentProfileId(); var lookup = (TensorConfig)quant; @@ -1068,7 +1098,7 @@ private static bool ShouldEliminateAsBadTrade(GroupCandidateEvaluation anchor, G x.c.MoeRouter == lookup.MoeRouter, ct); - if (row == null) + if (row == null || !await BenchmarkEvidenceService.IsCurrentAsync(quant, row.b.EvidenceIdentityHash, ct)) return null; return new BenchmarkSnapshot @@ -1446,4 +1476,4 @@ private sealed class CategorySnapshot public double Ppl { get; set; } public double PplError { get; set; } } -} \ No newline at end of file +} diff --git a/src/MagicQuant/Services/IsolationRescuePlanner.cs b/src/MagicQuant/Services/IsolationRescuePlanner.cs new file mode 100644 index 0000000..f27e8f7 --- /dev/null +++ b/src/MagicQuant/Services/IsolationRescuePlanner.cs @@ -0,0 +1,99 @@ +using MagicQuant.Models; +using MQ.DB.Models; + +namespace MagicQuant.Services; + +/// A heuristic exclusion retained for bounded contextual testing, never a global unban. +public sealed record IsolationRescueCandidate +{ + public byte GroupId { get; init; } + public string GroupName { get; init; } = string.Empty; + public byte CandidateBaselineId { get; init; } + public string CandidateName { get; init; } = string.Empty; + public byte AnchorBaselineId { get; init; } + public string AnchorName { get; init; } = string.Empty; + public ulong CandidateSizeBytes { get; init; } + public double CandidateKld { get; init; } + public ulong AnchorSizeBytes { get; init; } + public double AnchorKld { get; init; } + public string OriginalRemovalReason { get; init; } = string.Empty; +} + +internal sealed record IsolationRescuePlan( + IsolationRescueCandidate Evidence, + BenchmarkSnapshotRecord Incumbent, + HybridQuant Quant); + +internal static class IsolationRescuePlanner +{ + public static bool IsSizeKldImprovement( + ulong candidateSize, double candidateKld, ulong anchorSize, double anchorKld, double epsilon) => + candidateSize > 0 && anchorSize > 0 && double.IsFinite(candidateKld) && double.IsFinite(anchorKld) && + candidateKld >= 0d && anchorKld >= 0d && candidateSize <= anchorSize && candidateKld <= anchorKld && + (candidateSize < anchorSize || candidateKld + Math.Max(0d, epsilon) < anchorKld); + + public static IReadOnlyList Select( + IEnumerable candidates, int maxPerGroup, double epsilon) + { + if (maxPerGroup <= 0) + return Array.Empty(); + + return candidates + .Where(x => x.CandidateBaselineId != x.AnchorBaselineId && + IsSizeKldImprovement(x.CandidateSizeBytes, x.CandidateKld, x.AnchorSizeBytes, x.AnchorKld, epsilon)) + .DistinctBy(x => (x.GroupId, x.CandidateBaselineId)) + .GroupBy(x => x.GroupId) + .SelectMany(g => g.OrderByDescending(x => x.AnchorKld - x.CandidateKld) + .ThenBy(x => x.CandidateSizeBytes).ThenBy(x => x.CandidateBaselineId) + .Take(Math.Clamp(maxPerGroup, 0, 16))) + .OrderByDescending(x => x.AnchorKld - x.CandidateKld) + .ThenBy(x => x.GroupId).ThenBy(x => x.CandidateBaselineId) + .ToList(); + } + + public static IReadOnlyList BuildPlans( + IReadOnlyList candidates, + IReadOnlyList incumbents, + int maxProbes, + IReadOnlyList activeGroups) + { + if (maxProbes <= 0 || candidates.Count == 0 || incumbents.Count == 0) + return Array.Empty(); + + // Visit low, high, then intermediate byte budgets. Do not adapt this order + // to outcomes within the batch or let one incumbent consume the whole cap. + var ordered = incumbents.DistinctBy(x => TensorConfigIdentity.ToKey(x.Config)) + .OrderBy(x => x.SizeBytes).ThenBy(x => x.Kld).ToList(); + var contextOrder = new List { ordered[0] }; + if (ordered.Count > 1) contextOrder.Add(ordered[^1]); + if (ordered.Count > 2) contextOrder.Add(ordered[ordered.Count / 2]); + contextOrder.AddRange(ordered); + + var seen = incumbents.Select(x => TensorConfigIdentity.ToKey(x.Config)).ToHashSet(StringComparer.Ordinal); + var plans = new List(); + foreach (var candidate in candidates) + { + foreach (var incumbent in contextOrder.DistinctBy(x => TensorConfigIdentity.ToKey(x.Config))) + { + var effective = RankSafeKldPredictionService.EnumerateEffectiveBaselines(incumbent.Config, activeGroups) + .ToDictionary(x => x.Group.UniqueId, x => x.EffectiveBaselineId); + var group = activeGroups.FirstOrDefault(x => x.UniqueId == candidate.GroupId); + // Test the specific isolated comparison in a real surrounding context. + // Do not extrapolate it into an arbitrary different group state. + if (group == null || !effective.TryGetValue(group.UniqueId, out byte currentId) || + currentId != candidate.AnchorBaselineId) + continue; + + var quant = new HybridQuant(incumbent.Config); + quant.SetLearnedCandidateOverride(group, BaselineQuants.FromId(candidate.CandidateBaselineId)); + if (!seen.Add(TensorConfigIdentity.ToKey((TensorConfig)quant))) + continue; + + plans.Add(new IsolationRescuePlan(candidate, incumbent, quant)); + if (plans.Count >= Math.Clamp(maxProbes, 0, 128)) + return plans; + } + } + return plans; + } +} diff --git a/src/MagicQuant/Services/MeasuredFrontierArchive.cs b/src/MagicQuant/Services/MeasuredFrontierArchive.cs new file mode 100644 index 0000000..31d7dea --- /dev/null +++ b/src/MagicQuant/Services/MeasuredFrontierArchive.cs @@ -0,0 +1,99 @@ +using MagicQuant.Models; +using MQ.DB.Models; +using MQ.DB.Models.DbModels; + +namespace MagicQuant.Services; + +internal static class MeasuredFrontierArchive +{ + public static bool HasValidMetrics(BenchmarkSnapshotRecord snapshot) => + snapshot.SizeBytes > 0 && double.IsFinite(snapshot.Kld) && snapshot.Kld >= 0d && + double.IsFinite(snapshot.Ppl) && snapshot.Ppl > 0d; + + public static IReadOnlyList Measurements(IEnumerable snapshots) => + snapshots.Where(HasValidMetrics) + .GroupBy(x => TensorConfigIdentity.ToKey(x.Config), StringComparer.Ordinal) + // Retain the last current observation, never select the most optimistic + // repeated measurement merely because it has the lowest KLD. + .Select(g => g.Last()) + .OrderBy(x => x.SizeBytes).ThenBy(x => x.Kld) + .ToList(); + + public static IReadOnlyList Frontier(IEnumerable snapshots) => + new FinalRealBenchmarkEliminationService().Eliminate(Measurements(snapshots).ToList()).Survivors; +} + +internal sealed record ContextualEvidenceResolution( + Guid ObservationId, string Role, string ConfigKey, double? RecordedKld, + string Status, BenchmarkSnapshotRecord? Snapshot); + +internal sealed record ContextualMeasurementSet( + IReadOnlyList Snapshots, + IReadOnlyList Resolutions, + BenchmarkSnapshotRecord? BestBeneficialProbe); + +internal static class ContextualMeasurementReconciler +{ + public static async Task ResolveAsync( + IEnumerable observations, + Func> loadCurrentSnapshot, + CancellationToken ct) + { + var resolutions = new List(); + var currentByKey = new Dictionary(StringComparer.Ordinal); + var beneficial = new List<(double Gain, BenchmarkSnapshotRecord Snapshot)>(); + + foreach (var observation in observations.Where(x => x.IsContextualAnomalyProbe && !x.OldBf16Isolation && x.AllActiveGroupsExplicit)) + { + // Accepted/classification describe the hypothesis, not whether either + // measured artifact is useful on the size/KLD frontier. + await ResolveSide(observation.ReferenceTensorCombo, observation.ReferenceTensorConfigKey, + observation.ReferenceActualKld, "reference"); + var probe = await ResolveSide(observation.ProbeTensorCombo, observation.ProbeTensorConfigKey, + observation.ActualKld, "probe"); + if (probe != null && observation.Accepted && + observation.RuleDirection == AnomalyRuleDirection.Beneficial.ToString()) + beneficial.Add((observation.ActualGainVsTwin, probe)); + + async Task ResolveSide(TensorCombo? combo, string recordedKey, double recordedKld, string role) + { + ct.ThrowIfCancellationRequested(); + if (combo == null) + { + resolutions.Add(new(observation.Id, role, recordedKey, null, "missing_configuration", null)); + return null; + } + + var config = new TensorConfig(combo.BaseQuant, combo.Embeddings, combo.LmHead, combo.AttnQ, + combo.AttnKV, combo.AttnOutput, combo.FfnUpGate, combo.FfnDown, combo.MoeExperts, combo.MoeRouter); + string key = TensorConfigIdentity.ToKey(config); + if (!string.IsNullOrWhiteSpace(recordedKey) && !string.Equals(recordedKey, key, StringComparison.Ordinal)) + { + resolutions.Add(new(observation.Id, role, key, double.IsFinite(recordedKld) ? recordedKld : null, + "observation_configuration_mismatch", null)); + return null; + } + + if (!currentByKey.TryGetValue(key, out var snapshot)) + currentByKey[key] = snapshot = await loadCurrentSnapshot(config, ct); + + string status = snapshot == null || !MeasuredFrontierArchive.HasValidMetrics(snapshot) || + TensorConfigIdentity.ToKey(snapshot.Config) != key + ? "current_measurement_unavailable_or_incompatible" + : !double.IsFinite(recordedKld) || recordedKld < 0d || + Math.Abs(snapshot.Kld - recordedKld) > Math.Max(1e-12d, Math.Abs(recordedKld) * 1e-9d) + ? "observation_kld_mismatch" + : "included"; + + var included = status == "included" ? snapshot : null; + resolutions.Add(new(observation.Id, role, key, double.IsFinite(recordedKld) ? recordedKld : null, status, included)); + return included; + } + } + + return new ContextualMeasurementSet( + MeasuredFrontierArchive.Measurements(resolutions.Where(x => x.Snapshot != null).Select(x => x.Snapshot!)), + resolutions, + beneficial.OrderByDescending(x => x.Gain).ThenBy(x => x.Snapshot.Kld).Select(x => x.Snapshot).FirstOrDefault()); + } +} diff --git a/src/MagicQuant/Services/PredictionDiagnosticContextService.cs b/src/MagicQuant/Services/PredictionDiagnosticContextService.cs new file mode 100644 index 0000000..f48eda1 --- /dev/null +++ b/src/MagicQuant/Services/PredictionDiagnosticContextService.cs @@ -0,0 +1,86 @@ +using MagicQuant.Helpers; +using MagicQuant.Models; +using Microsoft.EntityFrameworkCore; +using MQ.DB; +using MQ.DB.Data; +using MQ.DB.Models; +using MQ.DB.Models.DbModels; +using Spectre.Console; + +namespace MagicQuant.Services; + +/// +/// Hydrates an existing campaign for diagnostics without creating/activating a +/// tensor-group profile, syncing external repositories, or running benchmarks. +/// +internal static class PredictionDiagnosticContextService +{ + public static async Task InitializeAsync(CancellationToken ct = default) + { + Cache.CurrentArchitectureFamilyId = null; + Cache.CurrentTensorGroupProfileId = null; + Cache.CurrentTensorGroupProfileFingerprintHash = null; + + await using var db = new MagicQuantContext(); + var mapping = await db.Set().AsNoTracking() + .Include(x => x.ArchitectureFamily) + .Where(x => x.AiModelHash.UniqueHash == Cache.CurrentModelId) + .SingleOrDefaultAsync(ct) + ?? throw new InvalidOperationException( + "Prediction diagnostics require an existing architecture-family mapping for this exact model. Run the campaign initialization first."); + var family = mapping.ArchitectureFamily; + var profiles = await db.TensorGroupProfiles.AsNoTracking() + .Where(x => x.ArchitectureFamilyId == family.Id).ToListAsync(ct); + var definitions = await db.BaselineQuantDefinitions.AsNoTracking() + .Where(x => x.ArchitectureFamilyId == family.Id && x.IsCustomBaseline).ToListAsync(ct); + + var paths = new ModelArtifactPathService(); + var metadata = await new GgufMetadataReader(new PythonManager(Cache.MagicQuantDirectory!)) + .ReadAsync(paths.GetNativeBaseGgufPath(), + Path.Combine(paths.ModelMagicQuantDirectory, "PredictionDiagnostics", "metadata"), ct); + InitializeFromExistingRows(family, profiles, definitions, metadata.TensorNames); + + AnsiConsole.MarkupLine($"[green]Prediction diagnostic context:[/] family={Markup.Escape(family.DisplayName)}, profile={Cache.CurrentTensorGroupProfileId}, active groups={TReg.All.Length - Cache.UnusedTensorGroups.Count}, historical custom baselines={definitions.Count}"); + } + + internal static void InitializeFromExistingRows( + ArchitectureFamily family, + IReadOnlyList profiles, + IReadOnlyList definitions, + IReadOnlyCollection nativeTensorNames) + { + if (!string.IsNullOrWhiteSpace(Cache.CurrentArchitectureFamilyName) && + !string.Equals(Cache.CurrentArchitectureFamilyName.Trim(), family.DisplayName.Trim(), StringComparison.OrdinalIgnoreCase) && + !string.Equals(Cache.CurrentArchitectureFamilyNormalizedName, family.NormalizedName, StringComparison.Ordinal)) + throw new InvalidOperationException( + $"The exact model is mapped to architecture family '{family.DisplayName}', which differs from the requested family. Diagnostics do not create or override model-family links."); + + string snapshot = TensorGroupProfileService.BuildSnapshotJson(); + string fingerprint = TensorGroupProfileService.ComputeSnapshotHash(snapshot); + var profile = profiles.SingleOrDefault(x => x.ArchitectureFamilyId == family.Id && x.FingerprintHash == fingerprint) + ?? throw new InvalidOperationException( + "No existing tensor-group profile matches the current YAML rules. Use the campaign's original grouping configuration; diagnostics do not create or activate profiles."); + + string signature = TensorConfigIdentity.StableHash(string.Join("\n", nativeTensorNames.OrderBy(x => x, StringComparer.Ordinal))); + if (nativeTensorNames.Count == 0 || family.TensorCount != nativeTensorNames.Count || + !string.Equals(family.TensorSignatureHash, signature, StringComparison.Ordinal)) + throw new InvalidOperationException("The existing native GGUF tensor names do not match the registered architecture family."); + + var custom = definitions.Where(x => x.IsCustomBaseline && x.ArchitectureFamilyId == family.Id) + .Select(x => BaselineDefinitionResolver.ToRuntimeBaseline(x, forceInactiveRegistration: true)).ToList(); + var activeGroupIds = nativeTensorNames.SelectMany(name => TReg.FindMatchingGroups(name)) + .Select(x => x.UniqueId).ToHashSet(); + if (activeGroupIds.Count == 0) + throw new InvalidOperationException("No current tensor groups match the existing native GGUF."); + + BaselineQuants.ResetDynamicCustomBaselines(); + foreach (var baseline in custom) + BaselineQuants.RegisterDynamicCustomBaseline(baseline); + Cache.CurrentArchitectureFamilyId = family.Id; + Cache.CurrentArchitectureFamilyName = family.DisplayName; + Cache.CurrentTensorGroupProfileId = profile.Id; + Cache.CurrentTensorGroupProfileFingerprintHash = profile.FingerprintHash; + Cache.UnusedTensorGroups.Clear(); + Cache.UnusedTensorGroups.AddRange(TReg.All.Where(x => !activeGroupIds.Contains(x.UniqueId))); + } +} diff --git a/src/MagicQuant/Services/PredictionGuidedHybridSelectionService.cs b/src/MagicQuant/Services/PredictionGuidedHybridSelectionService.cs index 0dbf32c..ab1b602 100644 --- a/src/MagicQuant/Services/PredictionGuidedHybridSelectionService.cs +++ b/src/MagicQuant/Services/PredictionGuidedHybridSelectionService.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using MagicQuant.Helpers; using MagicQuant.Models; using MagicQuant.Services.Progress; using Microsoft.EntityFrameworkCore; @@ -51,7 +52,8 @@ public PredictionGuidedHybridSelectionService( public async Task RunAsync( IReadOnlyList pureBaselineSnapshots, - CancellationToken ct = default) + CancellationToken ct = default, + IReadOnlyList? isolationRescueCandidates = null) { var eliminationRecords = new List(); var validationFailures = new List(); @@ -78,13 +80,30 @@ public async Task RunAsync( var interior = await RunInteriorSubspaceDiscoveryAsync(current, predictedAnchors, validationFailures, validationAttempts, phaseDiagnostics, ct); current = MergeAndDominanceFilter(current, interior.AcceptedSnapshots, eliminationRecords, "interior subspace discovery dominated by real benchmark truth"); - var bestConfirmedAnomaly = await LoadBestConfirmedBeneficialAnomalySnapshotAsync(ct); - if (bestConfirmedAnomaly != null && current.All(x => TensorConfigIdentity.ToKey(x.Config) != TensorConfigIdentity.ToKey(bestConfirmedAnomaly.Config))) + var contextualMeasurements = await LoadContextualMeasurementsAsync(ct); + var bestConfirmedAnomaly = contextualMeasurements.BestBeneficialProbe; + if (contextualMeasurements.Snapshots.Count > 0) { - AnsiConsole.MarkupLine($"[yellow]Best confirmed anomaly reconciliation:[/] adding probe-confirmed anomaly to final frontier consideration: [cyan]{Markup.Escape(bestConfirmedAnomaly.DisplayName)}[/]"); - current = MergeAndDominanceFilter(current, new[] { bestConfirmedAnomaly }, eliminationRecords, "best confirmed beneficial anomaly included for final reconciliation"); + AnsiConsole.MarkupLine($"[yellow]Contextual measurement reconciliation:[/] considering [cyan]{contextualMeasurements.Snapshots.Count:N0}[/] compatible measured probes/references, including rejected hypotheses and harmful references."); + current = MergeAndDominanceFilter(current, contextualMeasurements.Snapshots, eliminationRecords, + "compatible measured contextual probe/reference included for final reconciliation"); } + var rescueQueue = isolationRescueCandidates ?? Array.Empty(); + var rescue = await RunIsolationRescueAsync(current, rescueQueue, ct); + current = MergeAndDominanceFilter(current, rescue.Snapshots, eliminationRecords, + "opt-in isolated size/KLD rescue evaluated in a measured context"); + + // The scientific archive is independent of selection gates and release spacing. + // The repository enforces current artifact/evaluation identity for every row. + var allCurrentMeasurements = await _repository.LoadAllBenchmarkSnapshotsForCurrentContextAsync(ct: ct); + var measuredSnapshots = MeasuredFrontierArchive.Measurements(allCurrentMeasurements + .Concat(pureBaselineSnapshots) + .Concat(validationAttempts.Select(x => x.Snapshot).OfType()) + .Concat(contextualMeasurements.Snapshots) + .Concat(rescue.Snapshots)); + var unspacedFrontier = MeasuredFrontierArchive.Frontier(measuredSnapshots); + current = ApplyMeaningfulSpacing(current, eliminationRecords); var finalDominance = _finalEliminator.Eliminate(current); @@ -105,11 +124,15 @@ public async Task RunAsync( } await WriteAnomalySelectionReconciliationAsync(finalDominance.Survivors, bestConfirmedAnomaly, ct); + await WriteMeasuredFrontierArchiveAsync(measuredSnapshots, unspacedFrontier, finalDominance.Survivors, + contextualMeasurements, rescueQueue, rescue.Attempts, ct); await WriteSelectionPhaseDiagnosticsAsync(phaseDiagnostics, validationFailures, validationAttempts, ct); return new PredictionGuidedSelectionResult { Survivors = finalDominance.Survivors.ToList(), + MeasuredSnapshots = measuredSnapshots, + UnspacedFrontier = unspacedFrontier, Eliminations = eliminationRecords .DistinctBy(x => $"{TensorConfigIdentity.ToKey(x.Eliminated.Config)}::{TensorConfigIdentity.ToKey(x.Eliminator.Config)}::{NormalizePublicEliminationReason(x.Reason)}") .ToList(), @@ -282,7 +305,7 @@ private async Task RunStrictDominanceReplacementAsync( PrintSelectionLadderNotes(selection.Notes); if (deterministicEligibleCount == 0) - AnsiConsole.MarkupLine($"[yellow]Strict dominance skipped builds for {Markup.Escape(anchor.DisplayName)}:[/] no physically eligible predicted candidates remained after deterministic size/KLD filters."); + AnsiConsole.MarkupLine($"[yellow]Strict dominance skipped builds for {Markup.Escape(anchor.DisplayName)}:[/] no predicted candidates met the deterministic size/KLD filters."); if (candidates.Count == 0) { @@ -423,50 +446,119 @@ private async Task TryRunSmartStrictFallbackAsync( - private async Task LoadBestConfirmedBeneficialAnomalySnapshotAsync(CancellationToken ct) + private async Task LoadContextualMeasurementsAsync(CancellationToken ct) { - if (!Config.AnomalyDetection.Enabled) - return null; - await using var db = new MagicQuantContext(); var modelHashId = await ArchitectureFamilyService.ResolveScopedAiModelHashIdOrNullAsync(db, ct); if (modelHashId == null) - return null; + return new ContextualMeasurementSet([], [], null); int architectureFamilyId = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); int tensorGroupProfileId = TensorGroupProfileService.RequireCurrentProfileId(); int? imatrixId = await ImatrixIdentityService.ResolveCurrentImatrixDefinitionIdAsync(db, modelHashId.Value, createIfMissing: false, ct); + if (Cache.IsImatrixAvailable && imatrixId == null) + return new ContextualMeasurementSet([], [], null); - // SQLite cannot translate ulong ordering expressions. Keep the database query - // to filtering/include only, then rank the tiny scoped anomaly observation set - // in LINQ-to-Objects. This preserves the intended ordering without tripping - // Microsoft.Data.Sqlite on SizeSavingsBytes. var observations = await db.AnomalyProbeObservations .AsNoTracking() + .Include(x => x.ReferenceTensorCombo) .Include(x => x.ProbeTensorCombo) .Where(x => x.ArchitectureFamilyId == architectureFamilyId) .Where(x => x.TensorGroupProfileId == tensorGroupProfileId) .Where(x => x.AiModelHashId == modelHashId.Value) .Where(x => x.ImatrixDefinitionId == imatrixId) .Where(x => x.BenchmarkCategory == (byte)BenchmarkCategory.General) - .Where(x => x.RuleDirection == AnomalyRuleDirection.Beneficial.ToString()) - .Where(x => x.Accepted) .Where(x => x.IsContextualAnomalyProbe && !x.OldBf16Isolation && x.AllActiveGroupsExplicit) - .Where(x => x.ProbeTensorCombo != null) .ToListAsync(ct); - var observation = observations - .OrderByDescending(x => x.ActualGainVsTwin) - .ThenBy(x => x.ActualKld) - .ThenByDescending(x => x.SizeSavingsBytes) - .FirstOrDefault(); + return await ContextualMeasurementReconciler.ResolveAsync(observations, + _repository.LoadBenchmarkSnapshotAsync, ct); + } - if (observation?.ProbeTensorCombo == null) - return null; + private async Task<(IReadOnlyList Snapshots, IReadOnlyList Attempts)> RunIsolationRescueAsync( + IReadOnlyList incumbents, + IReadOnlyList queue, + CancellationToken ct) + { + var options = Config.Current.IsolationPruning; + if (!options.KldSizeRescueEnabled || options.KldSizeRescueMaxContextProbesPerRun <= 0) + return (Array.Empty(), Array.Empty()); + + var activeGroups = TReg.All.Where(g => !Cache.UnusedTensorGroups.Any(u => u.UniqueId == g.UniqueId)).ToList(); + var plans = IsolationRescuePlanner.BuildPlans(queue, incumbents, + options.KldSizeRescueMaxContextProbesPerRun, activeGroups); + if (plans.Count == 0) + return (Array.Empty(), Array.Empty()); + + AnsiConsole.MarkupLine($"[yellow]Isolated size/KLD rescue:[/] testing [cyan]{plans.Count}[/] scoped swaps; global bans remain unchanged."); + await _quantizationService.ProcessHybridBatchAsync(plans.Select(x => x.Quant).ToList(), + new StageProgressOptions + { + StageName = "Isolated size/KLD contextual rescue", + Total = plans.Count, + MinimumNonSkippedSamplesBeforeEta = 2, + ShowEta = true, + CountSkippedForEta = false + }, ct); + + var snapshots = new List(); + var attempts = new List(); + foreach (var plan in plans) + { + var snapshot = await _repository.LoadBenchmarkSnapshotAsync((TensorConfig)plan.Quant, ct); + if (snapshot != null && MeasuredFrontierArchive.HasValidMetrics(snapshot)) + snapshots.Add(snapshot); + attempts.Add(new + { + configKey = TensorConfigIdentity.ToKey((TensorConfig)plan.Quant), + contextKey = TensorConfigIdentity.ToKey(plan.Incumbent.Config), + evidence = plan.Evidence, + measured = snapshot != null && MeasuredFrontierArchive.HasValidMetrics(snapshot), + result = snapshot != null && MeasuredFrontierArchive.HasValidMetrics(snapshot) ? ToAnchorLog(snapshot) : null + }); + } + return (snapshots, attempts); + } - var combo = observation.ProbeTensorCombo; - var config = new TensorConfig(combo.BaseQuant, combo.Embeddings, combo.LmHead, combo.AttnQ, combo.AttnKV, combo.AttnOutput, combo.FfnUpGate, combo.FfnDown, combo.MoeExperts, combo.MoeRouter); - return await _repository.LoadBenchmarkSnapshotAsync(config, ct); + private static async Task WriteMeasuredFrontierArchiveAsync( + IReadOnlyList measured, + IReadOnlyList unspaced, + IReadOnlyList curated, + ContextualMeasurementSet contextual, + IReadOnlyList rescueQueue, + IReadOnlyList rescueAttempts, + CancellationToken ct) + { + string directory = string.IsNullOrWhiteSpace(Cache.OutputDirectory) + ? ResolveGgufDirectory() : Path.Combine(Cache.OutputDirectory!, "magicquant-manifest"); + Directory.CreateDirectory(directory); + var frontierKeys = unspaced.Select(x => TensorConfigIdentity.ToKey(x.Config)).ToHashSet(StringComparer.Ordinal); + var curatedKeys = curated.Select(x => TensorConfigIdentity.ToKey(x.Config)).ToHashSet(StringComparer.Ordinal); + var payload = new + { + schemaVersion = 1, + generatedAtUtc = DateTime.UtcNow, + modelId = Cache.CurrentModelId, + imatrixIdentity = Cache.IsImatrixAvailable ? Cache.ActiveImatrixIdentityHash : null, + comparisonPolicy = "current compatible General measurements; existing final KLD/size dominance and equivalent-truth policy; no release spacing", + measuredCount = measured.Count, + unspacedFrontierCount = unspaced.Count, + measurements = measured.Select(x => new + { + observation = ToAnchorLog(x), + slots = new { x.Config.BaseQuant, x.Config.Embeddings, x.Config.LmHead, x.Config.AttnQ, x.Config.AttnKV, + x.Config.AttnOutput, x.Config.FfnUpGate, x.Config.FfnDown, x.Config.MoeExperts, x.Config.MoeRouter }, + onUnspacedFrontier = frontierKeys.Contains(TensorConfigIdentity.ToKey(x.Config)), + inCuratedSelection = curatedKeys.Contains(TensorConfigIdentity.ToKey(x.Config)) + }).ToList(), + contextualReconciliation = contextual.Resolutions.Select(x => new + { x.ObservationId, x.Role, x.ConfigKey, x.RecordedKld, x.Status }).ToList(), + isolatedRescueEnabled = Config.Current.IsolationPruning.KldSizeRescueEnabled, + isolatedRescueQueue = rescueQueue, + isolatedRescueAttempts = rescueAttempts + }; + await File.WriteAllTextAsync(Path.Combine(directory, "magicquant.measured-frontier.json"), + JsonSerializer.Serialize(payload, JsonOptions), ct); } private async Task WriteAnomalySelectionReconciliationAsync( @@ -777,8 +869,12 @@ private async Task RunNearBaselineReplacementAsync( realMax, ct); long rejectedByRealSizeWindow = Math.Max(0, predictedPoolCount - phaseSizeEligiblePool); + long deterministicEligibleCount = await _predictedStore.CountBetterThanLinearCandidatesAsync( + predictedLowerSizeHigherDamage, predictedUpperSizeLowerDamage, + predictionMin, predictionMax, realMin, realMax, ct, + applyNearAnchorRequirement: true); bool diversityEligible = ShouldUseDiversityForWindow(lowerSizeHigherDamage, upperSizeLowerDamage, predictedLowerSizeHigherDamage, predictedUpperSizeLowerDamage); - fetchLimit = ResolveValidationScanLimit(attemptLimit, phaseSizeEligiblePool, diversityEligible); + fetchLimit = ResolveValidationScanLimit(attemptLimit, deterministicEligibleCount, diversityEligible); var rawCandidates = (await _predictedStore.QueryBetterThanLinearCandidatesAsync( lowerSizeHigherDamage, upperSizeLowerDamage, @@ -798,8 +894,7 @@ private async Task RunNearBaselineReplacementAsync( .ToList(); int afterBrutalityCount = brutalityAnalyses.Count(y => y.Brutality.Passed); - long deterministicEligibleCount = afterBrutalityCount; - long rejectedByOtherPhaseDeterministicRules = Math.Max(0, rawCandidates.Count - afterBrutalityCount); + long rejectedByOtherPhaseDeterministicRules = Math.Max(0, phaseSizeEligiblePool - deterministicEligibleCount); var rankedCandidates = brutalityAnalyses .Where(x => x.Brutality.Passed) .Select(x => AttachSelectionDiagnostics( @@ -889,7 +984,7 @@ private async Task RunNearBaselineReplacementAsync( PrintSelectionLadderNotes(selection.Notes); if (deterministicEligibleCount == 0) - AnsiConsole.MarkupLine($"[yellow]Near-baseline window skipped builds:[/] no physically eligible candidates remained after predicted line, real size window, and deterministic brutality filters."); + AnsiConsole.MarkupLine($"[yellow]Near-baseline window skipped builds:[/] no predicted candidates met the line, size-window, and near-anchor gain requirements."); if (rejectedByBrutality.Count > 0) AnsiConsole.MarkupLine($"[grey] rejected by near-lower-anchor brutality preview:[/] [cyan]{rejectedByBrutality.Count:N0}[/] (see magicquant-selection-phase-diagnostics.json)"); @@ -1023,7 +1118,7 @@ private async Task RunInteriorSubspaceDiscoveryAsync( int interiorAttemptLimit = Math.Max(1, Math.Max(Config.SelectionMaxCandidatesPerInteriorWindow, Config.SelectionMaxFallbackAttemptsPerAnchor)); int interiorFetchLimit = ResolveValidationScanLimit(interiorAttemptLimit, long.MaxValue, diversityEligible: Config.SelectionDiversifyValidationCandidates); - AnsiConsole.MarkupLine($"[grey]Interior neighbor pairs:[/] [cyan]{pairs.Count:N0}[/] | window fractions=[cyan]{Markup.Escape(string.Join(", ", fractions.Select(x => x.ToString("0.###"))))}[/] | candidates/window=[cyan]{Config.SelectionMaxCandidatesPerInteriorWindow:N0}[/] | fallback attempts/window=[cyan]{Config.SelectionMaxFallbackAttemptsPerAnchor:N0}[/] | validation attempts/window=[cyan]{interiorAttemptLimit:N0}[/] | max scan/window=[cyan]{interiorFetchLimit:N0}[/]"); + AnsiConsole.MarkupLine($"[grey]Interior neighbor pairs:[/] [cyan]{pairs.Count:N0}[/] | window fractions=[cyan]{Markup.Escape(string.Join(", ", fractions.Select(x => x.ToString("0.###"))))}[/] | complete coverage=[cyan]{Config.SelectionCompleteInteriorCoverage}[/] | candidates/window=[cyan]{Config.SelectionMaxCandidatesPerInteriorWindow:N0}[/] | fallback attempts/window=[cyan]{Config.SelectionMaxFallbackAttemptsPerAnchor:N0}[/] | validation attempts/window=[cyan]{interiorAttemptLimit:N0}[/] | max scan/window=[cyan]{interiorFetchLimit:N0}[/]"); var allCandidates = new List(); int globalWindowIndex = 0; @@ -1050,8 +1145,6 @@ private async Task RunInteriorSubspaceDiscoveryAsync( LogPredictionAndRealPairLines(pair.HigherDamageSmaller, pair.LowerDamageLarger, predictedHigherDamageSmaller, predictedLowerDamageLarger, "Interior pair"); - ulong realSpan = realHighSize - realLowSize; - ulong predictionSpan = predictionHighSize - predictionLowSize; ulong realCursor = realLowSize; ulong predictionCursor = predictionLowSize; @@ -1061,15 +1154,12 @@ private async Task RunInteriorSubspaceDiscoveryAsync( if (fraction <= 0d) continue; - ulong realWidth = (ulong)Math.Round(realSpan * fraction, MidpointRounding.AwayFromZero); - ulong predictionWidth = (ulong)Math.Round(predictionSpan * fraction, MidpointRounding.AwayFromZero); - if (realWidth == 0 || predictionWidth == 0) - continue; - ulong realMin = realCursor; - ulong realMax = Math.Min(realHighSize, realCursor + realWidth); + ulong realMax = InteriorWindowPlanner.End(realLowSize, realHighSize, realCursor, + fraction, i == fractions.Count - 1, Config.SelectionCompleteInteriorCoverage); ulong predictionMin = predictionCursor; - ulong predictionMax = Math.Min(predictionHighSize, predictionCursor + predictionWidth); + ulong predictionMax = InteriorWindowPlanner.End(predictionLowSize, predictionHighSize, predictionCursor, + fraction, i == fractions.Count - 1, Config.SelectionCompleteInteriorCoverage); if (realMax <= realMin || predictionMax <= predictionMin) continue; @@ -1088,8 +1178,12 @@ private async Task RunInteriorSubspaceDiscoveryAsync( realMax, ct); long rejectedByRealSizeWindow = Math.Max(0, predictedPoolCount - phaseSizeEligiblePool); + long deterministicEligibleCount = await _predictedStore.CountBetterThanLinearCandidatesAsync( + predictedHigherDamageSmaller, predictedLowerDamageLarger, + predictionMin, predictionMax, realMin, realMax, ct, + applyNearAnchorRequirement: true); bool diversityEligible = ShouldUseDiversityForWindow(pair.HigherDamageSmaller, pair.LowerDamageLarger, predictedHigherDamageSmaller, predictedLowerDamageLarger); - interiorFetchLimit = ResolveValidationScanLimit(interiorAttemptLimit, phaseSizeEligiblePool, diversityEligible); + interiorFetchLimit = ResolveValidationScanLimit(interiorAttemptLimit, deterministicEligibleCount, diversityEligible); var rawCandidates = (await _predictedStore.QueryBetterThanLinearCandidatesAsync( pair.HigherDamageSmaller, @@ -1110,8 +1204,7 @@ private async Task RunInteriorSubspaceDiscoveryAsync( .ToList(); int afterBrutalityCount = brutalityAnalyses.Count(y => y.Brutality.Passed); - long deterministicEligibleCount = afterBrutalityCount; - long rejectedByOtherPhaseDeterministicRules = Math.Max(0, rawCandidates.Count - afterBrutalityCount); + long rejectedByOtherPhaseDeterministicRules = Math.Max(0, phaseSizeEligiblePool - deterministicEligibleCount); var rankedCandidates = brutalityAnalyses .Where(x => x.Brutality.Passed) @@ -1202,7 +1295,7 @@ private async Task RunInteriorSubspaceDiscoveryAsync( PrintSelectionLadderNotes(selection.Notes); if (deterministicEligibleCount == 0) - AnsiConsole.MarkupLine($"[yellow]Interior window skipped builds:[/] no physically eligible candidates remained after predicted nonlinear line, real size slice, and deterministic brutality filters."); + AnsiConsole.MarkupLine($"[yellow]Interior window skipped builds:[/] no predicted candidates met the line, size-window, and near-anchor gain requirements."); realCursor = realMax; predictionCursor = predictionMax; @@ -2143,11 +2236,9 @@ private static BrutalityAnalysis AnalyzeNearLowerAnchorBrutality(HybridSelection }; } - ulong span = lowerDamagePredictionAnchor.PredictedSizeBytes > higherDamagePredictionAnchor.PredictedSizeBytes - ? lowerDamagePredictionAnchor.PredictedSizeBytes - higherDamagePredictionAnchor.PredictedSizeBytes - : 0; + var requirement = NearAnchorGainRequirement.Create(higherDamagePredictionAnchor, lowerDamagePredictionAnchor); - if (span == 0) + if (requirement.Span == 0) { return new BrutalityAnalysis { @@ -2158,18 +2249,9 @@ private static BrutalityAnalysis AnalyzeNearLowerAnchorBrutality(HybridSelection }; } - ulong distanceFromSmall = candidate.Prediction.PredictedSizeBytes > higherDamagePredictionAnchor.PredictedSizeBytes - ? candidate.Prediction.PredictedSizeBytes - higherDamagePredictionAnchor.PredictedSizeBytes - : 0; - - double fraction = distanceFromSmall / (double)span; - double requiredGain = Math.Max( - Config.SelectionMinimumKldImprovementEpsilon, - Math.Abs(higherDamagePredictionAnchor.PredictedKld - lowerDamagePredictionAnchor.PredictedKld) * - Config.SelectionNearAnchorRequiredKldGainFractionOfPairGap); - - bool passed = fraction > Config.SelectionNearLowerAnchorBrutalZoneFractionOfPairSpan || - candidate.PredictedGainOverLine >= requiredGain; + double fraction = requirement.FractionFromSmallAnchor(candidate.Prediction.PredictedSizeBytes); + double requiredGain = requirement.RequiredGain; + bool passed = requirement.Passes(candidate.Prediction.PredictedSizeBytes, candidate.PredictedGainOverLine); string explanation = passed ? fraction > Config.SelectionNearLowerAnchorBrutalZoneFractionOfPairSpan @@ -2335,7 +2417,6 @@ private static int EstimateInteriorWindowCount(AdjacentAnchorPair pair, IReadOnl if (pair.LowerDamageLarger.SizeBytes <= pair.HigherDamageSmaller.SizeBytes) return 0; - ulong span = pair.LowerDamageLarger.SizeBytes - pair.HigherDamageSmaller.SizeBytes; ulong cursor = pair.HigherDamageSmaller.SizeBytes; int count = 0; @@ -2345,11 +2426,8 @@ private static int EstimateInteriorWindowCount(AdjacentAnchorPair pair, IReadOnl if (fraction <= 0d) continue; - ulong width = (ulong)Math.Round(span * fraction, MidpointRounding.AwayFromZero); - if (width == 0) - continue; - - ulong max = Math.Min(pair.LowerDamageLarger.SizeBytes, cursor + width); + ulong max = InteriorWindowPlanner.End(pair.HigherDamageSmaller.SizeBytes, pair.LowerDamageLarger.SizeBytes, + cursor, fraction, i == fractions.Count - 1, Config.SelectionCompleteInteriorCoverage); if (max <= cursor) continue; @@ -2670,6 +2748,7 @@ private static object ToAnchorLog(BenchmarkSnapshotRecord anchor) sizeGiB = ToGiB(anchor.SizeBytes), kld = anchor.Kld, ppl = anchor.Ppl, + evidenceIdentityHash = anchor.EvidenceIdentityHash, bitRange = anchor.Quant.BaseQuant.BitRange, quantizeBase = anchor.Quant.BaseQuant.QuantizeBaseArgumentName }; @@ -2715,6 +2794,7 @@ private static async Task WriteSelectionPhaseDiagnosticsAsync( { nearBaselineMaxSizeGrowthPercent = Config.SelectionNearBaselineMaxSizeGrowthPercent, interiorWindowFractions = Config.SelectionInteriorWindowFractions, + completeInteriorCoverage = Config.SelectionCompleteInteriorCoverage, maxCandidatesPerInteriorWindow = Config.SelectionMaxCandidatesPerInteriorWindow, maxFallbackAttemptsPerAnchor = Config.SelectionMaxFallbackAttemptsPerAnchor, minimumKldImprovementEpsilon = Config.SelectionMinimumKldImprovementEpsilon, @@ -3105,4 +3185,4 @@ private sealed class CandidatePreviewLog public double BrutalityRequiredGain { get; init; } public string BrutalityExplanation { get; init; } = string.Empty; } -} \ No newline at end of file +} diff --git a/src/MagicQuant/Services/PredictionValidationService.cs b/src/MagicQuant/Services/PredictionValidationService.cs index 1d16d1d..2c2cc22 100644 --- a/src/MagicQuant/Services/PredictionValidationService.cs +++ b/src/MagicQuant/Services/PredictionValidationService.cs @@ -1,6 +1,8 @@ using System.Globalization; using System.Text; +using System.Text.Json; using MagicQuant.Models; +using MQ.DB; using MQ.DB.Models; using MQ.DB.Models.DbModels; using Spectre.Console; @@ -8,10 +10,9 @@ namespace MagicQuant.Services; /// -/// Offline validator for the rank-safe isolation predictor. -/// It scores every currently benchmarked general-category combo in the active -/// scoped-model/imatrix bucket, compares predicted KLD to real KLD, and reports -/// rank/order accuracy. +/// Offline reconstruction/coefficient-holdout diagnostic. Its PAVA population is +/// the requested measured subset; it is not a replay of production eligibility, +/// whole-universe projection, or post-projection anomaly rules. /// public sealed class PredictionValidationService { @@ -28,23 +29,33 @@ public PredictionValidationService( public async Task ExportAsync( string outputDirectory, - CancellationToken ct = default) + CancellationToken ct = default, + IReadOnlyCollection? holdoutConfigKeys = null) { Directory.CreateDirectory(outputDirectory); - var actual = await _repository.LoadAllBenchmarkSnapshotsForCurrentContextAsync( + var available = await _repository.LoadAllBenchmarkSnapshotsForCurrentContextAsync( category: (byte)BenchmarkCategory.General, strictImatrixContext: true, ct: ct); - if (actual.Count == 0) + if (available.Count == 0) throw new InvalidOperationException("No category=General benchmark snapshots were found for the active scoped model/imatrix context."); - var predictions = await _predictionService.PredictAsync(actual.Select(x => x.Config).ToList(), ct); + var requestedKeys = (holdoutConfigKeys ?? Array.Empty()).ToHashSet(StringComparer.Ordinal); + var availableKeys = available.Select(x => TensorConfigIdentity.ToKey(x.Config)).ToHashSet(StringComparer.Ordinal); + var missing = requestedKeys.Except(availableKeys, StringComparer.Ordinal).ToList(); + if (missing.Count > 0) + throw new InvalidOperationException($"Holdout configuration keys were not found in the active benchmark bucket: {string.Join(", ", missing)}"); + + var actual = available.Where(x => requestedKeys.Count == 0 || requestedKeys.Contains(TensorConfigIdentity.ToKey(x.Config))).ToList(); + string mode = requestedKeys.Count == 0 ? "in_sample_reconstruction" : "coefficient_holdout_subset_diagnostic"; + var configs = actual.Select(x => x.Config).ToList(); + var predictions = await _predictionService.PredictAsync( + configs, ct, excludedFitConfigs: requestedKeys.Count == 0 ? null : configs); var actualByKey = actual.ToDictionary(x => TensorConfigIdentity.ToKey(x.Config), StringComparer.Ordinal); var rows = predictions.Rows - .Where(x => x.IsPredictable) .Where(x => actualByKey.ContainsKey(TensorConfigIdentity.ToKey(x.Config))) .ToList(); @@ -61,17 +72,21 @@ public async Task ExportAsync( var summary = BuildSummary(rows); string csvPath = Path.Combine(outputDirectory, "prediction_validation_general.csv"); string markdownPath = Path.Combine(outputDirectory, "prediction_validation_general.md"); + string jsonPath = Path.Combine(outputDirectory, "prediction_validation_general.json"); await File.WriteAllTextAsync(csvPath, BuildCsv(rows), ct); - await File.WriteAllTextAsync(markdownPath, BuildMarkdown(summary, rows, predictions.Notes), ct); + await File.WriteAllTextAsync(markdownPath, BuildMarkdown(summary, rows, predictions.Notes, mode), ct); + await File.WriteAllTextAsync(jsonPath, BuildJson(summary, rows, predictions, mode, requestedKeys), ct); - PrintSummary(summary, csvPath, markdownPath); + PrintSummary(summary, csvPath, markdownPath, jsonPath, mode); return new PredictionValidationExportResult { Summary = summary, CsvPath = csvPath, MarkdownPath = markdownPath, + JsonPath = jsonPath, + Mode = mode, Rows = rows .OrderByDescending(x => x.AbsoluteKldError) .ThenByDescending(x => RankDistance(x)) @@ -81,71 +96,102 @@ public async Task ExportAsync( private static void AssignRanks(IReadOnlyList rows) { + foreach (var row in rows) + { + row.ActualRank = null; + row.PredictedRank = null; + } + var comparable = rows.Where(IsComparable).ToList(); int actualRank = 1; - foreach (var row in rows.OrderBy(x => x.ActualKld).ThenBy(x => x.ActualSizeBytes ?? ulong.MaxValue)) + foreach (var row in comparable.OrderBy(x => x.ActualKld).ThenBy(x => x.ActualSizeBytes ?? ulong.MaxValue)) row.ActualRank = actualRank++; ulong predictedRank = 1; - foreach (var row in rows.OrderBy(x => x.PredictedKld).ThenBy(x => x.PredictedSizeBytes)) + foreach (var row in comparable.OrderBy(x => x.PredictedKld).ThenBy(x => x.PredictedSizeBytes)) row.PredictedRank = predictedRank++; } - private static RankSafeValidationSummary BuildSummary(IReadOnlyList rows) + internal static bool IsComparable(RankSafePredictionRow row) => + row.IsPredictable && double.IsFinite(row.PredictedKld) && double.IsFinite(row.ActualKld); + + internal static RankSafeValidationSummary BuildSummary(IReadOnlyList rows) { - if (rows.Count == 0) - return new RankSafeValidationSummary(); + var comparable = rows.Where(IsComparable).ToList(); + int sizePredictableCount = rows.Count(x => x.IsSizePredictable && x.ActualSizeBytes.HasValue); + if (comparable.Count == 0) + return new RankSafeValidationSummary { RowCount = rows.Count, SizePredictableCount = sizePredictableCount }; - double mae = rows.Average(x => x.AbsoluteKldError); - double rmse = Math.Sqrt(rows.Average(x => x.SignedKldError * x.SignedKldError)); - double maxAbs = rows.Max(x => x.AbsoluteKldError); - double meanSigned = rows.Average(x => x.SignedKldError); + double mae = comparable.Average(x => x.AbsoluteKldError); + double rmse = Math.Sqrt(comparable.Average(x => x.SignedKldError * x.SignedKldError)); + double maxAbs = comparable.Max(x => x.AbsoluteKldError); + double meanSigned = comparable.Average(x => x.SignedKldError); long concordant = 0; long discordant = 0; long tiedPred = 0; + long tiedActual = 0; + long tiedBoth = 0; - for (int i = 0; i < rows.Count; i++) + for (int i = 0; i < comparable.Count; i++) { - for (int j = i + 1; j < rows.Count; j++) + for (int j = i + 1; j < comparable.Count; j++) { - double actualDiff = rows[i].ActualKld - rows[j].ActualKld; - double predDiff = rows[i].PredictedKld - rows[j].PredictedKld; + double actualDiff = comparable[i].ActualKld - comparable[j].ActualKld; + double predDiff = comparable[i].PredictedKld - comparable[j].PredictedKld; int actualSign = Math.Sign(actualDiff); int predSign = Math.Sign(predDiff); + if (actualSign == 0 && predSign == 0) + { + tiedBoth++; + continue; + } + if (actualSign == 0) + { + tiedActual++; + continue; + } if (predSign == 0) { tiedPred++; continue; } - if (actualSign == 0 || actualSign == predSign) + if (actualSign == predSign) concordant++; else discordant++; } } - long denominator = concordant + discordant; - double pairwise = denominator == 0 ? 100d : concordant * 100d / denominator; + long denominator = concordant + discordant + tiedPred; + double? pairwise = denominator == 0 ? null : (concordant + 0.5d * tiedPred) * 100d / denominator; + double tauDenominator = Math.Sqrt( + (double)(concordant + discordant + tiedPred) * (concordant + discordant + tiedActual)); + double? tau = tauDenominator == 0d ? null : (concordant - discordant) / tauDenominator; int ShiftWithin(int maxShift) => - rows.Count(x => x.ActualRank.HasValue && x.PredictedRank.HasValue && + comparable.Count(x => x.ActualRank.HasValue && x.PredictedRank.HasValue && RankDistance(x) <= (ulong)maxShift); return new RankSafeValidationSummary { RowCount = rows.Count, - PredictableCount = rows.Count, + PredictableCount = comparable.Count, + SizePredictableCount = sizePredictableCount, Mae = mae, Rmse = rmse, MaxAbsoluteError = maxAbs, MeanSignedError = meanSigned, PairwiseAccuracyPercent = pairwise, + KendallTauB = tau, + OrderableActualPairs = denominator, ConcordantPairs = concordant, DiscordantPairs = discordant, - TiedPredictedPairs = tiedPred, + TiedPredictedPairs = tiedPred + tiedBoth, + TiedActualPairs = tiedActual + tiedBoth, + TiedBothPairs = tiedBoth, ExactRankMatches = ShiftWithin(0), WithinOneRank = ShiftWithin(1), WithinTwoRanks = ShiftWithin(2), @@ -158,7 +204,7 @@ int ShiftWithin(int maxShift) => private static string BuildCsv(IReadOnlyList rows) { var sb = new StringBuilder(); - sb.AppendLine("config_key,display_name,is_hybrid,base_quant,is_size_predictable,predicted_kld,actual_kld,abs_error,signed_error,predicted_rank,actual_rank,rank_shift,predicted_size_bytes,actual_size_bytes,size_abs_error_bytes,size_abs_error_percent,predicted_ppl,actual_ppl,effective_groups,notes"); + sb.AppendLine("config_key,display_name,is_hybrid,base_quant,is_size_predictable,predicted_kld,actual_kld,abs_error,signed_error,predicted_rank,actual_rank,rank_shift,predicted_size_bytes,actual_size_bytes,size_abs_error_bytes,size_abs_error_percent,predicted_ppl,actual_ppl,effective_groups,notes,is_predictable,prediction_config_key,additive_kld,cross_term,raw_interaction_kld,projected_kld,projection_adjustment_kld"); foreach (var row in rows .OrderByDescending(x => x.AbsoluteKldError) @@ -176,7 +222,7 @@ private static string BuildCsv(IReadOnlyList rows) sb.Append(Format(row.SignedKldError)).Append(','); sb.Append(row.PredictedRank?.ToString(CultureInfo.InvariantCulture) ?? "").Append(','); sb.Append(row.ActualRank?.ToString(CultureInfo.InvariantCulture) ?? "").Append(','); - sb.Append(shift.ToString(CultureInfo.InvariantCulture)).Append(','); + sb.Append(row.ActualRank.HasValue && row.PredictedRank.HasValue ? shift.ToString(CultureInfo.InvariantCulture) : "").Append(','); sb.Append(row.PredictedSizeBytes.ToString(CultureInfo.InvariantCulture)).Append(','); sb.Append(row.ActualSizeBytes?.ToString(CultureInfo.InvariantCulture) ?? "").Append(','); long sizeError = row.ActualSizeBytes.HasValue ? (long)row.PredictedSizeBytes - (long)row.ActualSizeBytes.Value : 0L; @@ -188,22 +234,108 @@ private static string BuildCsv(IReadOnlyList rows) sb.Append(Format(row.PredictedPpl)).Append(','); sb.Append(Format(row.ActualPpl)).Append(','); sb.Append(Csv(BuildEffectiveGroupSummary(row.Config))).Append(','); - sb.Append(Csv(string.Join(" | ", row.Notes))); + sb.Append(Csv(string.Join(" | ", row.Notes))).Append(','); + sb.Append(row.IsPredictable ? "true" : "false").Append(','); + sb.Append(Csv(TensorConfigIdentity.ToKey(row.PredictionConfig))).Append(','); + sb.Append(Format(row.AdditiveKld)).Append(','); + sb.Append(Format(row.CrossTerm)).Append(','); + sb.Append(Format(row.InteractionKld)).Append(','); + sb.Append(Format(row.ProjectedKld)).Append(','); + sb.Append(Format(row.ProjectionAdjustmentKld)); sb.AppendLine(); } return sb.ToString(); } + internal static string BuildJson( + RankSafeValidationSummary summary, + IReadOnlyList rows, + RankSafePredictionSet predictions, + string mode, + IReadOnlyCollection requestedHoldoutKeys) + { + static double? Finite(double value) => double.IsFinite(value) ? value : null; + var population = rows.Select(x => TensorConfigIdentity.ToKey(x.Config)) + .OrderBy(x => x, StringComparer.Ordinal).ToList(); + return JsonSerializer.Serialize(new + { + schema_version = 1, + mode, + generated_at_utc = DateTime.UtcNow, + prediction_context = new + { + model_id = Cache.CurrentModelId, + architecture_family_id = Cache.CurrentArchitectureFamilyId, + tensor_group_profile_id = Cache.CurrentTensorGroupProfileId, + tensor_group_profile_fingerprint = Cache.CurrentTensorGroupProfileFingerprintHash, + imatrix_identity = Cache.IsImatrixAvailable ? Cache.ActiveImatrixIdentityHash : "off", + category = "General" + }, + scoring_scope = "requested_measured_subset_before_anomaly_rules", + projection_mode = "rank_safe", + production_replay = false, + eligibility_scope = "prediction_coverage_only", + limitations = new[] + { + "PAVA depends on the requested subset; scores need not equal full DuckDB materialization.", + "Production pruning, anomaly rules, candidate eligibility and selection budgets are not replayed.", + "Coefficient holdout excludes requested configurations and canonical aliases from fitting; input isolation/pure/base-only observations remain shared and cannot themselves be held out.", + "Tensor-map equivalence between a real artifact and its virtual carrier coordinates is not verified here.", + "The legacy effective-state key is diagnostic metadata, not an artifact-content hash or evaluation identity." + }, + fit = predictions.Fit, + fit_training_config_key_scope = "canonical_prediction_coordinates", + fit_training_config_keys = predictions.FitTrainingConfigKeys, + requested_holdout_config_keys = requestedHoldoutKeys.OrderBy(x => x, StringComparer.Ordinal).ToList(), + score_population_keys = population, + score_population_key_hash = TensorConfigIdentity.StableHash(string.Join("\n", population)), + summary, + records = rows.Select(x => new + { + config_key = TensorConfigIdentity.ToKey(x.Config), + prediction_config_key = TensorConfigIdentity.ToKey(x.PredictionConfig), + effective_state_key = x.EffectiveStateKey, + has_unknown_mappings = x.HasUnknownMappings, + is_predictable = x.IsPredictable, + is_size_predictable = x.IsSizePredictable, + prediction_coverage = x.IsPredictable && x.IsSizePredictable && double.IsFinite(x.PredictedKld) ? "covered" : "incomplete", + selection_eligible = (bool?)null, + additive_kld = Finite(x.AdditiveKld), + cross_term = Finite(x.CrossTerm), + raw_interaction_kld = Finite(x.InteractionKld), + projected_kld = Finite(x.ProjectedKld), + predicted_kld = Finite(x.PredictedKld), + projection_adjustment_kld = Finite(x.ProjectionAdjustmentKld), + projection_changed_score = double.IsFinite(x.ProjectionAdjustmentKld) && x.ProjectionAdjustmentKld != 0d, + predicted_size_bytes = x.IsSizePredictable ? (ulong?)x.PredictedSizeBytes : null, + predicted_rank = x.PredictedRank, + actual_kld = Finite(x.ActualKld), + actual_ppl = Finite(x.ActualPpl), + actual_size_bytes = x.ActualSizeBytes, + actual_rank_within_comparable_subset = x.ActualRank, + notes = x.Notes + }), + notes = predictions.Notes + }, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }); + } + private static string BuildMarkdown( RankSafeValidationSummary summary, IReadOnlyList rows, - IReadOnlyList notes) + IReadOnlyList notes, + string mode) { var sb = new StringBuilder(); - sb.AppendLine("# MagicQuant Rank-Safe Prediction Validation"); + sb.AppendLine("# MagicQuant Prediction Reconstruction / Coefficient-Holdout Diagnostic"); sb.AppendLine(); - sb.AppendLine("This report compares predicted KLD to real category=General benchmark KLD for the active scoped model/imatrix bucket."); + sb.AppendLine($"Mode: `{mode}`. This report compares predicted KLD to category=General benchmark KLD in the active scoped model/imatrix bucket."); + sb.AppendLine(); + sb.AppendLine(mode == "in_sample_reconstruction" + ? "The same available outcomes participate in fitting. These are reconstruction metrics, not held-out discovery accuracy." + : "Listed target configurations and their canonical aliases are excluded from coefficient/threshold fitting. Pure, base-only and isolation inputs cannot be held out through this mode because their outcomes are also features. This is a configuration-level coefficient holdout, not a new-corpus or full-production replay."); + sb.AppendLine(); + sb.AppendLine("PAVA runs over the requested measured subset. The report does not apply production candidate pruning, whole-universe projection, anomaly rules or eligibility gates. Virtual Q8-carrier coordinates do not establish actual tensor-map equivalence for uncovered tensors. Unknown/unpredictable rows remain in the export and coverage denominator."); sb.AppendLine(); sb.AppendLine("## Summary"); @@ -211,18 +343,31 @@ private static string BuildMarkdown( sb.AppendLine("| Metric | Value |"); sb.AppendLine("|---|---:|"); sb.AppendLine($"| Rows | {summary.RowCount:N0} |"); - sb.AppendLine($"| MAE | {summary.Mae:0.000000} |"); - sb.AppendLine($"| RMSE | {summary.Rmse:0.000000} |"); - sb.AppendLine($"| Max abs error | {summary.MaxAbsoluteError:0.000000} |"); - sb.AppendLine($"| Mean signed error | {summary.MeanSignedError:0.000000} |"); - sb.AppendLine($"| Pairwise order accuracy | {summary.PairwiseAccuracyPercent:0.0000}% |"); + sb.AppendLine($"| Comparable predictable rows | {summary.PredictableCount:N0} |"); + sb.AppendLine($"| Unscored/noncomparable rows | {summary.UnpredictableCount:N0} |"); + sb.AppendLine($"| MAE | {Display(summary.Mae)} |"); + sb.AppendLine($"| RMSE | {Display(summary.Rmse)} |"); + sb.AppendLine($"| Max abs error | {Display(summary.MaxAbsoluteError)} |"); + sb.AppendLine($"| Mean signed error | {Display(summary.MeanSignedError)} |"); + sb.AppendLine($"| Tie-aware pairwise accuracy (%) | {Display(summary.PairwiseAccuracyPercent)} |"); + sb.AppendLine($"| Kendall tau-b | {Display(summary.KendallTauB)} |"); + sb.AppendLine($"| Actual-distinct pairs | {summary.OrderableActualPairs:N0} |"); sb.AppendLine($"| Concordant pairs | {summary.ConcordantPairs:N0} |"); sb.AppendLine($"| Discordant pairs | {summary.DiscordantPairs:N0} |"); sb.AppendLine($"| Tied predicted pairs | {summary.TiedPredictedPairs:N0} |"); + sb.AppendLine($"| Tied actual pairs | {summary.TiedActualPairs:N0} |"); + sb.AppendLine($"| Pairs tied in both | {summary.TiedBothPairs:N0} |"); + sb.AppendLine(); + sb.AppendLine("Pairwise accuracy excludes actual ties and gives predicted ties half credit. An all-tied predictor is 50% when actual values differ; no orderable actual pairs yields n/a. Kendall tau-b is n/a for a completely tied axis. Exact ties are numerical equality, not statistical equivalence."); - var sizeRows = rows.Where(x => x.ActualSizeBytes.HasValue && x.IsSizePredictable).ToList(); + var sizeRows = rows.Where(x => x.ActualSizeBytes is > 0 && x.IsSizePredictable).ToList(); if (sizeRows.Count > 0) { + sb.AppendLine(); + sb.AppendLine("## Size reconstruction"); + sb.AppendLine(); + sb.AppendLine("| Metric | Value |"); + sb.AppendLine("|---|---:|"); double sizeMaePercent = sizeRows.Average(x => Math.Abs((long)x.PredictedSizeBytes - (long)x.ActualSizeBytes!.Value) * 100d / x.ActualSizeBytes!.Value); double sizeMaxPercent = sizeRows.Max(x => Math.Abs((long)x.PredictedSizeBytes - (long)x.ActualSizeBytes!.Value) * 100d / x.ActualSizeBytes!.Value); sb.AppendLine($"| Size-safe rows | {sizeRows.Count:N0} |"); @@ -235,12 +380,12 @@ private static string BuildMarkdown( sb.AppendLine(); sb.AppendLine("| Window | Count | Percent |"); sb.AppendLine("|---|---:|---:|"); - AppendRankWindow(sb, "Exact", summary.ExactRankMatches, summary.RowCount); - AppendRankWindow(sb, "Within 1", summary.WithinOneRank, summary.RowCount); - AppendRankWindow(sb, "Within 2", summary.WithinTwoRanks, summary.RowCount); - AppendRankWindow(sb, "Within 5", summary.WithinFiveRanks, summary.RowCount); - AppendRankWindow(sb, "Within 10", summary.WithinTenRanks, summary.RowCount); - AppendRankWindow(sb, "Within 20", summary.WithinTwentyRanks, summary.RowCount); + AppendRankWindow(sb, "Exact", summary.ExactRankMatches, summary.PredictableCount); + AppendRankWindow(sb, "Within 1", summary.WithinOneRank, summary.PredictableCount); + AppendRankWindow(sb, "Within 2", summary.WithinTwoRanks, summary.PredictableCount); + AppendRankWindow(sb, "Within 5", summary.WithinFiveRanks, summary.PredictableCount); + AppendRankWindow(sb, "Within 10", summary.WithinTenRanks, summary.PredictableCount); + AppendRankWindow(sb, "Within 20", summary.WithinTwentyRanks, summary.PredictableCount); sb.AppendLine(); if (notes.Count > 0) @@ -274,6 +419,7 @@ private static string BuildMarkdown( sb.AppendLine("|---|---:|---:|---:|---:|---:|---:|---:|---:|---|"); foreach (var row in rows + .Where(IsComparable) .OrderByDescending(x => x.AbsoluteKldError) .ThenByDescending(x => RankDistance(x)) .Take(100)) @@ -287,16 +433,21 @@ private static string BuildMarkdown( return sb.ToString(); } - private static void PrintSummary(RankSafeValidationSummary summary, string csvPath, string markdownPath) + private static void PrintSummary(RankSafeValidationSummary summary, string csvPath, string markdownPath, string jsonPath, string mode) { - AnsiConsole.Write(new Rule("[yellow]Prediction Validation[/]") { Justification = Justify.Left }); - AnsiConsole.MarkupLine($"[green]Rows:[/] [cyan]{summary.RowCount:N0}[/]"); - AnsiConsole.MarkupLine($"[green]MAE:[/] [cyan]{summary.Mae:0.000000}[/] [green]RMSE:[/] [cyan]{summary.Rmse:0.000000}[/] [green]MaxAbs:[/] [cyan]{summary.MaxAbsoluteError:0.000000}[/]"); - AnsiConsole.MarkupLine($"[green]Pairwise order accuracy:[/] [cyan]{summary.PairwiseAccuracyPercent:0.0000}%[/] [grey]discordant={summary.DiscordantPairs:N0} tied-pred={summary.TiedPredictedPairs:N0}[/]"); + AnsiConsole.Write(new Rule("[yellow]Prediction Diagnostic[/]") { Justification = Justify.Left }); + AnsiConsole.MarkupLine($"[yellow]Mode:[/] {mode}; subset projection, not production discovery replay."); + AnsiConsole.MarkupLine($"[green]Rows:[/] [cyan]{summary.PredictableCount:N0}[/] comparable / [cyan]{summary.RowCount:N0}[/] requested"); + AnsiConsole.MarkupLine($"[green]MAE:[/] [cyan]{Display(summary.Mae)}[/] [green]RMSE:[/] [cyan]{Display(summary.Rmse)}[/] [green]MaxAbs:[/] [cyan]{Display(summary.MaxAbsoluteError)}[/]"); + AnsiConsole.MarkupLine($"[green]Tie-aware pairwise accuracy (%):[/] [cyan]{Display(summary.PairwiseAccuracyPercent)}[/] [grey]discordant={summary.DiscordantPairs:N0} tied-pred={summary.TiedPredictedPairs:N0}[/]"); AnsiConsole.MarkupLine($"[green]CSV:[/] [blue]{Markup.Escape(csvPath)}[/]"); AnsiConsole.MarkupLine($"[green]Markdown:[/] [blue]{Markup.Escape(markdownPath)}[/]"); + AnsiConsole.MarkupLine($"[green]JSON:[/] [blue]{Markup.Escape(jsonPath)}[/]"); } + private static string Display(double? value) => value.HasValue && double.IsFinite(value.Value) + ? value.Value.ToString("0.000000", CultureInfo.InvariantCulture) : "n/a"; + private static void AppendRankWindow(StringBuilder sb, string label, int count, int total) { double pct = total == 0 ? 0d : count * 100d / total; @@ -353,4 +504,4 @@ private static string Csv(string value) private static string ToGb(ulong bytes) => (bytes / 1024d / 1024d / 1024d).ToString("0.00", CultureInfo.InvariantCulture); private static string EscapePipe(string value) => (value ?? string.Empty).Replace("|", "\\|"); -} \ No newline at end of file +} diff --git a/src/MagicQuant/Services/QuantizationService.cs b/src/MagicQuant/Services/QuantizationService.cs index df4cccd..4cb7d03 100644 --- a/src/MagicQuant/Services/QuantizationService.cs +++ b/src/MagicQuant/Services/QuantizationService.cs @@ -499,18 +499,13 @@ public async Task ProcessHybridQuantAsync( modelPath: string.Empty, benchDir: modelBenchDir, klLogitsDir: baseLogitsDir, - domainsOverride: new[] { "general" })) + domainsOverride: new[] { "general" }, + allowIndependentGpuTopology: allowIndependentGpuTopology)) { AnsiConsole.MarkupLine($"[grey]Reused existing benchmark artifacts:[/] {Markup.Escape(modelName)}"); return SampleProcessState.Skipped; } - if (!forceBaselineRelearn && baselineLearnedTruthExists && await BenchmarkExistsAsync(quant, ct)) - { - AnsiConsole.MarkupLine($"[grey]Skipping already completed sample:[/] {Markup.Escape(modelName)}"); - return SampleProcessState.Skipped; - } - string inputPath = await GetEffectiveInputModelPathAsync( quant, forceBaselineRelearn, @@ -532,13 +527,20 @@ public async Task ProcessHybridQuantAsync( await using var lease = await _scratchStorage.AcquireAsync(leaseKind, modelName, ct: ct); string benchmarkModelPath = lease.GgufPath; + var stageMilliseconds = new Dictionary(StringComparer.Ordinal) + { + ["scratch_queue_wait"] = lease.WaitMilliseconds + }; try { QuantizationExecutionReport? quantizationReport = null; PreparedExternalBaselineBuild? preparedExternalBaseline = null; + var quantizationClock = Stopwatch.StartNew(); await _cpuQuantLock.WaitAsync(ct); + stageMilliseconds["cpu_queue_wait"] = quantizationClock.Elapsed.TotalMilliseconds; + quantizationClock.Restart(); try { if (pureExternalBaseline) @@ -593,25 +595,38 @@ public async Task ProcessHybridQuantAsync( } finally { + stageMilliseconds["quantization_with_preparation"] = quantizationClock.Elapsed.TotalMilliseconds; _cpuQuantLock.Release(); } AnsiConsole.MarkupLine($"[yellow]Benchmarking:[/] {Markup.Escape(modelName)}"); - await _benchmarker.RunAllBenchmarksAsync( + // Freeze the verified external map before taking measurement identity. The + // placeholder owns recipe FKs only; it is not usable as measured evidence. + if (preparedExternalBaseline?.HasPreparedLearningTruth == true) + { + await _benchmarker.EnsureUnmeasuredBenchmarkIdentityAsync(quant, ct); + await PersistLearnedBaselineTensorMapFromPreparedAsync(quant, preparedExternalBaseline, ct); + } + + var benchmarkClock = Stopwatch.StartNew(); + var benchmarkResult = await _benchmarker.RunAllBenchmarksAsync( quantConfig: quant, modelPath: benchmarkModelPath, benchDir: modelBenchDir, klLogitsDir: baseLogitsDir, saveLogits: false, domainsOverride: new[] { "general" }, - allowIndependentGpuTopology: allowIndependentGpuTopology); + allowIndependentGpuTopology: allowIndependentGpuTopology, + forceRebenchmark: forceBaselineRelearn); + stageMilliseconds["benchmark_with_identity_and_persistence"] = benchmarkClock.Elapsed.TotalMilliseconds; + foreach (var item in benchmarkResult.StageMilliseconds) + stageMilliseconds[item.Key] = item.Value; if (IsLearnableBaselineRun(quant)) { - if (preparedExternalBaseline?.HasPreparedLearningTruth == true) - await PersistLearnedBaselineTensorMapFromPreparedAsync(quant, preparedExternalBaseline, ct); - else if (!baselineLearnedTruthExists || forceBaselineRelearn) + if (preparedExternalBaseline?.HasPreparedLearningTruth != true && + (!baselineLearnedTruthExists || forceBaselineRelearn)) await LearnAndPersistBaselineTensorMapAsync(quant, benchmarkModelPath, quantizationReport, ct); } @@ -647,6 +662,19 @@ await PersistQuantizationRunAsync( throw; } + finally + { + stageMilliseconds["processing_total"] = (DateTime.UtcNow - startedUtc).TotalMilliseconds; + try + { + await BenchmarkEvidenceService.AtomicWriteAsync(lease.PrimaryLogPath + ".stages.json", new + { + SchemaVersion = 1, Model = modelName, LeaseId = lease.LeaseId, + StageMilliseconds = stageMilliseconds + }); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } } finally { @@ -1126,62 +1154,6 @@ private static bool IsPathInside(string childPath, string parentPath) private string GetBaseLogitsDirectory() => _paths.GetBaseLogitsDirectory(); - private async Task BenchmarkExistsAsync(HybridQuant quant, CancellationToken ct) - { - if (string.IsNullOrWhiteSpace(Cache.CurrentModelId)) - throw new InvalidOperationException("Cache.CurrentModelId is not set."); - - var lookup = BuildTensorLookup(quant); - - await using var db = new MagicQuantContext(); - - var scopedAiModelHashId = await ResolveCurrentScopedAiModelHashIdOrNullAsync(db, ct); - - if (scopedAiModelHashId == null) - return false; - - var imatrixDefinitionId = - await ImatrixIdentityService.ResolveCurrentImatrixDefinitionIdAsync(db, scopedAiModelHashId.Value, - createIfMissing: false, ct); - - int architectureFamilyId = TensorGroupProfileService.RequireCurrentArchitectureFamilyId(); - int tensorGroupProfileId = TensorGroupProfileService.RequireCurrentProfileId(); - - var bench = await db.AiBenchmarks - .AsNoTracking() - .Where(x => x.ArchitectureFamilyId == architectureFamilyId && - x.TensorGroupProfileId == tensorGroupProfileId && - x.AiModelHashId == scopedAiModelHashId.Value && - x.ImatrixDefinitionId == imatrixDefinitionId) - .Join( - db.TensorCombos.AsNoTracking(), - benchmark => benchmark.TensorComboId, - combo => combo.Id, - (benchmark, combo) => new { benchmark, combo }) - .Where(x => - x.combo.BaseQuant == lookup.BaseQuant && - x.combo.Embeddings == lookup.Embeddings && - x.combo.LmHead == lookup.LmHead && - x.combo.AttnQ == lookup.AttnQ && - x.combo.AttnKV == lookup.AttnKV && - x.combo.AttnOutput == lookup.AttnOutput && - x.combo.FfnUpGate == lookup.FfnUpGate && - x.combo.FfnDown == lookup.FfnDown && - x.combo.MoeExperts == lookup.MoeExperts && - x.combo.MoeRouter == lookup.MoeRouter) - .Select(x => x.benchmark.Id) - .FirstOrDefaultAsync(ct); - - if (bench == Guid.Empty) - return false; - - bool hasCategory = await db.Set() - .AsNoTracking() - .AnyAsync(x => x.AiBenchmarkId == bench, ct); - - return hasCategory; - } - private static TensorConfig BuildTensorLookup(HybridQuant quant) { return (TensorConfig)quant; @@ -1577,6 +1549,10 @@ private async Task RunLlamaQuantizeWithExactTensorM throw new InvalidOperationException( $"Imatrix was marked active but canonical artifact is missing: {imatrixPath}"); + string actualImatrixHash = await BenchmarkEvidenceService.HashFileAsync(imatrixPath, ct); + if (actualImatrixHash != await ImatrixIdentityService.EnsureActiveImatrixIdentityHashAsync(ct)) + throw new InvalidOperationException("The canonical quantizer imatrix differs from the active evidence identity."); + args.AddRange(["--imatrix", imatrixPath]); } @@ -2857,9 +2833,32 @@ private async Task CloneEquivalentIsolationBenchmarkAsync( .Include(x => x.CategorBenchmarks) .FirstOrDefaultAsync(x => x.Id == sourceIdentity.BenchmarkId.Value, ct); - if (sourceBench == null) + if (sourceBench == null || + !await BenchmarkEvidenceService.IsCurrentAsync(sourcePlan.Quant, sourceBench.EvidenceIdentityHash, ct)) + return false; + + // The planning dedupe key is only a proposal. Prove that the complete quantizer + // command would apply the same concrete types to the same native tensors. + string nativePath = await EnsureBaseModelFileAsync(); + var nativeMetadata = await ReadTensorMetadataFromGgufAsync(nativePath, _paths.GgufDir); + var sourceOverrides = ResolveConcreteTensorOverrides(nativeMetadata.TensorNames, + BuildRequestedTensorOverrides(sourcePlan.Quant, nativeMetadata.TensorNames)); + var duplicateOverrides = ResolveConcreteTensorOverrides(nativeMetadata.TensorNames, + BuildRequestedTensorOverrides(duplicatePlan.Quant, nativeMetadata.TensorNames)); + if (!EquivalentConcreteRecipes( + ResolveQuantizeBaseArgument(sourcePlan.Quant, sourceOverrides), + sourceOverrides.Select(x => new KeyValuePair(x.TensorName, x.SchemeName)), + ResolveQuantizeBaseArgument(duplicatePlan.Quant, duplicateOverrides), + duplicateOverrides.Select(x => new KeyValuePair(x.TensorName, x.SchemeName))) || + ShouldApplyImatrix(sourcePlan.Quant) != ShouldApplyImatrix(duplicatePlan.Quant)) return false; + string sourceDir = _paths.GetBenchmarkDir(GetHybridName(sourcePlan.Quant)); + var sourceResult = JsonSerializer.Deserialize( + await File.ReadAllTextAsync(Path.Combine(sourceDir, "bench_metrics.json"), ct)); + if (sourceResult?.Evidence is not { } sourceEvidence || + sourceEvidence.IdentityHash != sourceBench.EvidenceIdentityHash) return false; + var duplicateLookup = BuildTensorLookup(duplicatePlan.Quant); var duplicateCombo = await db.TensorCombos.FirstOrDefaultAsync(x => x.BaseQuant == duplicateLookup.BaseQuant && @@ -2898,7 +2897,19 @@ private async Task CloneEquivalentIsolationBenchmarkAsync( x.TensorComboId == duplicateCombo.Id, ct); if (existing != null) - return true; + return await BenchmarkEvidenceService.IsCurrentAsync(duplicatePlan.Quant, existing.EvidenceIdentityHash, ct); + + string duplicateDir = _paths.GetBenchmarkDir(GetHybridName(duplicatePlan.Quant)); + var duplicateEvidence = await BenchmarkEvidenceService.CreateAsync(duplicatePlan.Quant, string.Empty, + duplicateDir, GetBaseLogitsDirectory(), sourceEvidence.Domains.Keys.ToArray(), + sourceEvidence.TokenTarget, sourceEvidence.SaveLogits, + sourceEvidence.AllowIndependentGpuTopology, ct); + duplicateEvidence.ModelSha256 = sourceEvidence.ModelSha256; + duplicateEvidence.EquivalentSourceEvidenceHash = sourceEvidence.IdentityHash; + duplicateEvidence.IdentityHash = BenchmarkEvidenceService.ComputeIdentityHash(duplicateEvidence); + sourceResult.Evidence = duplicateEvidence; + await BenchmarkEvidenceService.ArchiveExistingMetricsAsync(duplicateDir, ct); + await BenchmarkEvidenceService.AtomicWriteAsync(Path.Combine(duplicateDir, "bench_metrics.json"), sourceResult, ct); var clonedBenchmark = new AiBenchmark { @@ -2908,6 +2919,7 @@ private async Task CloneEquivalentIsolationBenchmarkAsync( Ngl = sourceBench.Ngl, SizeBytes = sourceBench.SizeBytes, TokensPerSecond = sourceBench.TokensPerSecond, + EvidenceIdentityHash = duplicateEvidence.IdentityHash, TensorComboId = duplicateCombo.Id, AiModelHashId = benchmarkAiModelHashId, ImatrixDefinitionId = imatrixDefinitionId @@ -2972,6 +2984,12 @@ private async Task CloneEquivalentIsolationBenchmarkAsync( return true; } + internal static bool EquivalentConcreteRecipes(string firstBase, IEnumerable> first, + string secondBase, IEnumerable> second) + => string.Equals(firstBase, secondBase, StringComparison.Ordinal) && + first.OrderBy(x => x.Key, StringComparer.Ordinal).ThenBy(x => x.Value, StringComparer.Ordinal) + .SequenceEqual(second.OrderBy(x => x.Key, StringComparer.Ordinal).ThenBy(x => x.Value, StringComparer.Ordinal)); + // ---------------------------------------------------------------- // Internal DTOs // ---------------------------------------------------------------- @@ -3091,7 +3109,9 @@ private static string ResolveSchemeName(TensorWeightScheme s) return s.Names[0]; } - public string GenerateHybridName(HybridQuant quant) + public string GenerateHybridName(HybridQuant quant) => GetHybridName(quant); + + public static string GetHybridName(HybridQuant quant) { string modelName = new DirectoryInfo(Cache.ModelDirectory!).Name; string baseName = ResolveBaseName(quant.BaseQuant); @@ -3145,12 +3165,12 @@ public string GenerateHybridName(HybridQuant quant) return $"{modelName}-{baseName}-{suffix}"; } - private int GetOrder(char c) + private static int GetOrder(char c) { return "EHQKOUDXR".IndexOf(c); } - private string SimplifyQuant(string quant) + private static string SimplifyQuant(string quant) { return quant.Replace("_", "") .Replace("BF16", "B16") diff --git a/src/MagicQuant/Services/RankSafeKldPredictionService.cs b/src/MagicQuant/Services/RankSafeKldPredictionService.cs index 3aad442..95eb4af 100644 --- a/src/MagicQuant/Services/RankSafeKldPredictionService.cs +++ b/src/MagicQuant/Services/RankSafeKldPredictionService.cs @@ -29,10 +29,13 @@ public RankSafeKldPredictionService( _effectiveResolver = effectiveResolver; } - internal async Task BuildModelAsync(CancellationToken ct = default) + internal async Task BuildModelAsync( + CancellationToken ct = default, + IReadOnlyCollection? excludedFitConfigs = null) { var context = await BuildContextAsync(ct); - var fitRows = await LoadFitRowsAsync(context, Array.Empty(), ct); + var excludedKeys = BuildFitExclusionKeys(context, excludedFitConfigs ?? Array.Empty()); + var fitRows = await LoadFitRowsAsync(context, excludedKeys, ct); var fit = FitInteractionModel(fitRows, context); var notes = new List(context.Notes) @@ -41,18 +44,21 @@ internal async Task BuildModelAsync(CancellationToken c }; context.Fit = fit; + context.FitTrainingConfigKeys = fitRows.Select(x => TensorConfigIdentity.ToKey(x.Config)) + .Distinct(StringComparer.Ordinal).OrderBy(x => x, StringComparer.Ordinal).ToList(); context.Notes = notes; return context; } public async Task PredictAsync( IReadOnlyCollection configs, - CancellationToken ct = default) + CancellationToken ct = default, + IReadOnlyCollection? excludedFitConfigs = null) { if (configs == null) throw new ArgumentNullException(nameof(configs)); - var context = await BuildModelAsync(ct); + var context = await BuildModelAsync(ct, excludedFitConfigs); var uniqueConfigs = configs .DistinctBy(TensorConfigIdentity.ToKey) .ToList(); @@ -68,7 +74,7 @@ public async Task PredictAsync( foreach (var row in rows.Where(x => x.IsPredictable)) { - row.CrossTerm = ComputeCrossTerm(row.Config, context, context.Fit.BitStressThreshold); + row.CrossTerm = ComputeCrossTerm(row.PredictionConfig, context, context.Fit.BitStressThreshold); row.InteractionKld = Math.Max(0d, (context.Fit.Alpha * row.AdditiveKld) + (context.Fit.Beta * row.CrossTerm)); } @@ -83,6 +89,7 @@ public async Task PredictAsync( .ThenBy(x => x.PredictedSizeBytes) .ToList(), Fit = context.Fit, + FitTrainingConfigKeys = context.FitTrainingConfigKeys, Notes = context.Notes }; } @@ -92,12 +99,23 @@ private async Task PredictSingleAsync( RankSafePredictionModel context, CancellationToken ct) { - var quant = (HybridQuant)config; var effective = await _effectiveResolver.ResolveAsync(config, ct); + return PredictFromContext(config, context, effective); + } + + internal static RankSafePredictionRow PredictFromContext( + TensorConfig config, + RankSafePredictionModel context, + EffectiveStateResolutionResult effective) + { + var quant = (HybridQuant)config; + if (!TryCanonicalizeBenchmarkSnapshotConfigForPrediction(config, context, out var predictionConfig, out var skipReason)) + throw new InvalidOperationException(skipReason ?? "Configuration cannot be represented in prediction coordinates."); var row = new RankSafePredictionRow { Config = config, + PredictionConfig = predictionConfig, Quant = quant, IsPureBaseline = TensorConfigIdentity.IsPureBaseline(config), EffectiveStateKey = effective.EffectiveStateKey, @@ -105,30 +123,35 @@ private async Task PredictSingleAsync( Notes = effective.Warnings.ToList() }; - if (row.IsPureBaseline) + if (row.IsPureBaseline && BaselineQuants.IsNativeExactAlias(config.BaseQuant)) { if (context.PureSnapshotsByBaselineId.TryGetValue(config.BaseQuant, out var pureDirect)) { row.PredictedSizeBytes = pureDirect.SizeBytes; - row.AdditiveKld = pureDirect.Kld; - row.InteractionKld = pureDirect.Kld; - row.PredictedKld = pureDirect.Kld; + // Native precision defines the zero-damage origin. Never feed the + // measured KLD target of a quantized pure baseline into its features. + row.AdditiveKld = 0d; + row.InteractionKld = 0d; + row.ProjectedKld = 0d; + row.PredictedKld = 0d; row.PredictedPpl = pureDirect.Ppl; return row; } - - GuardAgainstDisabledPureBaselineSurrogateFallback(config.BaseQuant, context, row.Notes); } - row.PredictedSizeBytes = PredictSize(config, context, row.Notes, out bool canPredictSize); + if (TensorConfigIdentity.ToKey(config) != TensorConfigIdentity.ToKey(predictionConfig)) + row.Notes.Add("Scored as a virtual Q8-carrier configuration; parity of uncovered tensor assignments with the real artifact is not established by this diagnostic."); + + row.PredictedSizeBytes = PredictSize(predictionConfig, context, row.Notes, out bool canPredictSize); row.IsSizePredictable = canPredictSize; - row.AdditiveKld = PredictAdditiveKld(config, context, row.Notes, out bool canPredict); - row.PredictedPpl = PredictPpl(config, context, row.Notes); + row.AdditiveKld = PredictAdditiveKld(predictionConfig, context, row.Notes, out bool canPredict); + row.PredictedPpl = PredictPpl(predictionConfig, context, row.Notes); if (!canPredict) { row.IsPredictable = false; row.InteractionKld = double.PositiveInfinity; + row.ProjectedKld = double.PositiveInfinity; row.PredictedKld = double.PositiveInfinity; return row; } @@ -287,7 +310,7 @@ private async Task BuildContextAsync(CancellationToken private async Task> LoadFitRowsAsync( RankSafePredictionModel context, - IReadOnlyList alreadyPredicted, + IReadOnlySet excludedKeys, CancellationToken ct) { var allBenchmarkRows = await _repository.LoadAllBenchmarkSnapshotsForCurrentContextAsync( @@ -295,13 +318,25 @@ private async Task> LoadFitRowsAsync( strictImatrixContext: true, ct: ct); - var alreadyByKey = alreadyPredicted.ToDictionary(x => TensorConfigIdentity.ToKey(x.Config), StringComparer.Ordinal); + return BuildFitRows(context, allBenchmarkRows, excludedKeys, ct); + } + + // Fitting uses the same frozen numeric context as scoring. Resolving display + // mappings has no effect on these features and must not read held-out outcomes. + internal static List BuildFitRows( + RankSafePredictionModel context, + IReadOnlyList allBenchmarkRows, + IReadOnlySet excludedKeys, + CancellationToken ct = default) + { var fitRows = new List(); var skippedFitReasons = new HashSet(StringComparer.Ordinal); foreach (var snapshot in allBenchmarkRows) { ct.ThrowIfCancellationRequested(); + if (!double.IsFinite(snapshot.Kld) || snapshot.Kld < 0d) + continue; /* * Keep the rank-safe predictor entirely in prediction space. @@ -340,12 +375,10 @@ private async Task> LoadFitRowsAsync( } var predictionKey = TensorConfigIdentity.ToKey(predictionConfig); + if (excludedKeys.Contains(TensorConfigIdentity.ToKey(snapshot.Config)) || excludedKeys.Contains(predictionKey)) + continue; - RankSafePredictionRow predicted; - if (!alreadyByKey.TryGetValue(predictionKey, out predicted!)) - { - predicted = await PredictSingleAsync(predictionConfig, context, ct); - } + var predicted = PredictFromContext(predictionConfig, context, new EffectiveStateResolutionResult()); if (!predicted.IsPredictable || double.IsInfinity(predicted.AdditiveKld) || double.IsNaN(predicted.AdditiveKld)) continue; @@ -364,7 +397,7 @@ private async Task> LoadFitRowsAsync( return fitRows; } - private static bool TryCanonicalizeBenchmarkSnapshotConfigForPrediction( + internal static bool TryCanonicalizeBenchmarkSnapshotConfigForPrediction( TensorConfig config, RankSafePredictionModel context, out TensorConfig predictionConfig, @@ -373,7 +406,7 @@ private static bool TryCanonicalizeBenchmarkSnapshotConfigForPrediction( predictionConfig = config; skipReason = null; - if (config.BaseQuant == BaselineQuants.Q8_0.UniqueId) + if (config.BaseQuant == BaselineQuants.Q8_0.UniqueId && !TensorConfigIdentity.IsPureBaseline(config)) return true; var baseline = BaselineQuants.FromId(config.BaseQuant); @@ -405,6 +438,38 @@ private static bool TryCanonicalizeBenchmarkSnapshotConfigForPrediction( return true; } + internal static HashSet BuildFitExclusionKeys( + RankSafePredictionModel context, + IReadOnlyCollection excludedConfigs) + { + var excluded = new HashSet(StringComparer.Ordinal); + if (excludedConfigs.Count == 0) + return excluded; + foreach (var config in excludedConfigs) + { + excluded.Add(TensorConfigIdentity.ToKey(config)); + if (TryCanonicalizeBenchmarkSnapshotConfigForPrediction(config, context, out var canonical, out _)) + excluded.Add(TensorConfigIdentity.ToKey(canonical)); + } + + // These observations are also input features, so excluding them only from + // coefficient fitting would still leak their outcomes through the context. + var required = context.PureSnapshotsByBaselineId.Values + .Concat(context.BaseOnlySnapshotsByBaselineId.Values) + .Concat(context.IsolationByGroupAndBaseline.Values); + foreach (var snapshot in required) + { + bool collision = excluded.Contains(TensorConfigIdentity.ToKey(snapshot.Config)); + if (TryCanonicalizeBenchmarkSnapshotConfigForPrediction(snapshot.Config, context, out var canonical, out _)) + collision |= excluded.Contains(TensorConfigIdentity.ToKey(canonical)); + if (collision) + throw new InvalidOperationException( + $"Cannot hold out configuration {TensorConfigIdentity.ToKey(snapshot.Config)}: it is a pure/base-only/isolation input to prediction. Choose hybrid outcomes not reused as prediction features."); + } + + return excluded; + } + private static byte CanonicalizePredictionSlot( TensorGroup group, byte storedValue, @@ -419,12 +484,12 @@ private static byte CanonicalizePredictionSlot( : storedValue; } - private RankSafePredictionFit FitInteractionModel( + internal static RankSafePredictionFit FitInteractionModel( IReadOnlyList observations, RankSafePredictionModel context) { var usable = observations - .Where(x => x.ActualKld >= 0d) + .Where(x => double.IsFinite(x.ActualKld) && x.ActualKld >= 0d) .Where(x => !double.IsNaN(x.AdditiveKld) && !double.IsInfinity(x.AdditiveKld)) .ToList(); @@ -524,7 +589,7 @@ private RankSafePredictionFit FitInteractionModel( }; } - private static void ApplyRankSafeProjection(IReadOnlyList rows) + internal static void ApplyRankSafeProjection(IReadOnlyList rows) { var predictable = rows .Where(x => x.IsPredictable) @@ -539,7 +604,10 @@ private static void ApplyRankSafeProjection(IReadOnlyList double[] projected = Pava(predictable.Select(x => x.InteractionKld).ToArray()); for (int i = 0; i < predictable.Count; i++) - predictable[i].PredictedKld = Math.Max(0d, projected[i]); + { + predictable[i].ProjectedKld = Math.Max(0d, projected[i]); + predictable[i].PredictedKld = predictable[i].ProjectedKld; + } ulong rank = 1; foreach (var row in rows @@ -551,7 +619,7 @@ private static void ApplyRankSafeProjection(IReadOnlyList } } - private static double[] Pava(double[] values) + internal static double[] Pava(double[] values) { var blocks = new List(); @@ -587,7 +655,7 @@ private static double[] Pava(double[] values) return result; } - private double PredictAdditiveKld( + private static double PredictAdditiveKld( TensorConfig config, RankSafePredictionModel context, List notes, @@ -614,7 +682,7 @@ private double PredictAdditiveKld( return Math.Max(0d, total); } - private double PredictPpl( + private static double PredictPpl( TensorConfig config, RankSafePredictionModel context, List notes) @@ -635,7 +703,7 @@ private double PredictPpl( return total; } - private ulong PredictSize( + private static ulong PredictSize( TensorConfig config, RankSafePredictionModel context, List notes, @@ -774,7 +842,7 @@ internal static double GetStressBitRangeForPrediction( : declared; } - private double ComputeCrossTerm(TensorConfig config, RankSafePredictionModel context, double threshold) + private static double ComputeCrossTerm(TensorConfig config, RankSafePredictionModel context, double threshold) { var contributions = new List<(double Kld, double Bits)>(); @@ -1140,9 +1208,10 @@ public RankSafePredictionModel( public Dictionary<(byte GroupId, byte BaselineId), double> IsolationDominanceBitTruthByGroupAndBaseline { get; } public IReadOnlyList Notes { get; set; } public RankSafePredictionFit Fit { get; set; } = new(); + public IReadOnlyList FitTrainingConfigKeys { get; set; } = Array.Empty(); } - private sealed class FitObservation + internal sealed class FitObservation { public TensorConfig Config { get; init; } public double ActualKld { get; init; } diff --git a/src/MagicQuant/Services/RemainingCombinationStore.cs b/src/MagicQuant/Services/RemainingCombinationStore.cs index 6d753c9..2eb85b6 100644 --- a/src/MagicQuant/Services/RemainingCombinationStore.cs +++ b/src/MagicQuant/Services/RemainingCombinationStore.cs @@ -352,7 +352,8 @@ public async Task CountBetterThanLinearCandidatesAsync( ulong predictionWindowMaxSize, ulong deterministicWindowMinSize, ulong deterministicWindowMaxSize, - CancellationToken ct = default) + CancellationToken ct = default, + bool applyNearAnchorRequirement = false) { var effectiveWindow = IntersectSizeWindows( predictionWindowMinSize, @@ -363,6 +364,9 @@ public async Task CountBetterThanLinearCandidatesAsync( if (effectiveWindow == null) return 0; + var eligibility = NearAnchorGainRequirement.Create(higherDamageSmaller, lowerDamageLarger); + string eligibilitySql = applyNearAnchorRequirement ? $"AND {NearAnchorGainRequirement.SqlPredicate}" : string.Empty; + string sql = $@" WITH scored AS ( SELECT {CombinationDuckDbSchema.EffectivePredictedKldSql} AS PredictedKld, @@ -377,29 +381,34 @@ AND PredictionRank IS NOT NULL AND {CombinationDuckDbSchema.ActiveCandidatePredicateSql} AND {CombinationDuckDbSchema.HybridPredicateSql} AND PredictedSizeBytes BETWEEN ? AND ? +), +ranked AS ( + SELECT *, LinearExpectedKld - PredictedKld AS Gain FROM scored ) SELECT COUNT(*) -FROM scored -WHERE LinearExpectedKld - PredictedKld > ?;"; +FROM ranked +WHERE Gain > ? + {eligibilitySql};"; double denominator = Math.Max( (double)lowerDamageLarger.PredictedSizeBytes - higherDamageSmaller.PredictedSizeBytes, 1d); - return await ExecuteCountAsync( - sql, - new object[] - { - higherDamageSmaller.PredictedKld, - (double)higherDamageSmaller.PredictedSizeBytes, - denominator, - lowerDamageLarger.PredictedKld, - higherDamageSmaller.PredictedKld, - effectiveWindow.Value.Min, - effectiveWindow.Value.Max, - Config.SelectionMinimumKldImprovementEpsilon - }, - ct); + var parameters = new List + { + higherDamageSmaller.PredictedKld, + (double)higherDamageSmaller.PredictedSizeBytes, + denominator, + lowerDamageLarger.PredictedKld, + higherDamageSmaller.PredictedKld, + effectiveWindow.Value.Min, + effectiveWindow.Value.Max, + Config.SelectionMinimumKldImprovementEpsilon + }; + if (applyNearAnchorRequirement) + parameters.AddRange(eligibility.SqlParameters); + + return await ExecuteCountAsync(sql, parameters.ToArray(), ct); } public Task> QueryStrictDominanceCandidatesAsync( @@ -498,6 +507,7 @@ FROM scored Gain FROM ranked WHERE Gain > ? + AND {NearAnchorGainRequirement.SqlPredicate} ORDER BY Gain DESC, PredictionConfidence DESC, PredictedSizeBytes ASC, @@ -517,18 +527,21 @@ PredictionRank ASC using var cmd = c.CreateCommand(); cmd.CommandText = sql; - foreach (var value in new object[] - { - higherDamagePredictionAnchor.PredictedKld, - (double)higherDamagePredictionAnchor.PredictedSizeBytes, - denominator, - lowerDamagePredictionAnchor.PredictedKld, - higherDamagePredictionAnchor.PredictedKld, - effectiveWindow.Value.Min, - effectiveWindow.Value.Max, - Config.SelectionMinimumKldImprovementEpsilon, - limit - }) + var parameters = new List + { + higherDamagePredictionAnchor.PredictedKld, + (double)higherDamagePredictionAnchor.PredictedSizeBytes, + denominator, + lowerDamagePredictionAnchor.PredictedKld, + higherDamagePredictionAnchor.PredictedKld, + effectiveWindow.Value.Min, + effectiveWindow.Value.Max, + Config.SelectionMinimumKldImprovementEpsilon + }; + parameters.AddRange(NearAnchorGainRequirement.Create(higherDamagePredictionAnchor, lowerDamagePredictionAnchor).SqlParameters); + parameters.Add(Math.Max(0, limit)); + + foreach (var value in parameters) { cmd.Parameters.Add(new DuckDBParameter { Value = value }); } @@ -815,4 +828,4 @@ private static async Task EnsureTensorConfigsTableExistsAsync(DuckDBConnection c "This almost always means the generator and prediction reader are using different DuckDB filenames, " + "or prediction started before QuantDatabaseService initialized/rebuilt the search-space table."); } -} \ No newline at end of file +} diff --git a/src/MagicQuant/Services/ScratchStorageService.cs b/src/MagicQuant/Services/ScratchStorageService.cs index 9622f52..54e9f4b 100644 --- a/src/MagicQuant/Services/ScratchStorageService.cs +++ b/src/MagicQuant/Services/ScratchStorageService.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using System.Diagnostics; using MagicQuant.Helpers; using MQ.DB; @@ -19,6 +20,7 @@ public sealed class ScratchArtifactLease : IAsyncDisposable { private readonly Func _dispose; private int _disposed; + private readonly Stopwatch _lifetime = Stopwatch.StartNew(); internal ScratchArtifactLease( Guid leaseId, @@ -27,7 +29,8 @@ internal ScratchArtifactLease( string leaseDirectory, string ggufPath, string primaryLogPath, - Func dispose) + Func dispose, + double waitMilliseconds = 0) { LeaseId = leaseId; Kind = kind; @@ -37,6 +40,7 @@ internal ScratchArtifactLease( PrimaryLogPath = primaryLogPath; OwnsGgufLifecycle = true; _dispose = dispose; + WaitMilliseconds = waitMilliseconds; } public Guid LeaseId { get; } @@ -46,6 +50,7 @@ internal ScratchArtifactLease( public string GgufPath { get; } public string PrimaryLogPath { get; } public bool OwnsGgufLifecycle { get; private set; } + public double WaitMilliseconds { get; } public void PreserveOutput() => OwnsGgufLifecycle = false; @@ -54,7 +59,28 @@ public async ValueTask DisposeAsync() if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - await _dispose(this); + _lifetime.Stop(); + var cleanup = Stopwatch.StartNew(); + try { await _dispose(this); } + finally + { + cleanup.Stop(); + // Observability only: root ownership and cleanup ordering are unchanged. + try + { + await BenchmarkEvidenceService.AtomicWriteAsync(PrimaryLogPath + ".scratch-timing.json", new + { + LeaseId, Kind = Kind.ToString(), ScratchRoot, WaitMilliseconds, + ArtifactLifetimeMilliseconds = _lifetime.Elapsed.TotalMilliseconds, + CleanupMilliseconds = cleanup.Elapsed.TotalMilliseconds, + Preserved = !OwnsGgufLifecycle + }); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A timing write must not hide the real processing/cleanup outcome. + } + } } } @@ -97,6 +123,7 @@ public async Task AcquireAsync( string extension = ".gguf", CancellationToken ct = default) { + var acquisition = Stopwatch.StartNew(); await _availableRoots.WaitAsync(ct); int rootIndex = -1; @@ -163,7 +190,7 @@ public async Task AcquireAsync( _rootLocks[rootIndex].Release(); _availableRoots.Release(); } - }); + }, acquisition.Elapsed.TotalMilliseconds); } catch { diff --git a/src/MagicQuant/Services/SelectionEligibility.cs b/src/MagicQuant/Services/SelectionEligibility.cs new file mode 100644 index 0000000..c6ac072 --- /dev/null +++ b/src/MagicQuant/Services/SelectionEligibility.cs @@ -0,0 +1,60 @@ +using MagicQuant.Models; + +namespace MagicQuant.Services; + +/// +/// The same deterministic requirement is applied by the SQL query before LIMIT +/// and by selection diagnostics. It uses prediction-space anchors only. +/// +internal readonly record struct NearAnchorGainRequirement( + ulong SmallAnchorSize, + ulong Span, + double ZoneFraction, + double RequiredGain) +{ + public static NearAnchorGainRequirement Create(PredictedAnchorRow smaller, PredictedAnchorRow larger) => new( + smaller.PredictedSizeBytes, + larger.PredictedSizeBytes > smaller.PredictedSizeBytes + ? larger.PredictedSizeBytes - smaller.PredictedSizeBytes : 0, + Config.SelectionNearLowerAnchorBrutalZoneFractionOfPairSpan, + Math.Max(Config.SelectionMinimumKldImprovementEpsilon, + Math.Abs(smaller.PredictedKld - larger.PredictedKld) * Config.SelectionNearAnchorRequiredKldGainFractionOfPairGap)); + + public double FractionFromSmallAnchor(ulong candidateSize) => Span == 0 + ? 1d + : (candidateSize > SmallAnchorSize ? candidateSize - SmallAnchorSize : 0) / (double)Span; + + public bool Passes(ulong candidateSize, double gain) => + Span == 0 || FractionFromSmallAnchor(candidateSize) > ZoneFraction || gain >= RequiredGain; + + // DECIMAL subtraction retains the exact unsigned byte distance before its + // conversion to DOUBLE, matching the in-memory unsigned subtraction. + public const string SqlPredicate = """ + (? OR + CAST(GREATEST(CAST(PredictedSizeBytes AS DECIMAL(20,0)) - CAST(? AS DECIMAL(20,0)), 0) AS DOUBLE) + / CAST(? AS DOUBLE) > ? + OR Gain >= ?) + """; + + public object[] SqlParameters => [Span == 0, SmallAnchorSize, Math.Max(Span, 1UL), ZoneFraction, RequiredGain]; +} + +internal static class InteriorWindowPlanner +{ + public static ulong End( + ulong low, + ulong high, + ulong cursor, + double fraction, + bool lastWindow, + bool completeCoverage) + { + if (high <= low || cursor >= high || fraction <= 0d || !double.IsFinite(fraction)) + return Math.Min(cursor, high); + if (completeCoverage && lastWindow) + return high; + + ulong width = (ulong)Math.Round((high - low) * Math.Clamp(fraction, 0d, 1d), MidpointRounding.AwayFromZero); + return cursor + Math.Min(width, high - cursor); + } +} diff --git a/src/MagicQuant/config.default.yaml b/src/MagicQuant/config.default.yaml index b0809f5..6fcf773 100644 --- a/src/MagicQuant/config.default.yaml +++ b/src/MagicQuant/config.default.yaml @@ -192,8 +192,19 @@ isolation_pruning: # Minimum meaningful reduction ratio for base-only comparisons. minimum_meaningful_base_only_reduction_ratio: 0.01 + # Opt-in bounded local swaps for isolated size/KLD improvements removed only + # by the bad-trade heuristic. Global candidate bans remain in force. + kld_size_rescue_enabled: false + kld_size_rescue_max_candidates_per_group: 1 + kld_size_rescue_max_context_probes_per_run: 3 + prediction: + # Optional streamed JSONL of the complete scored pool plus fit/context metadata. + # This can be large. Scores are pre-anomaly and are not selection-eligibility decisions. + # Does not change the production projection or candidate policy. + export_candidate_scores: false + # Rank-safe isolation KLD predictor. # # manual_max_predicted_size_bytes is retained only as an emergency compatibility @@ -234,6 +245,10 @@ candidate_selection: - 0.35 - 0.35 + # Opt-in: extend the last window to the larger anchor, preserving window and + # attempt counts. [0.35, 0.35] then covers [0%,35%] and [35%,100%]. + complete_interior_coverage: false + # Number of predicted winners to keep per interior window. max_candidates_per_interior_window: 1 diff --git a/tests/MagicQuant.Tests/BenchmarkEvidenceTests.cs b/tests/MagicQuant.Tests/BenchmarkEvidenceTests.cs new file mode 100644 index 0000000..2cc001c --- /dev/null +++ b/tests/MagicQuant.Tests/BenchmarkEvidenceTests.cs @@ -0,0 +1,446 @@ +using System.Text.Json; +using MagicQuant.Services; +using Microsoft.EntityFrameworkCore; +using MQ.DB; +using MQ.DB.Data; +using MQ.DB.Models; +using MQ.DB.Models.DbModels; +using Xunit; + +namespace MagicQuant.Tests; + +public sealed class BenchmarkEvidenceTests +{ + [Fact] + public async Task Identical_definition_reuses_after_transient_gguf_is_removed() + { + using var f = await EvidenceFixture.CreateAsync(); + var written = await f.WriteMeasurementAsync(); + File.Delete(f.CandidatePath); + var reused = await f.ReadAsync(); + Assert.NotNull(reused); + Assert.Equal(written.Evidence!.IdentityHash, reused.Evidence!.IdentityHash); + Assert.Equal(0.02, reused.Perplexity["general"].Kld); + } + + [Theory] + [InlineData("recipe")] + [InlineData("imatrix")] + [InlineData("source")] + [InlineData("evaluator")] + [InlineData("library")] + [InlineData("corpus")] + [InlineData("reference")] + [InlineData("budget")] + [InlineData("topology")] + public async Task Changed_inputs_cannot_relabel_old_disk_metrics(string changed) + { + using var f = await EvidenceFixture.CreateAsync(); + var written = await f.WriteMeasurementAsync(); + var quant = f.Quant; + int budget = BenchmarkEvidenceService.DefaultTokenTarget; + bool independent = true; + switch (changed) + { + case "recipe": quant = HybridQuant.CreatePureBaseline(BaselineQuants.Q5_K); break; + case "imatrix": await f.ActivateImatrixAsync("new calibration"); break; + case "source": await EvidenceFixture.ReplaceAsync(f.NativePath, "other native model"); break; + case "evaluator": await EvidenceFixture.ReplaceAsync(f.PplExecutable, "other evaluator"); break; + case "library": await File.WriteAllTextAsync(Path.Combine(f.BinDir, "libggml-test.so"), "new kernel"); break; + case "corpus": await EvidenceFixture.ReplaceAsync(f.CorpusPath, "other corpus"); break; + case "reference": await EvidenceFixture.ReplaceAsync(f.ReferencePath, "other serialized logits"); break; + case "budget": budget = 8192; break; + case "topology": independent = false; break; + } + Assert.Null(await BenchmarkEvidenceService.TryReadCompatibleResultAsync(quant, string.Empty, + f.CandidateDir, f.LogitsDir, ["general"], budget, allowIndependentGpuTopology: independent)); + var unchanged = JsonSerializer.Deserialize(await File.ReadAllTextAsync(f.MetricsPath)); + Assert.Equal(written.Evidence!.IdentityHash, unchanged!.Evidence!.IdentityHash); + } + + [Fact] + public async Task Materialized_output_is_content_checked_even_when_byte_length_matches() + { + using var f = await EvidenceFixture.CreateAsync(); + await f.WriteMeasurementAsync(); + long size = new FileInfo(f.CandidatePath).Length; + await EvidenceFixture.ReplaceAsync(f.CandidatePath, new string('z', checked((int)size))); + Assert.Equal(size, new FileInfo(f.CandidatePath).Length); + Assert.Null(await f.ReadAsync(f.CandidatePath)); + } + + [Fact] + public async Task Legacy_json_and_untagged_logs_never_become_current_evidence() + { + using var f = await EvidenceFixture.CreateAsync(); + await File.WriteAllTextAsync(f.MetricsPath, + "{\"ModelSizeBytes\":100,\"Perplexity\":{\"general\":{\"Ppl\":5,\"PplError\":0.1,\"Kld\":0.02}}}"); + await File.WriteAllTextAsync(Path.Combine(f.CandidateDir, "perplexity_general.log"), + "PPL = 5 +/- 0.1\nMean KLD: 0.02"); + Assert.Null(await f.ReadAsync()); + File.Delete(f.MetricsPath); + Assert.Null(await f.ReadAsync()); + } + + [Fact] + public async Task Native_reference_without_a_matching_content_sidecar_is_not_reusable() + { + using var f = await EvidenceFixture.CreateAsync(); + await f.WriteMeasurementAsync(); + File.Delete(Path.Combine(f.LogitsDir, "kld_logits_general.evidence.json")); + Assert.Null(await f.ReadAsync()); + await Assert.ThrowsAsync(() => BenchmarkEvidenceService.CreateAsync( + f.Quant, f.CandidatePath, f.CandidateDir, f.LogitsDir, ["general"])); + } + + [Fact] + public async Task Native_producer_can_regenerate_identity_for_legacy_or_missing_reference() + { + using var f = await EvidenceFixture.CreateAsync(); + File.Delete(Path.Combine(f.LogitsDir, "kld_logits_general.evidence.json")); + File.Delete(f.ReferencePath); + // Identity creation for saveLogits does not need the very artifact it must repair. + var native = await BenchmarkEvidenceService.CreateAsync(f.NativeQuant, f.NativePath, + f.NativeDir, f.LogitsDir, ["general"], saveLogits: true); + await File.WriteAllTextAsync(f.ReferencePath, "regenerated logits"); + await BenchmarkEvidenceService.WriteReferenceEvidenceAsync(native, f.LogitsDir, "general"); + await f.WriteMeasurementAsync(); + Assert.NotNull(await f.ReadAsync()); + } + + [Fact] + public async Task Frozen_text_overrides_are_exact_inputs_and_do_not_replace_discovery_corpus() + { + using var f = await EvidenceFixture.CreateAsync(); + string before = await File.ReadAllTextAsync(f.CorpusPath); + string holdout = Path.Combine(f.Root, "holdout.txt"); + await File.WriteAllTextAsync(holdout, "frozen held-out documents"); + var overrides = new Dictionary { ["general"] = holdout }; + var native = await BenchmarkEvidenceService.CreateAsync(f.NativeQuant, f.NativePath, + f.NativeDir, f.LogitsDir, ["general"], saveLogits: true, corpusOverrides: overrides); + await BenchmarkEvidenceService.WriteReferenceEvidenceAsync(native, f.LogitsDir, "general"); + var identity = await BenchmarkEvidenceService.CreateAsync(f.Quant, f.CandidatePath, + f.CandidateDir, f.LogitsDir, ["general"], corpusOverrides: overrides); + Assert.Equal(await BenchmarkEvidenceService.HashFileAsync(holdout), identity.Domains["general"].CorpusSha256); + Assert.Equal(before, await File.ReadAllTextAsync(f.CorpusPath)); + await Assert.ThrowsAsync(() => BenchmarkEvidenceService.CreateAsync( + f.Quant, f.CandidatePath, f.CandidateDir, f.LogitsDir, ["general"])); + Assert.Throws(() => BenchmarkEvidenceService.ResolveCorpusPath(f.CandidateDir, + "general", new Dictionary { ["typo"] = holdout })); + } + + [Fact] + public async Task In_process_imatrix_replacement_refreshes_previously_cached_identity() + { + using var f = await EvidenceFixture.CreateAsync(); + await f.ActivateImatrixAsync("calibration-A"); + string? first = await ImatrixIdentityService.EnsureActiveImatrixIdentityHashAsync(); + await EvidenceFixture.ReplaceAsync(Cache.ActiveImatrixPath!, "calibration-B"); + string? second = await ImatrixIdentityService.EnsureActiveImatrixIdentityHashAsync(); + Assert.NotEqual(first, second); + } + + [Fact] + public async Task Archive_preserves_old_measurement_and_logs_idempotently() + { + using var f = await EvidenceFixture.CreateAsync(); + await f.WriteMeasurementAsync(); + string old = await File.ReadAllTextAsync(f.MetricsPath); + await File.WriteAllTextAsync(Path.Combine(f.CandidateDir, "perplexity_general.log"), "old raw log"); + await BenchmarkEvidenceService.ArchiveExistingMetricsAsync(f.CandidateDir); + await BenchmarkEvidenceService.ArchiveExistingMetricsAsync(f.CandidateDir); + string archive = Assert.Single(Directory.GetDirectories(Path.Combine(f.CandidateDir, "history"))); + Assert.Equal(old, await File.ReadAllTextAsync(Path.Combine(archive, "bench_metrics.json"))); + Assert.Equal("old raw log", await File.ReadAllTextAsync(Path.Combine(archive, "perplexity_general.log"))); + } + + [Fact] + public async Task Scalar_contract_accepts_exact_zero_and_rejects_nonfinite_or_negative_values() + { + using var f = await EvidenceFixture.CreateAsync(); + var result = await f.WriteMeasurementAsync(); + result.Perplexity["general"].Kld = 0; + Assert.True(BenchmarkEvidenceService.HasValidMetrics(result, ["general"], true)); + foreach (double invalid in new[] { -0.001, double.NaN, double.PositiveInfinity }) + { + result.Perplexity["general"].Kld = invalid; + Assert.False(BenchmarkEvidenceService.HasValidMetrics(result, ["general"], true)); + } + result.Perplexity["general"].Kld = 0; + result.Perplexity["general"].Ppl = double.NaN; + Assert.False(BenchmarkEvidenceService.HasValidMetrics(result, ["general"], true)); + } + + [Fact] + public async Task Recorded_evidence_read_does_not_require_rediscovering_execution_hardware() + { + var previous = Cache.SysInfo; + try + { + Cache.SysInfo = new SystemInfo { ThreadCount = 12, RamGb = 32 }; + using var f = await EvidenceFixture.CreateAsync(); + var measured = await f.WriteMeasurementAsync(); + Cache.SysInfo = null; // validate-predictions does not run hardware/plan discovery. + Assert.True(await BenchmarkEvidenceService.IsCurrentAsync(f.Quant, measured.Evidence!.IdentityHash)); + // A request to run again still needs the current policy and reference to match. + Assert.Null(await f.ReadAsync()); + await EvidenceFixture.ReplaceAsync(f.CorpusPath, "changed source text"); + Assert.False(await BenchmarkEvidenceService.IsCurrentAsync(f.Quant, measured.Evidence.IdentityHash)); + } + finally { Cache.SysInfo = previous; } + } + + [Fact] + public async Task Hash_only_imatrix_context_selects_recorded_evidence_but_cannot_create_a_measurement() + { + using var f = await EvidenceFixture.CreateAsync(); + await f.ActivateImatrixAsync("calibration for read-only diagnosis"); + var measured = await f.WriteMeasurementAsync(); + string? identity = Cache.ActiveImatrixIdentityHash; + Cache.ActiveImatrixPath = null; + Assert.Equal(identity, await ImatrixIdentityService.EnsureActiveImatrixIdentityHashAsync()); + Assert.False(await BenchmarkEvidenceService.IsCurrentAsync(f.Quant, measured.Evidence!.IdentityHash)); + using (BenchmarkEvidenceService.BeginRecordedDiagnosticRead()) + Assert.True(await BenchmarkEvidenceService.IsCurrentAsync(f.Quant, measured.Evidence.IdentityHash)); + Assert.False(await BenchmarkEvidenceService.IsCurrentAsync(f.Quant, measured.Evidence.IdentityHash)); + Assert.Null(await f.ReadAsync()); + await Assert.ThrowsAsync(() => BenchmarkEvidenceService.CreateAsync( + f.Quant, f.CandidatePath, f.CandidateDir, f.LogitsDir, ["general"])); + } + + [Fact] + public async Task Live_reads_reject_changed_imatrix_application_even_when_artifact_hash_is_unchanged() + { + using var f = await EvidenceFixture.CreateAsync(); + await f.ActivateImatrixAsync("same calibration bytes"); + var measured = await f.WriteMeasurementAsync(); + Cache.UseImatrix = false; + Assert.False(await BenchmarkEvidenceService.IsCurrentAsync(f.Quant, measured.Evidence!.IdentityHash)); + using (BenchmarkEvidenceService.BeginRecordedDiagnosticRead()) + Assert.True(await BenchmarkEvidenceService.IsCurrentAsync(f.Quant, measured.Evidence.IdentityHash)); + } + + [Fact] + public async Task Native_carrier_comparison_has_quantizer_and_reference_identity_and_requires_kld() + { + using var f = await EvidenceFixture.CreateAsync(); + var compared = await BenchmarkEvidenceService.CreateAsync(f.NativeQuant, f.CandidatePath, + f.CandidateDir, f.LogitsDir, ["general"], saveLogits: false); + Assert.True(compared.CompareLogits); + Assert.NotNull(compared.Domains["general"].ReferenceLogitsSha256); + Assert.True(BenchmarkEvidenceService.RequiresComparison(f.NativeQuant, f.LogitsDir, false)); + Assert.False(BenchmarkEvidenceService.RequiresComparison(f.NativeQuant, f.LogitsDir, true)); + string quantizer = Path.Combine(f.BinDir, "llama-quantize" + (OperatingSystem.IsWindows() ? ".exe" : "")); + await EvidenceFixture.ReplaceAsync(quantizer, "changed quantizer even for a native-base clone"); + var changed = await BenchmarkEvidenceService.CreateAsync(f.NativeQuant, f.CandidatePath, + f.CandidateDir, f.LogitsDir, ["general"], saveLogits: false); + Assert.NotEqual(compared.RecipeHash, changed.RecipeHash); + await Assert.ThrowsAsync(() => BenchmarkEvidenceService.CreateAsync( + f.NativeQuant, f.CandidatePath, f.CandidateDir, f.LogitsDir, ["general"], saveLogits: true)); + } + + [Fact] + public async Task Native_repair_preserves_compact_evidence_and_prior_history_outside_deleted_directory() + { + using var f = await EvidenceFixture.CreateAsync(); + var native = new BenchmarkResult + { + Evidence = await BenchmarkEvidenceService.CreateAsync(f.NativeQuant, f.NativePath, + f.NativeDir, f.LogitsDir, ["general"], saveLogits: true), + ModelSizeBytes = (ulong)new FileInfo(f.NativePath).Length, + Perplexity = new() { ["general"] = new PplMetrics { Ppl = 5, PplError = 0.1 } } + }; + await BenchmarkEvidenceService.AtomicWriteAsync(Path.Combine(f.NativeDir, "bench_metrics.json"), native); + await File.WriteAllTextAsync(Path.Combine(f.NativeDir, "perplexity_general.log"), "native measurement log"); + await BenchmarkEvidenceService.ArchiveExistingMetricsAsync(f.NativeDir); + await BenchmarkEvidenceService.ArchiveForNativeRepairAsync(f.NativeDir); + Directory.Delete(f.NativeDir, recursive: true); + string archive = Path.Combine(f.Paths.BenchDir, "_evidence_history", "native-repair", "BF16"); + Assert.NotEmpty(Directory.GetFiles(archive, "bench_metrics.json", SearchOption.AllDirectories)); + Assert.NotEmpty(Directory.GetFiles(archive, "perplexity_general.log", SearchOption.AllDirectories)); + Assert.NotEmpty(Directory.GetFiles(archive, "kld_logits_general.evidence.json", SearchOption.AllDirectories)); + Assert.Empty(Directory.GetFiles(archive, "*.bin", SearchOption.AllDirectories)); + Assert.NotEmpty(Directory.GetDirectories(archive, "prior-history-*")); + } + + [Fact] + public void Equivalent_recipe_proof_requires_full_map_and_base_argument_equality() + { + var a = new Dictionary { ["tensor1"] = "Q4_K", ["tensor2"] = "Q8_0" }; + var b = new Dictionary { ["tensor2"] = "Q8_0", ["tensor1"] = "Q4_K" }; + Assert.True(QuantizationService.EquivalentConcreteRecipes("Q4_K_M", a, "Q4_K_M", b)); + Assert.False(QuantizationService.EquivalentConcreteRecipes("Q4_K_M", a, "Q5_K_M", b)); + b["tensor2"] = "Q6_K"; + Assert.False(QuantizationService.EquivalentConcreteRecipes("Q4_K_M", a, "Q4_K_M", b)); + b.Remove("tensor2"); + Assert.False(QuantizationService.EquivalentConcreteRecipes("Q4_K_M", a, "Q4_K_M", b)); + } + + [Fact] + public async Task Snapshot_queries_require_exact_imatrix_and_current_evidence() + { + using var f = await EvidenceFixture.CreateAsync(); + await using var db = new MagicQuantContext(); + var family = new ArchitectureFamily { NormalizedName = "evidence-fixture", DisplayName = "fixture" }; + var model = new AiModelHash { UniqueHash = Cache.CurrentModelId }; + db.AddRange(family, model); + await db.SaveChangesAsync(); + var profile = new TensorGroupProfile { ArchitectureFamilyId = family.Id, FingerprintHash = "profile", SnapshotJson = "{}" }; + var combo = new TensorCombo((TensorConfig)f.Quant); + db.AddRange(profile, combo); + await db.SaveChangesAsync(); + Cache.CurrentArchitectureFamilyId = family.Id; + Cache.CurrentTensorGroupProfileId = profile.Id; + + async Task AddAsync(string? matrix, double kld) + { + if (matrix == null) f.DisableImatrix(); + else await f.ActivateImatrixAsync(matrix); + int? matrixId = await ImatrixIdentityService.ResolveCurrentImatrixDefinitionIdAsync(db, model.Id, true); + var result = await f.WriteMeasurementAsync(kld); + var row = new AiBenchmark + { + ArchitectureFamilyId = family.Id, TensorGroupProfileId = profile.Id, AiModelHashId = model.Id, + TensorComboId = combo.Id, ImatrixDefinitionId = matrixId, SizeBytes = result.ModelSizeBytes!.Value, + EvidenceIdentityHash = result.Evidence!.IdentityHash + }; + row.CategorBenchmarks.Add(new CategoryBenchmark { AiBenchmarkId = row.Id, + Category = (byte)BenchmarkCategory.General, Kld = kld, Ppl = 5, PplError = 0.1 }); + db.Add(row); + await db.SaveChangesAsync(); + return result; + } + + var off = await AddAsync(null, 0.1); + var a = await AddAsync("A", 0.2); + var b = await AddAsync("B", 0.3); + var repository = new HybridBenchmarkRepository(); + foreach (var item in new[] { (Matrix: (string?)null, Result: off), (Matrix: (string?)"A", Result: a), (Matrix: (string?)"B", Result: b) }) + { + if (item.Matrix == null) f.DisableImatrix(); else await f.ActivateImatrixAsync(item.Matrix); + await BenchmarkEvidenceService.AtomicWriteAsync(f.MetricsPath, item.Result); + var snapshot = await repository.LoadBenchmarkSnapshotAsync((TensorConfig)f.Quant); + Assert.NotNull(snapshot); + Assert.Equal(item.Result.Perplexity["general"].Kld, snapshot.Kld); + Assert.Equal(item.Result.Evidence!.IdentityHash, snapshot.EvidenceIdentityHash); + Assert.Single(await repository.LoadAllBenchmarkSnapshotsForCurrentContextAsync()); + } + await f.ActivateImatrixAsync("C-no-row"); + Assert.Null(await repository.LoadBenchmarkSnapshotAsync((TensorConfig)f.Quant)); + Assert.Empty(await repository.LoadAllBenchmarkSnapshotsForCurrentContextAsync()); + + f.DisableImatrix(); + var legacy = await db.AiBenchmarks.FirstAsync(x => x.ImatrixDefinitionId == null); + legacy.EvidenceIdentityHash = null; + await db.SaveChangesAsync(); + await BenchmarkEvidenceService.AtomicWriteAsync(f.MetricsPath, off); + Assert.Null(await repository.LoadBenchmarkSnapshotAsync((TensorConfig)f.Quant)); + } +} + +internal sealed class EvidenceFixture : IDisposable +{ + private readonly string? _oldDirectory = Cache.MagicQuantDirectory, _oldModelDirectory = Cache.ModelDirectory, + _oldModelWork = Cache.ModelMagicQuantDirectory, _oldLlamaBin = Cache.LlamaBin, + _oldImatrixPath = Cache.ActiveImatrixPath, _oldImatrixHash = Cache.ActiveImatrixIdentityHash; + private readonly string _oldModelId = Cache.CurrentModelId; + private readonly bool _oldAvailable = Cache.IsImatrixAvailable, _oldUse = Cache.UseImatrix; + private readonly Cache.MainTorchType? _oldTorchType = Cache.TorchType; + private readonly int? _oldFamily = Cache.CurrentArchitectureFamilyId, _oldProfile = Cache.CurrentTensorGroupProfileId; + public string Root { get; } = Path.Combine(Path.GetTempPath(), "mq-evidence-" + Guid.NewGuid().ToString("N")); + public ModelArtifactPathService Paths { get; } = new(); + public HybridQuant Quant { get; } = HybridQuant.CreatePureBaseline(BaselineQuants.Q4_K_M); + public HybridQuant NativeQuant => HybridQuant.CreatePureBaseline(BaselineQuants.GetNativeQuant()); + public string NativePath => Paths.GetNativeBaseGgufPath(); + public string CandidatePath => Path.Combine(Root, "candidate.gguf"); + public string BinDir => Path.Combine(Root, "bin"); + public string PplExecutable => Path.Combine(BinDir, "llama-perplexity" + (OperatingSystem.IsWindows() ? ".exe" : "")); + public string CandidateDir => Paths.GetBenchmarkDir(QuantizationService.GetHybridName(Quant)); + public string NativeDir => Path.Combine(Paths.BenchDir, "BF16"); + public string CorpusPath => Path.Combine(Paths.BenchDir, "_ppl_corpora", "ppl_corpus_general.txt"); + public string LogitsDir => Paths.GetBaseLogitsDirectory(); + public string ReferencePath => Path.Combine(LogitsDir, "kld_logits_general.bin"); + public string MetricsPath => Path.Combine(CandidateDir, "bench_metrics.json"); + + private EvidenceFixture() + { + Cache.MagicQuantDirectory = Root; + Cache.ModelDirectory = Path.Combine(Root, "fixture-model"); + Cache.ModelMagicQuantDirectory = Path.Combine(Root, "model-work"); + Cache.CurrentModelId = "fixture-" + Guid.NewGuid().ToString("N"); + Cache.CurrentArchitectureFamilyId = null; + Cache.CurrentTensorGroupProfileId = null; + Cache.TorchType = Cache.MainTorchType.BF16; + Cache.LlamaBin = BinDir; + DisableImatrix(); + foreach (string dir in new[] { Paths.GgufDir, BinDir, CandidateDir, Path.GetDirectoryName(CorpusPath)!, LogitsDir }) + Directory.CreateDirectory(dir); + File.WriteAllText(NativePath, "native GGUF fixture bytes"); + File.WriteAllText(CandidatePath, "quantized GGUF fixture bytes"); + File.WriteAllText(CorpusPath, new string('a', 131072)); + foreach (string name in new[] { "llama-perplexity", "llama-quantize" }) + File.WriteAllText(Path.Combine(BinDir, name + (OperatingSystem.IsWindows() ? ".exe" : "")), "binary fixture " + name); + File.WriteAllText(ReferencePath, "native serialized logits fixture"); + } + + public static async Task CreateAsync() + { + var f = new EvidenceFixture(); + try + { + var reference = await BenchmarkEvidenceService.CreateAsync(f.NativeQuant, f.NativePath, + f.NativeDir, f.LogitsDir, ["general"], saveLogits: true); + await BenchmarkEvidenceService.WriteReferenceEvidenceAsync(reference, f.LogitsDir, "general"); + return f; + } + catch { f.Dispose(); throw; } + } + + public async Task WriteMeasurementAsync(double kld = 0.02) + { + var result = new BenchmarkResult + { + Evidence = await BenchmarkEvidenceService.CreateAsync(Quant, CandidatePath, CandidateDir, LogitsDir, ["general"]), + ModelSizeBytes = (ulong)new FileInfo(CandidatePath).Length, + Perplexity = new() { ["general"] = new PplMetrics { Ppl = 5, PplError = 0.1, Kld = kld } } + }; + await BenchmarkEvidenceService.AtomicWriteAsync(MetricsPath, result); + return result; + } + + public Task ReadAsync(string modelPath = "") + => BenchmarkEvidenceService.TryReadCompatibleResultAsync(Quant, modelPath, CandidateDir, LogitsDir, ["general"]); + + public async Task ActivateImatrixAsync(string content) + { + Cache.IsImatrixAvailable = Cache.UseImatrix = true; + Cache.ActiveImatrixPath = Path.Combine(Root, "active-imatrix.dat"); + await ReplaceAsync(Cache.ActiveImatrixPath, content); + Cache.ActiveImatrixIdentityHash = await BenchmarkEvidenceService.HashFileAsync(Cache.ActiveImatrixPath); + } + + public void DisableImatrix() + { + Cache.IsImatrixAvailable = Cache.UseImatrix = false; + Cache.ActiveImatrixPath = Cache.ActiveImatrixIdentityHash = null; + } + + public static async Task ReplaceAsync(string path, string contents) + { + DateTime stamp = File.Exists(path) ? File.GetLastWriteTimeUtc(path).AddSeconds(1) : DateTime.UtcNow; + await File.WriteAllTextAsync(path, contents); + File.SetLastWriteTimeUtc(path, stamp); + } + + public void Dispose() + { + Cache.MagicQuantDirectory = _oldDirectory; Cache.ModelDirectory = _oldModelDirectory; + Cache.ModelMagicQuantDirectory = _oldModelWork; Cache.CurrentModelId = _oldModelId; + Cache.LlamaBin = _oldLlamaBin; Cache.TorchType = _oldTorchType; + Cache.CurrentArchitectureFamilyId = _oldFamily; Cache.CurrentTensorGroupProfileId = _oldProfile; + Cache.IsImatrixAvailable = _oldAvailable; Cache.UseImatrix = _oldUse; + Cache.ActiveImatrixPath = _oldImatrixPath; Cache.ActiveImatrixIdentityHash = _oldImatrixHash; + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true); + } +} diff --git a/tests/MagicQuant.Tests/CloneArtifactEvidenceTests.cs b/tests/MagicQuant.Tests/CloneArtifactEvidenceTests.cs new file mode 100644 index 0000000..9157bf2 --- /dev/null +++ b/tests/MagicQuant.Tests/CloneArtifactEvidenceTests.cs @@ -0,0 +1,46 @@ +using MagicQuant.Services; +using Xunit; + +namespace MagicQuant.Tests; + +public sealed class CloneArtifactEvidenceTests +{ + [Fact] + public void Build_identity_changes_with_map_source_matrix_tool_and_subset_policy() + { + var map = new Dictionary { ["b"] = "Q4_K", ["a"] = "Q8_0" }; + string Hash(string source = "source", string tool = "tool", string? matrix = null, + bool subset = false, int threads = 4, IReadOnlyDictionary? tensors = null) => + CloneArtifactEvidenceService.ComputeRequestHash(source, tool, matrix, "Q8_0", tensors ?? map, subset, null, threads); + string identity = Hash(); + Assert.Equal(identity, Hash(tensors: new Dictionary { ["a"] = "q8_0", ["b"] = "q4_k" })); + Assert.NotEqual(identity, Hash(source: "different")); + Assert.NotEqual(identity, Hash(tool: "different")); + Assert.NotEqual(identity, Hash(matrix: "different")); + Assert.NotEqual(identity, Hash(subset: true)); + Assert.NotEqual(identity, Hash(threads: 8)); + Assert.NotEqual(identity, Hash(tensors: new Dictionary { ["a"] = "Q8_0", ["b"] = "Q5_K" })); + } + + [Fact] + public async Task Matching_size_is_not_a_build_proof_and_changed_bytes_invalidate_reuse() + { + string dir = Path.Combine(Path.GetTempPath(), "mq-clone-proof-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + string artifact = Path.Combine(dir, "artifact.gguf"), proof = Path.Combine(dir, "proof.json"); + await File.WriteAllTextAsync(artifact, "ABCD"); + Assert.False(await CloneArtifactEvidenceService.CanReuseAsync(artifact, proof, "request")); + await CloneArtifactEvidenceService.WriteAsync(artifact, proof, "request"); + Assert.True(await CloneArtifactEvidenceService.CanReuseAsync(artifact, proof, "request")); + Assert.False(await CloneArtifactEvidenceService.CanReuseAsync(artifact, proof, "other-request")); + await File.WriteAllTextAsync(artifact, "WXYZ"); + File.SetLastWriteTimeUtc(artifact, DateTime.UtcNow.AddSeconds(2)); + Assert.False(await CloneArtifactEvidenceService.CanReuseAsync(artifact, proof, "request")); + await File.WriteAllTextAsync(proof, "broken"); + Assert.False(await CloneArtifactEvidenceService.CanReuseAsync(artifact, proof, "request")); + } + finally { Directory.Delete(dir, recursive: true); } + } +} diff --git a/tests/MagicQuant.Tests/HardwareInitializationTests.cs b/tests/MagicQuant.Tests/HardwareInitializationTests.cs index c1037b0..76931f1 100644 --- a/tests/MagicQuant.Tests/HardwareInitializationTests.cs +++ b/tests/MagicQuant.Tests/HardwareInitializationTests.cs @@ -2,6 +2,8 @@ using MagicQuant.Configuration; using MagicQuant.Models; using MQ.DB; +using MQ.DB.Models; +using Spectre.Console; using Xunit; namespace MagicQuant.Tests; @@ -15,6 +17,31 @@ public sealed class HardwareInitializationCollection [Collection(HardwareInitializationCollection.Name)] public sealed class HardwareInitializationTests { + [Theory] + [InlineData("Intel [8086:7113]")] + [InlineData("[red]Device[/]")] + public void Hardware_labels_are_rendered_literally_without_interpreting_markup(string label) + { + using var output = new StringWriter(); + var console = AnsiConsole.Create(new AnsiConsoleSettings + { + Ansi = AnsiSupport.No, + Out = new AnsiConsoleOutput(output) + }); + var system = new SystemInfo + { + RamGb = 64, + ThreadCount = 4, + GpuInfo = [new GpuInfo { GpuVendor = GpuVendor.Intel, GpuName = label, VramGb = 8 }] + }; + + InitializeLlamaCpp.WriteSystemInfo(console, system); + + Assert.Contains(label, output.ToString()); + Assert.Contains("Detected GPU:", output.ToString()); + Assert.Contains("Detected RAM:", output.ToString()); + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/tests/MagicQuant.Tests/PredictionDiagnosticContextTests.cs b/tests/MagicQuant.Tests/PredictionDiagnosticContextTests.cs new file mode 100644 index 0000000..d84541a --- /dev/null +++ b/tests/MagicQuant.Tests/PredictionDiagnosticContextTests.cs @@ -0,0 +1,143 @@ +using MagicQuant.Models; +using MagicQuant.Services; +using MQ.DB; +using MQ.DB.Models; +using MQ.DB.Models.DbModels; +using Xunit; + +namespace MagicQuant.Tests; + +public sealed class PredictionDiagnosticContextTests +{ + private static readonly string[] NativeNames = ["token_embd.weight", "output.weight", "blk.0.attn_q.weight"]; + + [Fact] + public void Existing_exact_profile_is_selected_without_changing_which_profile_is_active() + { + using var state = new RuntimeState(); + var family = Family(); + var matching = Profile(isActive: false); + var unrelatedActive = new TensorGroupProfile + { + Id = 99, ArchitectureFamilyId = family.Id, FingerprintHash = "other-rules", IsActive = true + }; + PredictionDiagnosticContextService.InitializeFromExistingRows( + family, [unrelatedActive, matching], [], NativeNames); + + Assert.Equal(matching.Id, Cache.CurrentTensorGroupProfileId); + Assert.Equal(matching.FingerprintHash, Cache.CurrentTensorGroupProfileFingerprintHash); + Assert.False(matching.IsActive); + Assert.True(unrelatedActive.IsActive); + Assert.Equal(family.Id, Cache.CurrentArchitectureFamilyId); + } + + [Fact] + public void Persisted_custom_ids_are_hydrated_even_when_inactive_and_other_families_are_ignored() + { + using var state = new RuntimeState(); + var definition = Definition(100, Family().Id, "custom:diagnostic:repo:baseline.gguf"); + var foreign = Definition(101, Family().Id + 1, "custom:foreign:repo:baseline.gguf"); + PredictionDiagnosticContextService.InitializeFromExistingRows( + Family(), [Profile()], [definition, foreign], NativeNames); + + var restored = BaselineQuants.FromId(100); + Assert.Equal(definition.CanonicalKey, restored.CanonicalKey); + Assert.True(restored.IsExternalRepositoryBaseline); + Assert.False(restored.IsLearningBaseline); + Assert.DoesNotContain(BaselineQuants.GetAllRecognizedBaselines(), x => x.CanonicalKey == foreign.CanonicalKey); + var quant = (HybridQuant)new TensorConfig(BaselineQuants.Q8_0.UniqueId, + BaselineQuants.EncodeTensorConfigGroupSlot(restored), 0, 0, 0, 0, 0, 0, 0, 0); + Assert.Equal(definition.CanonicalKey, Assert.Single(quant.Tensors).CandidateBaseline!.CanonicalKey); + Assert.False(definition.IsActiveInCurrentConfig); + } + + [Fact] + public void Native_tensor_names_restore_the_same_active_group_coordinate_shape() + { + using var state = new RuntimeState(); + PredictionDiagnosticContextService.InitializeFromExistingRows(Family(), [Profile()], [], NativeNames); + + var active = TReg.All.Where(x => !Cache.UnusedTensorGroups.Any(u => u.UniqueId == x.UniqueId)).ToList(); + Assert.Equal(new[] { TReg.Embeddings.UniqueId, TReg.LmHead.UniqueId, TReg.AttnQ.UniqueId }, + active.Select(x => x.UniqueId)); + var pure = (TensorConfig)HybridQuant.CreatePureBaseline(BaselineQuants.Q8_0); + Assert.Equal(3, RankSafeKldPredictionService.EnumerateEffectiveBaselines(pure).Count); + var baseOnly = (TensorConfig)HybridQuant.CreateExactBlanket( + BaselineQuants.Q8_0, active, TensorWeightScheme.BF16); + Assert.NotEqual(0, baseOnly.AttnQ); + Assert.Equal(0, baseOnly.FfnDown); + Assert.Equal(0, baseOnly.MoeExperts); + } + + [Fact] + public void Missing_matching_profile_or_wrong_native_signature_fails_instead_of_creating_scope() + { + using var state = new RuntimeState(); + var noProfile = Assert.Throws(() => + PredictionDiagnosticContextService.InitializeFromExistingRows(Family(), [], [], NativeNames)); + Assert.Contains("No existing tensor-group profile", noProfile.Message); + Assert.Null(Cache.CurrentTensorGroupProfileId); + + var wrongNative = Assert.Throws(() => + PredictionDiagnosticContextService.InitializeFromExistingRows(Family(), [Profile()], [], ["other.weight"])); + Assert.Contains("native GGUF tensor names", wrongNative.Message); + Assert.Null(Cache.CurrentTensorGroupProfileId); + + Cache.CurrentArchitectureFamilyName = "different-family"; + Assert.Throws(() => + PredictionDiagnosticContextService.InitializeFromExistingRows(Family(), [Profile()], [], NativeNames)); + Assert.Null(Cache.CurrentTensorGroupProfileId); + } + + private static ArchitectureFamily Family() => new() + { + Id = 7, DisplayName = "diagnostic-family", NormalizedName = "diagnostic-family", + TensorCount = NativeNames.Length, + TensorSignatureHash = TensorConfigIdentity.StableHash(string.Join("\n", NativeNames.OrderBy(x => x, StringComparer.Ordinal))) + }; + + private static TensorGroupProfile Profile(bool isActive = true) => new() + { + Id = 17, ArchitectureFamilyId = Family().Id, IsActive = isActive, + FingerprintHash = TensorGroupProfileService.ComputeSnapshotHash(TensorGroupProfileService.BuildSnapshotJson()) + }; + + private static BaselineQuantDefinition Definition(byte id, int familyId, string canonicalKey) => new() + { + RuntimeBaselineId = id, ArchitectureFamilyId = familyId, + CanonicalKey = canonicalKey, IsCustomBaseline = true, IsActiveInCurrentConfig = false, + BaselineName = "Test Q4", DisplayName = "Test Q4", QuantizeBaseArgumentName = "Q4_K_M", + SourceKind = "huggingface", SourceRepository = "example/test", SourceFileName = "baseline.gguf", + DefaultTensorSchemeId = BaselineQuants.Q4_K_M.DefaultTensorScheme!.UniqueId, BitRange = 4 + }; + + private sealed class RuntimeState : IDisposable + { + private readonly string _familyName = Cache.CurrentArchitectureFamilyName; + private readonly int? _familyId = Cache.CurrentArchitectureFamilyId; + private readonly int? _profileId = Cache.CurrentTensorGroupProfileId; + private readonly string? _fingerprint = Cache.CurrentTensorGroupProfileFingerprintHash; + private readonly List _unused = Cache.UnusedTensorGroups.ToList(); + private readonly List _custom = BaselineQuants.GetAllRecognizedBaselines().Where(x => x.IsCustomBaseline).ToList(); + + public RuntimeState() + { + Cache.CurrentArchitectureFamilyName = string.Empty; + Cache.CurrentArchitectureFamilyId = null; + Cache.CurrentTensorGroupProfileId = null; + Cache.CurrentTensorGroupProfileFingerprintHash = null; + } + + public void Dispose() + { + Cache.CurrentArchitectureFamilyName = _familyName; + Cache.CurrentArchitectureFamilyId = _familyId; + Cache.CurrentTensorGroupProfileId = _profileId; + Cache.CurrentTensorGroupProfileFingerprintHash = _fingerprint; + Cache.UnusedTensorGroups.Clear(); + Cache.UnusedTensorGroups.AddRange(_unused); + BaselineQuants.ResetDynamicCustomBaselines(); + foreach (var baseline in _custom) BaselineQuants.RegisterDynamicCustomBaseline(baseline); + } + } +} diff --git a/tests/MagicQuant.Tests/PredictionDiagnosticTests.cs b/tests/MagicQuant.Tests/PredictionDiagnosticTests.cs new file mode 100644 index 0000000..77247c8 --- /dev/null +++ b/tests/MagicQuant.Tests/PredictionDiagnosticTests.cs @@ -0,0 +1,286 @@ +using System.Globalization; +using System.Text.Json; +using DuckDB.NET.Data; +using MagicQuant.Configuration; +using MagicQuant.Models; +using MagicQuant.Services; +using MQ.DB.Models; +using Xunit; + +namespace MagicQuant.Tests; + +public sealed class PredictionDiagnosticTests +{ + [Fact] + public void A_constant_predictor_gets_half_credit_and_no_defined_tau() + { + var summary = PredictionValidationService.BuildSummary( + [Row(.01, .02), Row(.02, .02), Row(.03, .02)]); + + Assert.Equal(50d, summary.PairwiseAccuracyPercent); + Assert.Null(summary.KendallTauB); + Assert.Equal(3, summary.OrderableActualPairs); + Assert.Equal(3, summary.TiedPredictedPairs); + Assert.Equal(0, summary.ConcordantPairs); + } + + [Fact] + public void Actual_ties_are_not_counted_as_correct_predictions() + { + // One actual-only tie, two concordant pairs. Tau-b penalizes the tie. + var summary = PredictionValidationService.BuildSummary( + [Row(.01, .01), Row(.01, .02), Row(.03, .03)]); + Assert.Equal(100d, summary.PairwiseAccuracyPercent); + Assert.Equal(2, summary.ConcordantPairs); + Assert.Equal(2, summary.OrderableActualPairs); + Assert.Equal(1, summary.TiedActualPairs); + Assert.Equal(2d / Math.Sqrt(6d), summary.KendallTauB!.Value, 12); + + var noOrder = PredictionValidationService.BuildSummary([Row(.01, .01), Row(.01, .02)]); + Assert.Null(noOrder.PairwiseAccuracyPercent); + Assert.Null(noOrder.KendallTauB); + Assert.Equal(0, noOrder.ConcordantPairs); + } + + [Fact] + public void Incomplete_rows_remain_in_coverage_and_undefined_metrics_are_null() + { + var missing = Row(.01, double.PositiveInfinity); + missing.IsPredictable = false; + var summary = PredictionValidationService.BuildSummary([missing]); + Assert.Equal(1, summary.RowCount); + Assert.Equal(0, summary.PredictableCount); + Assert.Equal(1, summary.UnpredictableCount); + Assert.Equal(1, summary.SizePredictableCount); + Assert.Null(summary.Mae); + Assert.Null(summary.Rmse); + Assert.Null(summary.PairwiseAccuracyPercent); + + var mixed = PredictionValidationService.BuildSummary([missing, Row(.01, .02)]); + Assert.Equal(2, mixed.RowCount); + Assert.Equal(1, mixed.PredictableCount); + Assert.Equal(.01d, mixed.Mae!.Value, 12); + } + + [Fact] + public void Json_preserves_raw_scores_coverage_and_honest_diagnostic_scope() + { + var scored = Row(.011, .0155); + scored.AdditiveKld = .01; + scored.InteractionKld = .02; + scored.ProjectedKld = .0155; + var missing = Row(.025, double.PositiveInfinity); + missing.IsPredictable = false; + missing.InteractionKld = missing.ProjectedKld = double.PositiveInfinity; + var rows = new[] { scored, missing }; + var predictions = new RankSafePredictionSet { Rows = rows, FitTrainingConfigKeys = ["training-only"] }; + using var json = JsonDocument.Parse(PredictionValidationService.BuildJson( + PredictionValidationService.BuildSummary(rows), rows, predictions, + "coefficient_holdout_subset_diagnostic", ["held-out"])); + var root = json.RootElement; + Assert.Equal(1, root.GetProperty("schema_version").GetInt32()); + Assert.Equal("coefficient_holdout_subset_diagnostic", root.GetProperty("mode").GetString()); + Assert.False(root.GetProperty("production_replay").GetBoolean()); + Assert.Equal(2, root.GetProperty("summary").GetProperty("row_count").GetInt32()); + var records = root.GetProperty("records"); + Assert.Equal(.02, records[0].GetProperty("raw_interaction_kld").GetDouble()); + Assert.Equal(.0155, records[0].GetProperty("projected_kld").GetDouble()); + Assert.True(records[0].GetProperty("projection_changed_score").GetBoolean()); + Assert.Equal(JsonValueKind.Null, records[0].GetProperty("selection_eligible").ValueKind); + Assert.Equal("incomplete", records[1].GetProperty("prediction_coverage").GetString()); + Assert.Equal(JsonValueKind.Null, records[1].GetProperty("predicted_kld").ValueKind); + } + + [Fact] + public void Quantized_pure_KLD_is_a_target_not_an_input_feature_and_native_stays_zero() + { + var first = Model(pureQ8Kld: .9); + var second = Model(pureQ8Kld: 9d); + TensorConfig pureQ8 = first.PureQ8.Config; + var a = RankSafeKldPredictionService.PredictFromContext(pureQ8, first, new()); + var b = RankSafeKldPredictionService.PredictFromContext(pureQ8, second, new()); + + Assert.Equal(.011, a.AdditiveKld, 12); + Assert.Equal(a.AdditiveKld, b.AdditiveKld); + Assert.Equal(TensorConfigIdentity.ToKey(pureQ8), TensorConfigIdentity.ToKey(a.Config)); + Assert.NotEqual(TensorConfigIdentity.ToKey(a.Config), TensorConfigIdentity.ToKey(a.PredictionConfig)); + Assert.Equal(BaselineQuants.EncodeTensorConfigGroupSlot(BaselineQuants.Q8_0), a.PredictionConfig.Embeddings); + Assert.Contains(a.Notes, note => note.Contains("parity of uncovered tensor assignments", StringComparison.Ordinal)); + + var native = RankSafeKldPredictionService.PredictFromContext( + first.PureSnapshotsByBaselineId[BaselineQuants.BF16_Hybrid.UniqueId].Config, first, new()); + Assert.Equal(0d, native.AdditiveKld); + Assert.Equal(0d, native.PredictedKld); + } + + [Fact] + public void Coefficient_holdout_removes_targets_and_canonical_aliases_before_fitting() + { + var previous = Config.Current; + var config = MagicQuantYamlConfig.CreateDefault(); + config.Prediction.MinimumFitRows = 3; + Config.Load(config); + try + { + var model = Model(); + var original = Recipe(BaselineQuants.Q4_K_M, BaselineQuants.Q6_K, null); + Assert.True(RankSafeKldPredictionService.TryCanonicalizeBenchmarkSnapshotConfigForPrediction( + original, model, out var canonical, out _)); + var excluded = RankSafeKldPredictionService.BuildFitExclusionKeys(model, [original]); + Assert.Contains(TensorConfigIdentity.ToKey(original), excluded); + Assert.Contains(TensorConfigIdentity.ToKey(canonical), excluded); + + var training = new[] + { + Snapshot(Recipe(BaselineQuants.Q8_0, BaselineQuants.Q4_K_M, BaselineQuants.Q4_K_M), .03), + Snapshot(Recipe(BaselineQuants.Q8_0, BaselineQuants.Q6_K, BaselineQuants.Q6_K), .02), + Snapshot(Recipe(BaselineQuants.Q8_0, BaselineQuants.Q8_0, BaselineQuants.Q6_K), .016) + }; + var before = RankSafeKldPredictionService.BuildFitRows(model, + training.Concat([Snapshot(original, .001), Snapshot(canonical, .002)]).ToList(), excluded); + var after = RankSafeKldPredictionService.BuildFitRows(model, + training.Concat([Snapshot(original, 1000), Snapshot(canonical, 2000)]).ToList(), excluded); + Assert.Equal(3, before.Count); + Assert.DoesNotContain(before, row => excluded.Contains(TensorConfigIdentity.ToKey(row.Config))); + var fitBefore = RankSafeKldPredictionService.FitInteractionModel(before, model); + var fitAfter = RankSafeKldPredictionService.FitInteractionModel(after, model); + Assert.False(fitBefore.UsedFallback); + Assert.Equal(fitBefore.Alpha, fitAfter.Alpha); + Assert.Equal(fitBefore.Beta, fitAfter.Beta); + Assert.Equal(fitBefore.BitStressThreshold, fitAfter.BitStressThreshold); + Assert.Equal(fitBefore.FitMae, fitAfter.FitMae); + } + finally { Config.Load(previous); } + } + + [Fact] + public void Input_feature_observations_cannot_be_mislabelled_as_held_out() + { + var model = Model(); + foreach (var snapshot in new[] { model.PureQ8, model.Q8BaseOnly, model.IsolationByGroupAndBaseline.Values.First() }) + { + var error = Assert.Throws(() => + RankSafeKldPredictionService.BuildFitExclusionKeys(model, [snapshot.Config])); + Assert.Contains("input to prediction", error.Message); + } + } + + [Fact] + public async Task Sql_materialization_retains_raw_interaction_reversal_and_matches_Csharp_projection() + { + using var connection = new DuckDBConnection("Data Source=:memory:"); + await connection.OpenAsync(); + var a = Recipe(BaselineQuants.Q8_0, BaselineQuants.Q4_K_M, BaselineQuants.Q4_K_M); + var b = Recipe(BaselineQuants.Q8_0, BaselineQuants.Q6_K, BaselineQuants.Q6_K); + using (var command = connection.CreateCommand()) + { + command.CommandText = CombinationDuckDbSchema.CreateTableSql + $""" + INSERT INTO tensor_configs ({CombinationDuckDbSchema.SlotColumnList}) VALUES ({SqlSlots(a)}), ({SqlSlots(b)}); + CREATE TEMP TABLE temp_prediction_work AS + SELECT *, CAST(ROW_NUMBER() OVER (ORDER BY Embeddings) AS UBIGINT) AS PredictionWorkId, + CASE WHEN Embeddings = {a.Embeddings} THEN 0.010 ELSE 0.011 END AS AdditiveKldWork + FROM tensor_configs; + UPDATE temp_prediction_work SET AdditiveKld = AdditiveKldWork; + CREATE TEMP TABLE temp_work_cross_term AS + SELECT PredictionWorkId, CASE WHEN Embeddings = {a.Embeddings} THEN 0.0004 ELSE 0.0 END AS CrossTerm + FROM temp_prediction_work; + CREATE TEMP TABLE temp_prediction_order AS + SELECT CAST(ROW_NUMBER() OVER (ORDER BY AdditiveKld) AS UBIGINT) AS PredictionOrdinal, + PredictionWorkId, AdditiveKld, + CASE WHEN Embeddings = {a.Embeddings} THEN 0.020 ELSE 0.011 END AS InteractionKld, + CAST(CASE WHEN Embeddings = {a.Embeddings} THEN 200 ELSE 100 END AS UBIGINT) AS PredictedSizeBytes + FROM temp_prediction_work; + """; + await command.ExecuteNonQueryAsync(); + } + await DuckDbPredictionMaterializationService.BuildPavaBlocksAsync(connection, default); + await DuckDbPredictionMaterializationService.PersistProjectedPredictionsAsync(connection, Model(), default); + + var first = Row(.02, .02); + first.AdditiveKld = .010; + first.InteractionKld = .020; + first.PredictedSizeBytes = 200; + var second = Row(.011, .011); + second.AdditiveKld = .011; + second.InteractionKld = .011; + second.PredictedSizeBytes = 100; + RankSafeKldPredictionService.ApplyRankSafeProjection([first, second]); + Assert.Equal(.0155, first.ProjectedKld, 12); + Assert.Equal(first.ProjectedKld, second.ProjectedKld); + + using var verify = connection.CreateCommand(); + verify.CommandText = "SELECT AdditiveKld, CrossTerm, RawInteractionKld, ProjectedKld, PredictedKld, FinalPredictedKld, PredictionRank FROM tensor_configs ORDER BY AdditiveKld;"; + using var reader = await verify.ExecuteReaderAsync(); + Assert.True(await reader.ReadAsync()); + Assert.Equal(.010, Convert.ToDouble(reader.GetValue(0)), 12); + Assert.Equal(.0004, Convert.ToDouble(reader.GetValue(1)), 12); + Assert.Equal(.020, Convert.ToDouble(reader.GetValue(2)), 12); + Assert.Equal(first.ProjectedKld, Convert.ToDouble(reader.GetValue(3)), 12); + Assert.Equal(first.ProjectedKld, Convert.ToDouble(reader.GetValue(4)), 12); + Assert.Equal(first.ProjectedKld, Convert.ToDouble(reader.GetValue(5)), 12); + Assert.Equal(2UL, Convert.ToUInt64(reader.GetValue(6))); // Smaller tied candidate goes first. + Assert.True(await reader.ReadAsync()); + Assert.Equal(.011, Convert.ToDouble(reader.GetValue(2)), 12); + Assert.Equal(second.ProjectedKld, Convert.ToDouble(reader.GetValue(3)), 12); + Assert.Equal(1UL, Convert.ToUInt64(reader.GetValue(6))); + } + + [Fact] + public void Subset_projection_is_not_a_frozen_production_score() + { + var whole = RankSafeKldPredictionService.Pava([.02, .011]); + var subset = RankSafeKldPredictionService.Pava([.011]); + Assert.Equal(.0155, whole[1], 12); + Assert.Equal(.011, subset[0]); + Assert.NotEqual(whole[1], subset[0]); + } + + private static RankSafePredictionRow Row(double actual, double predicted) => new() + { + Config = Recipe(BaselineQuants.Q8_0, BaselineQuants.Q6_K, BaselineQuants.Q4_K_M), + PredictionConfig = Recipe(BaselineQuants.Q8_0, BaselineQuants.Q6_K, BaselineQuants.Q4_K_M), + ActualKld = actual, + PredictedKld = predicted, + ActualSizeBytes = 1000, + PredictedSizeBytes = 1000 + }; + + private static TensorConfig Recipe(BaselineQuants carrier, BaselineQuants? embeddings, BaselineQuants? lmHead) => new( + carrier.UniqueId, + embeddings is null ? (byte)0 : BaselineQuants.EncodeTensorConfigGroupSlot(embeddings), + lmHead is null ? (byte)0 : BaselineQuants.EncodeTensorConfigGroupSlot(lmHead), + 0, 0, 0, 0, 0, 0, 0); + + private static BenchmarkSnapshotRecord Snapshot(TensorConfig config, double kld, ulong size = 900_000) => new() + { + Config = config, + Quant = (HybridQuant)config, + Kld = kld, + Ppl = 10, + SizeBytes = size + }; + + private static RankSafeKldPredictionService.RankSafePredictionModel Model(double pureQ8Kld = .9) + { + TensorGroup[] groups = [TReg.Embeddings, TReg.LmHead]; + var q8 = Snapshot(Recipe(BaselineQuants.Q8_0, null, null), pureQ8Kld); + var native = Snapshot(Recipe(BaselineQuants.BF16_Hybrid, null, null), 9d, 1_000_000); + var baseOnly = Snapshot(Recipe(BaselineQuants.Q8_0, BaselineQuants.BF16_Hybrid, BaselineQuants.BF16_Hybrid), .003, 1_000_000); + var isolation = new Dictionary<(byte GroupId, byte BaselineId), BenchmarkSnapshotRecord>(); + var baselines = new[] { BaselineQuants.Q8_0, BaselineQuants.Q6_K, BaselineQuants.Q4_K_M }; + for (int i = 0; i < baselines.Length; i++) + { + var baseline = baselines[i]; + isolation[(TReg.Embeddings.UniqueId, baseline.UniqueId)] = Snapshot( + Recipe(BaselineQuants.Q8_0, baseline, BaselineQuants.BF16_Hybrid), .005 * (i + 1)); + isolation[(TReg.LmHead.UniqueId, baseline.UniqueId)] = Snapshot( + Recipe(BaselineQuants.Q8_0, BaselineQuants.BF16_Hybrid, baseline), .006 * (i + 1)); + } + return new(groups, q8, baseOnly, + new() { [BaselineQuants.Q8_0.UniqueId] = q8, [BaselineQuants.BF16_Hybrid.UniqueId] = native }, + new() { [BaselineQuants.Q8_0.UniqueId] = baseOnly }, isolation, new(), Array.Empty()); + } + + private static string SqlSlots(TensorConfig config) => string.Join(", ", + TensorConfigIdentity.ToKey(config).Split(':').Select(x => byte.Parse(x, CultureInfo.InvariantCulture))); +} diff --git a/tests/MagicQuant.Tests/SearchDiscoveryCorrectnessTests.cs b/tests/MagicQuant.Tests/SearchDiscoveryCorrectnessTests.cs new file mode 100644 index 0000000..cc111e0 --- /dev/null +++ b/tests/MagicQuant.Tests/SearchDiscoveryCorrectnessTests.cs @@ -0,0 +1,296 @@ +using DuckDB.NET.Data; +using MagicQuant.Configuration; +using MagicQuant.Helpers; +using MagicQuant.Models; +using MagicQuant.Services; +using MQ.DB; +using MQ.DB.Models; +using MQ.DB.Models.DbModels; +using Xunit; + +namespace MagicQuant.Tests; + +public sealed class SearchDiscoveryCorrectnessTests +{ + [Fact] + public async Task Sql_filters_near_anchor_requirement_before_limit_and_counts_the_full_eligible_pool() + { + using var context = new CandidateDatabaseScope(); + var smaller = PredictionAnchor(10_000, 0.11); + var larger = PredictionAnchor(20_000, 0.01); + var last = Recipe(BaselineQuants.Q4_K_M); + var variedGroups = new[] { TReg.Embeddings, TReg.LmHead, TReg.AttnQ, TReg.AttnOutput, + TReg.FfnUpGate, TReg.FfnDown, TReg.MoeExperts }; + var configs = Enumerable.Range(0, 125).Select(index => + { + var quant = (HybridQuant)Recipe(BaselineQuants.Q6_K); + for (int bit = 0; bit < variedGroups.Length; bit++) + quant.SetLearnedCandidateOverride(variedGroups[bit], + (index & (1 << bit)) == 0 ? BaselineQuants.Q6_K : BaselineQuants.Q5_K); + return (TensorConfig)quant; + }).Append(last).ToList(); + var store = new RemainingCombinationStore(); + Assert.Equal(126, configs.Select(TensorConfigIdentity.ToKey).Distinct().Count()); + await store.ReplaceAllAsync(configs, "regression fixture"); + + using (var connection = new DuckDBConnection($"Data Source={store.GetDatabaseFilePath()}")) + { + await connection.OpenAsync(); + using var command = connection.CreateCommand(); + // Every row beats the line. The 125 higher-ranked rows fail the + // near-anchor requirement; only the row beyond the old LIMIT passes. + command.CommandText = """ + UPDATE tensor_configs SET PredictedKld = 0.1041, PredictedSizeBytes = 10100, + PredictionConfidence = 1, PredictionRank = 1; + """; + await command.ExecuteNonQueryAsync(); + command.CommandText = """ + UPDATE tensor_configs SET PredictedKld = 0.057, PredictedSizeBytes = 15000, + PredictionRank = 126 WHERE AttnKV = ?; + """; + command.Parameters.Add(new DuckDBParameter { Value = last.AttnKV }); + await command.ExecuteNonQueryAsync(); + } + + Assert.Equal(126L, await store.CountBetterThanLinearCandidatesAsync(smaller, larger, 10_000, 20_000)); + Assert.Equal(1L, await store.CountBetterThanLinearCandidatesAsync(smaller, larger, + 10_000, 20_000, 10_000, 20_000, applyNearAnchorRequirement: true)); + var rows = await store.QueryBetterThanLinearCandidatesAsync( + Snapshot(smaller.Config, 10_000, 0.11), Snapshot(larger.Config, 20_000, 0.01), smaller, larger, + 10_000, 20_000, 10_000, 20_000, HybridSelectionReason.InteriorSubspaceDiscovery, + "regression", 125); + Assert.Equal(TensorConfigIdentity.ToKey(last), TensorConfigIdentity.ToKey(Assert.Single(rows).Prediction.Config)); + + Assert.Equal(0L, await store.CountBetterThanLinearCandidatesAsync(smaller, larger, + 10_000, 11_000, 15_000, 16_000, applyNearAnchorRequirement: true)); + Assert.Empty(await store.QueryBetterThanLinearCandidatesAsync( + Snapshot(smaller.Config, 10_000, 0.11), Snapshot(larger.Config, 20_000, 0.01), smaller, larger, + 10_000, 11_000, 15_000, 16_000, HybridSelectionReason.InteriorSubspaceDiscovery, "empty", 125)); + } + + [Fact] + public async Task Sql_and_in_memory_near_anchor_conditions_agree_at_boundaries_and_zero_span() + { + var previous = Config.Current; + Config.Load(MagicQuantYamlConfig.CreateDefault()); + try + { + using var connection = new DuckDBConnection("Data Source=:memory:"); + await connection.OpenAsync(); + foreach (var requirement in new[] + { + NearAnchorGainRequirement.Create(PredictionAnchor(10_000, .11), PredictionAnchor(20_000, .01)), + NearAnchorGainRequirement.Create(PredictionAnchor(10_000, .11), PredictionAnchor(10_000, .01)), + new NearAnchorGainRequirement(ulong.MaxValue - 10_000, 10_000, .02, .005) + }) + { + foreach (var (distance, gain) in new[] + { + (0UL, requirement.RequiredGain - 1e-6), + (200UL, requirement.RequiredGain), + (200UL, requirement.RequiredGain - 1e-6), + (201UL, 0d) + }) + { + ulong size = requirement.SmallAnchorSize + distance; + using var command = connection.CreateCommand(); + command.CommandText = $"SELECT {NearAnchorGainRequirement.SqlPredicate} FROM " + + "(SELECT CAST(? AS UBIGINT) AS PredictedSizeBytes, CAST(? AS DOUBLE) AS Gain) candidate;"; + foreach (var value in requirement.SqlParameters.Append((object)size).Append(gain)) + command.Parameters.Add(new DuckDBParameter { Value = value }); + bool actual = Convert.ToBoolean(await command.ExecuteScalarAsync()); + Assert.Equal(requirement.Passes(size, gain), actual); + } + } + } + finally { Config.Load(previous); } + } + + [Theory] + [InlineData(false, 17_000UL)] + [InlineData(true, 20_000UL)] + public void Complete_coverage_extends_the_last_window_without_adding_attempt_windows(bool enabled, ulong expectedEnd) + { + ulong first = InteriorWindowPlanner.End(10_000, 20_000, 10_000, .35, false, enabled); + ulong second = InteriorWindowPlanner.End(10_000, 20_000, first, .35, true, enabled); + Assert.Equal(13_500UL, first); + Assert.Equal(expectedEnd, second); + Assert.Equal(10_000UL, InteriorWindowPlanner.End(10_000, 10_000, 10_000, .35, true, enabled)); + Assert.Equal(ulong.MaxValue, InteriorWindowPlanner.End(ulong.MaxValue - 100, ulong.MaxValue, + ulong.MaxValue - 1, 1, true, enabled)); + } + + [Fact] + public void Rescue_preserves_the_published_KV_improvement_but_rejects_worse_or_invalid_states() + { + var evidence = RescueEvidence(); + var queue = IsolationRescuePlanner.Select(new[] + { + evidence, + evidence with { CandidateBaselineId = BaselineQuants.Q4_K_M.UniqueId, CandidateKld = .005 }, + evidence with { CandidateBaselineId = BaselineQuants.Q5_K.UniqueId, CandidateSizeBytes = evidence.AnchorSizeBytes + 1 }, + evidence with { CandidateBaselineId = BaselineQuants.Q8_0.UniqueId }, + evidence with { CandidateKld = double.NaN } + }, 1, 1e-8); + + Assert.Equal(evidence, Assert.Single(queue)); + Assert.Empty(IsolationRescuePlanner.Select([evidence], 0, 1e-8)); + Assert.False(MagicQuantYamlConfig.CreateDefault().IsolationPruning.KldSizeRescueEnabled); + Assert.False(MagicQuantYamlConfig.CreateDefault().CandidateSelection.CompleteInteriorCoverage); + } + + [Fact] + public void Rescue_plans_are_bounded_contextual_swaps_and_do_not_remove_global_bans() + { + var group = TReg.AttnKV; + var baseline = BaselineQuants.Q6_K; + bool alreadyBanned = RuntimeSearchSpace.IsCombinationCandidateRuntimeBannedForGroup(group, baseline); + if (!alreadyBanned) RuntimeSearchSpace.BanCombinationCandidateForGroup(group, baseline, "test", "secondary heuristic"); + try + { + var contexts = new[] + { + Snapshot(Context(BaselineQuants.Q8_0), 20_000, .01), + Snapshot(Context(BaselineQuants.Q6_K), 18_000, .02), + Snapshot(Context(BaselineQuants.Q4_K_M), 16_000, .03) + }; + var plans = IsolationRescuePlanner.BuildPlans([RescueEvidence()], contexts, 3, [TReg.AttnKV, TReg.FfnUpGate]); + Assert.Equal(3, plans.Count); + Assert.Equal(3, plans.Select(x => TensorConfigIdentity.ToKey((TensorConfig)x.Quant)).Distinct().Count()); + Assert.All(plans, plan => + { + Assert.Equal(baseline.UniqueId, plan.Quant.GetRequiredTensor(group).CandidateBaseline!.UniqueId); + Assert.Equal(plan.Incumbent.Config.FfnUpGate, ((TensorConfig)plan.Quant).FfnUpGate); + }); + Assert.Single(IsolationRescuePlanner.BuildPlans([RescueEvidence()], contexts, 1, [group, TReg.FfnUpGate])); + Assert.Empty(IsolationRescuePlanner.BuildPlans([RescueEvidence()], contexts, 0, [group])); + Assert.Empty(IsolationRescuePlanner.BuildPlans([RescueEvidence()], contexts, 3, [TReg.FfnUpGate])); + Assert.Empty(IsolationRescuePlanner.BuildPlans([RescueEvidence()], + [Snapshot(Recipe(BaselineQuants.Q5_K), 15_000, .02)], 3, [group])); + Assert.True(RuntimeSearchSpace.IsCombinationCandidateRuntimeBannedForGroup(group, baseline)); + } + finally + { + if (!alreadyBanned) RuntimeSearchSpace.UnbanCombinationCandidateForGroup(group, baseline, "test-cleanup", "restore"); + } + } + + [Fact] + public async Task Harmful_probe_reconciles_its_better_reference_even_when_the_hypothesis_was_rejected() + { + var reference = Snapshot(Recipe(BaselineQuants.Q6_K), 10_000, .01); + var probe = Snapshot(Recipe(BaselineQuants.Q8_0), 10_000, .02); + var observation = Observation(reference, probe); + observation.Accepted = false; + observation.RuleDirection = AnomalyRuleDirection.Harmful.ToString(); + var current = new[] { reference, probe }.ToDictionary(x => TensorConfigIdentity.ToKey(x.Config)); + + var reconciled = await ContextualMeasurementReconciler.ResolveAsync([observation], + (config, _) => Task.FromResult(current[TensorConfigIdentity.ToKey(config)]), default); + + Assert.Equal(2, reconciled.Snapshots.Count); + Assert.Null(reconciled.BestBeneficialProbe); + Assert.All(reconciled.Resolutions, x => Assert.Equal("included", x.Status)); + Assert.Equal(TensorConfigIdentity.ToKey(reference.Config), + TensorConfigIdentity.ToKey(Assert.Single(MeasuredFrontierArchive.Frontier(reconciled.Snapshots)).Config)); + } + + [Fact] + public async Task Context_reconciliation_cannot_promote_an_observation_without_matching_current_measurement() + { + var reference = Snapshot(Recipe(BaselineQuants.Q6_K), 10_000, .01); + var probe = Snapshot(Recipe(BaselineQuants.Q8_0), 10_000, .02); + var observation = Observation(reference, probe); + var currentProbe = Snapshot(probe.Config, probe.SizeBytes, .03); + var result = await ContextualMeasurementReconciler.ResolveAsync([observation], + (config, _) => Task.FromResult( + TensorConfigIdentity.ToKey(config) == TensorConfigIdentity.ToKey(probe.Config) ? currentProbe : null), default); + + Assert.Empty(result.Snapshots); + Assert.Contains(result.Resolutions, x => x.Role == "reference" && x.Status == "current_measurement_unavailable_or_incompatible"); + Assert.Contains(result.Resolutions, x => x.Role == "probe" && x.Status == "observation_kld_mismatch"); + } + + [Fact] + public void Unspaced_archive_preserves_close_budget_options_and_does_not_pick_optimistic_repeats() + { + var first = Snapshot(Recipe(BaselineQuants.Q6_K), 10_000, .02); + var close = Snapshot(Recipe(BaselineQuants.Q5_K), 10_100, .019); + Assert.Equal(2, MeasuredFrontierArchive.Frontier([first, close]).Count); + var optimisticOld = Snapshot(first.Config, first.SizeBytes, .001); + Assert.Equal(first.Kld, Assert.Single(MeasuredFrontierArchive.Measurements([optimisticOld, first])).Kld); + Assert.Empty(MeasuredFrontierArchive.Measurements([Snapshot(first.Config, 0, .01)])); + } + + private static IsolationRescueCandidate RescueEvidence() => new() + { + GroupId = TReg.AttnKV.UniqueId, GroupName = TReg.AttnKV.Name, + CandidateBaselineId = BaselineQuants.Q6_K.UniqueId, CandidateName = "Q6_K", + AnchorBaselineId = BaselineQuants.Q8_0.UniqueId, AnchorName = "Q8_0", + CandidateSizeBytes = 68_882_127_264, CandidateKld = .004395, + AnchorSizeBytes = 68_887_206_304, AnchorKld = .004491, + OriginalRemovalReason = "small size gain; |PPL| ratio 5.5471" + }; + + private static TensorConfig Recipe(BaselineQuants kv) + { + var quant = HybridQuant.CreatePureBaseline(BaselineQuants.Q8_0); + quant.SetLearnedCandidateOverride(TReg.AttnKV, kv); + return (TensorConfig)quant; + } + + private static TensorConfig Context(BaselineQuants ffn) + { + var quant = HybridQuant.CreatePureBaseline(BaselineQuants.Q8_0); + quant.SetLearnedCandidateOverride(TReg.FfnUpGate, ffn); + return (TensorConfig)quant; + } + + private static BenchmarkSnapshotRecord Snapshot(TensorConfig config, ulong size, double kld) => new() + { + Config = config, Quant = (HybridQuant)config, DisplayName = TensorConfigIdentity.ToKey(config), + IsHybrid = true, SizeBytes = size, Kld = kld, Ppl = 5 + }; + + private static PredictedAnchorRow PredictionAnchor(ulong size, double kld) + { + var config = Recipe(BaselineQuants.Q8_0); + return new PredictedAnchorRow + { + Config = config, ConfigKey = TensorConfigIdentity.ToKey(config), DisplayName = "anchor", + BaselineCanonicalKey = "anchor", PredictedKld = kld, PredictedSizeBytes = size + }; + } + + private static AnomalyProbeObservation Observation(BenchmarkSnapshotRecord reference, BenchmarkSnapshotRecord probe) => new() + { + ReferenceTensorCombo = new TensorCombo(reference.Config), ProbeTensorCombo = new TensorCombo(probe.Config), + ReferenceTensorConfigKey = TensorConfigIdentity.ToKey(reference.Config), ProbeTensorConfigKey = TensorConfigIdentity.ToKey(probe.Config), + ReferenceActualKld = reference.Kld, ActualKld = probe.Kld, + IsContextualAnomalyProbe = true, AllActiveGroupsExplicit = true + }; + + private sealed class CandidateDatabaseScope : IDisposable + { + private readonly string directory = Path.Combine(Path.GetTempPath(), "mq-selection-tests-" + Guid.NewGuid().ToString("N")); + private readonly string? previousDirectory = Cache.ModelMagicQuantDirectory; + private readonly string previousModel = Cache.CurrentModelId; + private readonly MagicQuantYamlConfig previousConfig = Config.Current; + + public CandidateDatabaseScope() + { + Directory.CreateDirectory(directory); + Cache.ModelMagicQuantDirectory = directory; + Cache.CurrentModelId = "selection-regression"; + Config.Load(MagicQuantYamlConfig.CreateDefault()); + } + + public void Dispose() + { + Cache.ModelMagicQuantDirectory = previousDirectory; + Cache.CurrentModelId = previousModel; + Config.Load(previousConfig); + Directory.Delete(directory, recursive: true); + } + } +}