You are working on a research idea from the Modal Research Exchange: TriMuon vs dimuon-lite (Polar Express) for LoRA SFT on no_robots Goal: reproduce this on Spindle, Modal's Tinker-compatible training service, using the stock tinker SDK or tinker-cookbook pointed at TINKER_BASE_URL. Report real metrics only. If it cannot run on Spindle, say why. Selected experiment version: exp_ff293ca443 The saved experiment spec below defines the hypothesis, methods and success criterion. Legacy context: the original idea context was not recorded (unknown). Use only the saved spec; do not reconstruct it from the current idea or other runs. Launch mode: ordinary Purpose: Execute the selected saved experiment version. Experiment spec: { "title": "TriMuon vs dimuon-lite (Polar Express) for LoRA SFT on no_robots", "hypothesis": "With a Spindle fork that adds TriMuon, LoRA SFT on Qwen3.5-4B reaches held-out no_robots loss at least 0.01 nats lower than dimuon-lite (Polar Express) at its best LR, after the same 80 steps.", "method": "Fork modal-projects/spindle and add TriMuon as an optimizer option. It keeps DiMuon's recovered momentum and preconditioning rules. It replaces only the Polar Express polar step with two outer Polar Switch passes, then four cubic Newton-Schulz refinements folded into the rank x rank multiplier. Use the FP16 polar core and TF32 disabled, as in aaron's benchmark. Deploy the fork as a throwaway copy. Train rank-32 LoRA on Qwen/Qwen3.5-4B with a short tinker SDK SFT loop on no_robots. The loop uses the cookbook renderer for the model, forward_backward with cross_entropy, then optim_step. The treatment arm runs on the fork with TriMuon. The baseline arm runs dimuon-lite on the same fork (or shared Spindle) with identical code. Each arm sweeps LR over {5e-5, 1e-4, 2e-4}: 6 runs of 80 steps each, same data order and seed. Each run evaluates held-out loss at step 80 and logs per-step optimizer wall time. Qwen3.5-4B is a scaled-down stand-in for the source's Qwen3-8B rank-32 workload. Polar Switch and AdamW arms are follow-up specs, not part of this decision.", "base_model": "Qwen/Qwen3.5-4B", "lora_rank": 32, "training_type": "sft", "dataset": { "name": "no_robots", "hf_path": "HuggingFaceH4/no_robots", "split": "train (eval on test)", "n_examples": 5120 }, "optimizer": { "name": "trimuon (fork)", "lr": 0.0001 }, "steps": 80, "batch_size": 64, "max_seq_len": 2048, "eval": { "benchmark": "no_robots test split", "metric": "mean per-token NLL on assistant tokens", "n_examples": 500 }, "baseline": "dimuon-lite (DiMuon with Polar Express), beta1=0.9, grad_clip_norm=0.0. Same model, rank, data order, seed, renderer, batch size, steps and LR grid. The best-LR run of each arm is compared.", "success_criterion": "Validated if best-LR TriMuon eval NLL is at least 0.01 nats below best-LR dimuon-lite eval NLL, and TriMuon's median optimizer step time is not higher. Failed if the gap is under 0.01 nats or reversed. A rerun of the best PE config with a second seed is optional, if budget allows, to check that the 0.01 margin exceeds seed noise.", "budget": { "gpu_hours": 1.8, "max_wall_minutes": 120 }, "command": "python - <<'EOF'\n# Custom part: the TriMuon config exists only on the fork; the baseline uses tinker.types.DimuonOptimizerConfig() / DimuonParams.\nimport os, tinker\nfrom tinker_cookbook.recipes.chat_sl import chat_datasets # renderer + no_robots builder\nsc = tinker.ServiceClient(base_url=os.environ[\"TINKER_BASE_URL\"]) # fork URL for the TriMuon arm\nARM = os.environ.get(\"ARM\", \"pe\"); LR = float(os.environ.get(\"LR\", \"1e-4\"))\nopt_cfg = tinker.types.DimuonOptimizerConfig() if ARM == \"pe\" else tinker.types.TrimuonOptimizerConfig() # Trimuon* added by the fork\ntc = sc.create_lora_training_client(base_model=\"Qwen/Qwen3.5-4B\", rank=32, optimizer=opt_cfg)\ntrain, test = chat_datasets.no_robots_batches(tc.get_tokenizer(), batch_size=64, max_length=2048, seed=0)\nfor step, batch in zip(range(80), train):\n tc.forward_backward(batch, loss_fn=\"cross_entropy\").result()\n P = tinker.types.DimuonParams if ARM == \"pe\" else tinker.types.TrimuonParams\n tc.optim_step(P(learning_rate=LR, beta1=0.9, grad_clip_norm=0.0)).result()\nprint(\"eval_nll\", sum(tc.forward(b, loss_fn=\"cross_entropy\").result().metrics[\"loss:mean\"] for b in test) / len(test))\ntc.save_weights_for_sampler(name=f\"rx-trimuon-{ARM}-{LR}\")\nEOF" } How to work: - Run the experiment on Spindle with the stock tinker SDK (or tinker-cookbook) pointed at $TINKER_BASE_URL. Every request needs the headers Modal-Key: $MODAL_PROXY_TOKEN_ID and Modal-Secret: $MODAL_PROXY_TOKEN_SECRET, plus TINKER_API_KEY. These are already set as env vars in this session: call Spindle directly from here. Don't search the repo for them or wrap your client in a Modal app to get them. Never print their values. - Any Modal app you do need (a Spindle fork, a GPU eval) goes in the environment research-exchange-runs, named with run_a4ee28e686. Never deploy or run anything in the research-exchange environment (it is production), never mount the volume research-exchange-data, and never create Modal environments. - Keep the run small and inside the spec's budget. Real numbers only; never estimate or invent a metric. - Before any arm trains, run the spec's preflight probe (or, when it has none, create a training client with each arm's exact optimizer and config and take one optim_step on one example). If the shared Spindle rejects an arm's optimizer or option (for example an HTTP 400 at model creation), that arm needs a fork: fork as described below, or stop with status "failed" and outcome_reason "incomplete_execution". Never swap in a different optimizer silently. - Compare tuned arms: if the spec gives per-arm learning-rate grids, run each arm's grid under the same budget and report the selected LR per arm. A selected LR at the edge of its grid sets "grid_edge": true and keeps "confidence" weak. - Before a paired comparison, run the restoration preflight in the saved spec. Save initialization_provenance (version 1) with one entry per named arm: initialization (pinned base_checkpoint, measured adapter_sha256, source=server_response or local_hash, evidence_ref, before_first_update=true), restore_count, optimizer_checks, and initial_output. All arms/replays in an initialization group must load the same initial checkpoint/adapter. A matching seed, step-0 loss, or base accuracy does not establish matched initialization (LoRA B may be zero). optimizer_checks must cover creation (after_restore=0) and EVERY restore (1..restore_count), before_next_update=true, actual optimizer family and actual_config from a server_response plus evidence_ref. Compare against each arm's requested optimizer/config. Creating from saved state can silently fall back to AdamW: creating TriMuon first then loading weights is a workaround to verify, not proof. Stop on mismatch. Do not invent SDK inspection methods; if no server response exposes the active optimizer, use source=declared and actual=null: this stays unverified. On a fork, add a minimal observation of the concrete server optimizer after restoration; retain its code revision and response. Check a create-save-restore fixed-gradient update against the uninterrupted client before a sweep. initial_output records available=true, batch_sha256 (token IDs/targets/masks), output_sha256 (all full-precision logits/logprobs, not an averaged loss), evidence_ref and before_first_update=true; compare across the paired group. If capture is unavailable, record available=false with a reason. For exact replay, require it in the spec. Retain the evidence before cleanup. Publish the provenance while running; full training waits for verified checks. - Initialization proof may use measured adapter_sha256, or an immutable FULL initialization checkpoint with source=server_response, checkpoint_uri, checkpoint_immutable=true, checkpoint_scope=full_initialization, loaded_checkpoint_uri (from the actual successful load response), load_succeeded=true, evidence_ref and before_first_update=true. Keep base_checkpoint in both proof types. A declared URI or base-model-only load does not prove matching adapters. Compare all available hashes and URI identities; mixed proofs need a shared identity. A lone resumed training arm may form one group only when checkpoint_restore=true, paired_training_arms=false, and it records at least one actual restore. Exclude frozen, untrained baselines from optimizer restoration groups. - If the spec's base_model is not served on Spindle, use the closest served model of the same family (e.g. Qwen/Qwen3.5-2B for a smaller Qwen3.5) and say so in the summary; a missing model is not a reason to stop. - If the shared Spindle lacks something the experiment needs (an optimizer, loss, or feature), you may fork Spindle (https://github.com/modal-projects/spindle), add it, and deploy your fork following its README as a throwaway Modal app named spindle-fork-run_a4ee28e686 in the research-exchange-runs environment. Call your fork with Modal-Key: $RUNS_PROXY_TOKEN_ID and Modal-Secret: $RUNS_PROXY_TOKEN_SECRET (the shared Spindle token gets 401 on research-exchange-runs); they're also set as env vars here. Run every arm on the fork so the comparison is fair. Never push to, redeploy, reconfigure, or stop the shared Spindle deployment, and never open PRs or issues on the Spindle repo; if the change looks worth upstreaming, propose it in your report. Include the fork's diff and app name in your report, and when you are done stop spindle-fork-run_a4ee28e686 and every app your fork deployed (Spindle deploys separate trainer, lora and inference apps; give them names containing run_a4ee28e686), with `modal app stop -e research-exchange-runs `, then check `modal app list -e research-exchange-runs` shows none of yours still deployed. Stop nothing else. - Spindle errors like "trainer capacity exhausted" or 429/503 are usually temporary because other runs share it: retry with backoff (e.g. 1, 2, 4 minutes) and update your structured output while you wait. If no comparison training step has run yet and it is still refused after about 10 minutes, don't keep waiting: release the Spindle clients this session created where the SDK lets you (yours only), then finish with "status": "failed", no "verdict", "outcome_reason": "incomplete_execution" and "capacity_block". The exchange may re-queue the run and start a fresh session later, within the spec's wall-time budget. If comparison steps already ran, keep retrying for up to 30 minutes so finished work isn't lost, then stop and report "capacity_block" with the real step count. - Release probe and setup clients you no longer need before starting the paired arms. - Clean up after yourself before you finish: stop every Modal app, sandbox, or other resource you started for this run (by exact name), and nothing else. Use the structured output tool to keep your output updated with exactly this JSON shape, and set "status" to "succeeded" or "failed" when you are done: {"status": "running" | "succeeded" | "failed", "summary": "<= 2 plain sentences: what ran and what it showed", "metrics": {"": , ..., "arms": {"": {"": }}}, "completed_arms": [""], "verdict": "supported" | "refuted", "confidence": "strong" | "weak", "effect": , "margin": , "ci": [, ], "seeds": , "grid_edge": true | false, "reasoning": "2-4 sentences: what the evidence showed, the effect against the margin, what limits confidence", "outcome_reason": "incomplete_execution", "capacity_block": {"error": "", "comparison_steps_completed": , "released_clients": true | false}} Include "capacity_block" only when Spindle capacity stopped the run. Put each arm's numbers under "arms", keyed by the arm's name, not in flat keys like "_". Update it while you work, not only at the end: post the base eval as soon as you have it, and each arm's metrics under "arms" with the arm added to "completed_arms" as soon as that arm finishes. Keep every number you posted earlier in later updates; if the session ends early the finished arms still count as partial results. Leave "verdict" out until you are done. A verdict is a direction plus a confidence; there is no "inconclusive". Once the comparison measured the effect, "verdict" follows the effect against the margin: "supported" when it meets the success criterion, "refuted" otherwise (ties, effects inside the tie band, mixed criteria). "confidence" is "strong" only when the interval or at least two seeds settle the margin and nothing limits the result; "weak" otherwise, with the limit named in "reasoning" (one seed, a wide interval, a grid-edge LR, a changed experiment, a check that did not pass). Finishing execution alone does not support the hypothesis. If the comparison never measured the effect (stopped early, a gate failed before training, an arm could not run), finish with "status": "failed", no "verdict" and "outcome_reason": "incomplete_execution": that is shown as no result, not a verdict. Use "succeeded" when execution completed; "failed" when it stopped early. Changes from the spec: the output also has "deviations": [{"field": "model" | "objective" | "effective_batch" | "steps" | "dataset" | "evaluator" | "endpoint", "original": "", "effective": "", "reason": ""}], "original_hypothesis_tested": true | false, "tested_instead": "" Use [] when you run the spec as written. effective_batch is sequences per optimizer step after accumulation. Before you train with any change (a substituted model, a different loss or RL objective, a smaller batch, another dataset or split, a different grader or eval set, a different decision metric or step), add it to "deviations" with status "running" first, then continue. A change you only report at the end is flagged as unrecorded. If the change means the run no longer tests the spec's hypothesis, set "original_hypothesis_tested": false and fill "tested_instead". Changing the objective (e.g. GRPO to REINFORCE) or the endpoint always counts as not testing it: the exchange then records that your verdict judges the changed experiment, which lowers its confidence. Correctness preflight is required before ANY full sweep using a new/custom/forked loss or optimizer, even if discovered after launch. First reproduce the stock baseline THROUGH the new path, with treatment disabled; then compare the enabled implementation to the pinned treatment reference. Use the same fixed inputs, weights, optimizer state, masks, normalization, precision and seeds. Loss paths need both loss AND full gradient errors; optimizer paths need update errors. Similar gradient norms alone do not prove parity. Check packed versus unpacked layouts on meaningful fixed inputs, including stale inputs when relevant. Reset state independently for each LR probe, measure update norms (per factor when applicable), and verify the prespecified LR scaling. STOP before full training/sweeps if any check is missing or fails. If the spec has no accepted preflight plan for a discovered custom path, report it as required/unverified and request a spec revision; do not pick a loose tolerance after observing errors. Activation and checkpoint provenance are separate gates. Add correctness_preflight alongside status/summary/metrics/verdict in structured output (or RESULT): {"required": true, "paths": [{"id": "", "fixed_input": {"sha256": "<64 hex>", "description": ""}, "baseline_revision": "", "reference_revision": "", "implementation_revision": "", "precision": "", "normalization": "", "errors": {"": {"max_abs_error": , "reference_max_abs": , "relative_l2_error": , "cosine_similarity": }}, "lr_scaling": [{"learning_rate": , "update_norm": }, ...]}]}. For stock-only execution use {"required": false, "paths": []}. Keep probe scripts and inputs as report artifacts. max_abs_error is max(abs(actual-reference)); relative_l2_error is norm(actual-reference)/norm(reference). Acceptance requires max_abs_error <= atol + rtol*reference_max_abs and any prespecified min_cosine. LR scaling checks the relative change of update_norm/LR against the first probe. These are measured errors, not self-declared pass flags. Small standard-library helpers parity_errors and lr_scaling_error live in research_exchange.correctness; `python -m research_exchange.correctness spec.json preflight.json` validates evidence and exits nonzero unless passed/not_applicable. Gate full-sweep launch on that exit code when available. The Exchange validates/persists reported checks and withholds definitive judgments when required checks fail or are missing. It cannot prevent autonomous training calls or attest reported remote measurements. Before full training, follow the spec's activation_gate: measure every prespecified diagnostic in a short pilot using the exact full-run model, loss path, dtype, lag and updates per batch. Stop before full training when a required diagnostic is missing or outside its accepted range; do not start full training. Do not change ranges after measuring. Stopping full training does not end the investigation. First use saved evidence to distinguish a code or instrumentation defect, a wrong reference/variant, and an inactive treatment regime. Check deterministic inputs that must activate and must not activate, including gradients and boundary decisions. Preserve the actual loss inputs and masks, with hashes. For policy constraints, record sampler checkpoint/version and immutable rollout logprobs, current logprobs before each update, token identities, advantage signs, and loss-token denominators. Log signed and absolute drift tails (p90/p99/max), threshold exceedance counts and removed-gradient counts; zero-advantage and padding tokens must not count as treatment engagement. Distinguish optimizer calls, disjoint minibatches, epochs over reused data, and the number of intervening updates since sampling. Continue offline diagnosis after a gate failure. Calibration training may continue only under a recorded, source-justified diagnostic plan with fixed settings, selection rule, update and wall-time caps within the remaining authorized budget. Keep calibration data separate from held-out outcome evaluation. If the accepted spec has no such plan, retain a concrete revised spec/deviation and cheapest next diagnostic; do not execute changed training settings under the old spec. Never lower a threshold or relax a gate merely to pass it. In the RESULT summary, state the verified or suspected cause, evidence gaps, fixes and cheapest next diagnostic. Include activation_calibration in RESULT: {"values": {"": }, "note": ""}. Preserve it separately from scalar metrics. The server validates reported calibration, not remote execution; a missing or failing required check withholds a definitive scientific judgment. Freeze the evaluator before scoring any arm. Report an evaluation object alongside metrics: { "version": 1, "evaluators": { "": { "code_sha256": "", "prompt_template": "", "decoding": {"temperature": 0, "max_tokens": 512, "stop": []}, "parser": "", "items": {"ids": [""]} }}, "scores": [{"arm": "baseline", "metric": "accuracy", "value": 0.8, "evaluator_id": "", "seed": 0, "predictions_ref": "predictions.jsonl"}], "comparisons": [{"metric": "accuracy", "arms": ["baseline", "treatment"]}] } evaluator_id is hashlib.sha256(json.dumps(provenance, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False).encode()).hexdigest(). Include seed per score when applicable. For large item lists use items {"manifest_ref": "items.jsonl", "manifest_sha256": ""} instead of ids; references are evidence file names. Include evaluator_id, metric, arm and item_id in each prediction record. Keep the scored model/checkpoint separate from evaluator identity. Any grader, parser, prompt, decoding or item change requires re-evaluating EVERY compared arm/seed and the base model with the new evaluator, including already completed arms. Until then report no verdict. Keep old scores identified with their original evaluator; never relabel them. When spec.decision_rule is present, report decision {version:1, observations:[ {item_id:"",arm:"treatment",seed:0,metric:"accuracy",value:1, evaluator_id:""}, ...]} for every arm, item and scheduled seed. For large evaluations, avoid putting all rows in structured output. Attach a UTF-8 JSONL file with those same scored rows (or a JSON array / object with observations), retain it via evidence.files as kind metrics, then report only decision {version:1, observations_file:{name:"scored-observations.jsonl",sha256:""}}. Use exactly one of observations or observations_file. The reference is a retained file name and hash, never a path or URL. The server reads only this run's verified immutable evidence copy, capped at 10 MiB and 100000 observations; missing/corrupt files stay unverified. Upload a new immutable file name/hash for each update. Keep selection metadata in the decision object. No scores, item IDs, seeds or evaluator IDs are inferred. Values are finite measured outcomes in the endpoint's original units; never clip or normalize them. For bounded accuracy, include failures as zero, not just successful items. Report unrounded per-arm/seed score means so they reproduce the paired observations. Record evaluation provenance and per-arm/seed scores with explicit items.ids (hashed manifest-only item lists are not yet resolved by the decision validator). Persist the raw predictions through evidence too. The server recomputes paired effects and uncertainty; it does not trust an agent-supplied interval or parse prose. Never add a seed after seeing the gap or treat test items/repeated evals as independent training seeds. For adaptive selection, observations must use only confirmation items, and decision.selection must contain frozen_before_confirmation:true. For kind weight_edit also report budgets:{:{values_touched:N,proposals:N}} for selected and random-control arms. Report "confidence": "strong" only when every criterion's interval settles the prespecified margin; otherwise "weak". Retain review evidence in structured output under "evidence": {"version":1,"files":[{"name":"run.py","kind":"script","content":""}, {"name":"effective-config.json","kind":"effective_config","content":""}], "checkpoints":[{"arm":"baseline","step":100,"uri":"tinker://training-id/weights/checkpoint-name"}], "per_arm_metrics":{"baseline":{"accuracy":0.5}}} Include files for the executed script, effective config, code revision (kind code_revision) and any patch (kind code_patch), per-item predictions (kind predictions), and per-arm metrics. Include generated_tasks when training on generated data. Use JSONL predictions with item_id, arm, prediction and reference in each row; retain seed, checkpoint, metric and evaluator_id metadata when available. Invalid outputs must remain rows. For larger files attach them in Devin and set source_url to the HTTPS /attachments/... URL instead of content; never use a session page URL, VM path or arbitrary external URL. Optional sha256 must match the original bytes. The web server copies accepted files into this run's storage and exposes reviewer downloads. Post evidence as stages finish, before cleanup. File names are immutable: use a new name for each stage/checkpoint/update. Each file is capped at 10 MiB, with 64 files / 40 MiB total per run. Never include .env, credentials, auth headers, secret values or credential-bearing URLs. Read credentials from environment variables in scripts. Checkpoint URIs are references, not copied weights; omit credentials and signed URL query strings. Missing evidence is shown as unknown or partial, never as verified. Do not invent an artifact or checkpoint that does not exist. Held-out loss: this spec's metric is a loss and asks for "token_mean". Save the module below as loss_eval.py and score every arm's held-out loss with it, on the same examples: run forward(..., "cross_entropy") and pass each output plus each example's loss weights to LossEval("token_mean").add_output. Do not average per-batch loss:mean values, and do not normalise weights per example to get a token mean. Report loss_eval.report("token_mean", {arm name: evaluator}) as "loss_eval" in the structured output, with one entry per arm. The server checks this record against the spec; a missing or mismatched record lowers the verdict's confidence. ```python """Shared held-out loss evaluator: one definition of "mean NLL" for every arm of a comparison. Standard library only, so experiment scripts can copy this file next to themselves and `import loss_eval`. Masking: a token counts when its loss weight is > 0. Weights are only a mask; their size is ignored, so a recipe that normalises weights to sum to 1 per example gets the same numbers as one that uses 0/1 weights. Aggregations (pick one before training and report it): - token_mean: sum of NLL over every counted token / number of counted tokens. Long responses weigh more. - example_mean: mean over examples of (that example's NLL sum / its counted tokens). Every example weighs the same. Examples with no counted tokens are left out of both and reported as n_empty. Totals are kept per example, so results do not depend on how examples were split into batches. Never average per-batch `loss:mean` values: that is neither of the two. """ import math AGGREGATIONS = ("token_mean", "example_mean") DEFAULT_AGGREGATION = "token_mean" REL_TOLERANCE = 1e-6 def _floats(values): if hasattr(values, "tolist"): values = values.tolist() elif hasattr(values, "data"): values = values.data return [float(v) for v in values] def example_nll(logprobs, weights): """(NLL summed over tokens with weight > 0, number of those tokens) for one example.""" logprobs, weights = _floats(logprobs), _floats(weights) if len(logprobs) != len(weights): raise ValueError(f"{len(logprobs)} logprobs but {len(weights)} weights") counted = [lp for lp, w in zip(logprobs, weights) if w > 0] return -sum(counted), len(counted) class LossEval: """Accumulates per-example NLL totals for one arm and reports both aggregations.""" def __init__(self, aggregation=DEFAULT_AGGREGATION): if aggregation not in AGGREGATIONS: raise ValueError(f"aggregation must be one of {AGGREGATIONS}, got {aggregation!r}") self.aggregation = aggregation self.examples = [] def add(self, logprobs, weights): self.examples.append(example_nll(logprobs, weights)) def add_output(self, output, weights_per_example): """Add a Tinker forward/forward_backward output ("cross_entropy" loss) for the batch it scored.""" for item, weights in zip(output.loss_fn_outputs, weights_per_example, strict=True): self.add(item["logprobs"], weights) def record(self): counted = [(s, n) for s, n in self.examples if n > 0] nll_sum = sum(s for s, _ in counted) n_tokens = sum(n for _, n in counted) token_mean = nll_sum / n_tokens if n_tokens else None example_mean = sum(s / n for s, n in counted) / len(counted) if counted else None return { "aggregation": self.aggregation, "value": token_mean if self.aggregation == "token_mean" else example_mean, "token_mean": token_mean, "example_mean": example_mean, "nll_sum": nll_sum, "n_tokens": n_tokens, "n_examples": len(counted), "n_empty": len(self.examples) - len(counted), } def report(aggregation, arms): """The `loss_eval` record a run reports: {"aggregation", "arms": {arm name: LossEval.record()}}.""" return {"aggregation": aggregation, "arms": {name: arm.record() for name, arm in arms.items()}} def requested_aggregation(spec): """The aggregation a spec asks for: eval.aggregation when set, else read from the eval metric text, else None.""" eval_spec = (spec or {}).get("eval") or {} explicit = str(eval_spec.get("aggregation") or "").strip().lower().replace("-", "_").replace(" ", "_") if explicit in AGGREGATIONS: return explicit text = " ".join(str(eval_spec.get(k) or "") for k in ("metric", "benchmark")).lower().replace("-", " ") if any(p in text for p in ("per example", "example mean", "example weighted", "mean of example", "per sequence")): return "example_mean" if any(p in text for p in ("per token", "token mean", "token weighted", "per assistant token", "nats/token")): return "token_mean" return None def is_loss_metric(spec): eval_spec = (spec or {}).get("eval") or {} text = " ".join(str(eval_spec.get(k) or "") for k in ("metric", "benchmark")).lower() return any(word in text for word in ("nll", "loss", "perplexity", "cross entropy", "cross-entropy", "log likelihood")) def check(spec, loss_eval): """Problems that make a run's loss comparison unusable for the spec's verdict; [] when it is consistent. Checks that the reported aggregation is the one the spec asked for, that every arm used it on the same tokens and examples, and that each arm's value really is that aggregation of its own totals.""" requested = requested_aggregation(spec) if not isinstance(loss_eval, dict) or not isinstance(loss_eval.get("arms"), dict) or not loss_eval["arms"]: if requested or is_loss_metric(spec): return ["no loss_eval record: the loss aggregation behind the reported numbers is unknown"] return [] problems = [] aggregation = loss_eval.get("aggregation") if aggregation not in AGGREGATIONS: problems.append(f"loss_eval aggregation {aggregation!r} is not one of {', '.join(AGGREGATIONS)}") elif requested and aggregation != requested: problems.append(f"spec asks for {requested} but the run reported {aggregation}") counts = {} for name, arm in loss_eval["arms"].items(): if not isinstance(arm, dict): problems.append(f"arm {name}: no loss record") continue if arm.get("aggregation", aggregation) != aggregation: problems.append(f"arm {name} used {arm.get('aggregation')}, not the run's {aggregation}") problems += _arm_problems(name, arm, aggregation) counts[name] = (arm.get("n_tokens"), arm.get("n_examples")) if len(set(counts.values())) > 1: problems.append("arms were scored on different tokens or examples: " + ", ".join(f"{n} {t} tokens / {e} examples" for n, (t, e) in counts.items())) return problems def _arm_problems(name, arm, aggregation): nll_sum, n_tokens, value = arm.get("nll_sum"), arm.get("n_tokens"), arm.get("value") if not all(_number(v) for v in (nll_sum, n_tokens, value)) or n_tokens <= 0: return [f"arm {name}: needs numeric value, nll_sum and n_tokens > 0"] token_mean = nll_sum / n_tokens reported_token_mean = arm.get("token_mean", token_mean) if not _number(reported_token_mean) or not _close(reported_token_mean, token_mean): return [f"arm {name}: token_mean {reported_token_mean} is not nll_sum / n_tokens = {token_mean:.6g}"] if aggregation == "token_mean" and not _close(value, token_mean): return [f"arm {name}: value {value} is not the token mean {token_mean:.6g} (nll_sum / n_tokens)"] if aggregation == "example_mean" and _number(arm.get("example_mean")) and not _close(value, arm["example_mean"]): return [f"arm {name}: value {value} is not its example_mean {arm['example_mean']}"] return [] def _number(value): return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) def _close(a, b): return math.isclose(a, b, rel_tol=REL_TOLERANCE, abs_tol=1e-12) ``` Feasibility is a measured projection, separate from scientific metrics and actual GPU usage. After resolving the served model, run a representative timing pilot before the full comparison. Publish feasibility in structured output before continuing; repeat it after changing model, arms, context, batch, steps, dataset size or evaluation count. Include fork/setup time, training AND held-out evaluation, generation AND filtering samples, measured yield, and a recovery reserve. Never scale timing by parameter count or assume concurrency is free. Measure the actual schedule. Preserve the primary endpoint when downsizing: drop optional secondary evals, extra seeds or LR points first, then shorten training with an explicit deviation; never replace held-out eval by train loss. If the primary comparison cannot fit, stop with no verdict. Use this additional structured field (null means no measurements yet): "feasibility": {"config": , "effective_config": , "primary_endpoint": , "source": , "measurements": { "setup": {"seconds": , "units": 1, "planned_units": 1, "samples": 0, "gpu_count": null, "allocation_source": null}, "training": {"seconds": , "units": , "planned_units": , "samples": , "gpu_count": null, "allocation_source": null}, "evaluation": {"seconds": , "units": , "planned_units": , "samples": , "gpu_count": null, "allocation_source": null}}, "generation": null, "recovery": {"seconds": , "gpu_count": null, "allocation_source": null}}. For generated tasks replace generation:null by {"attempted": , "accepted": , "target_accepted": , "filter_samples_per_candidate": } and add generation and filter measurements (units=candidates and filter rollouts respectively). Include an audit measurement for independent task re-solves when the shared generation_audit applicability is enforced. generated_training_data=true overrides a legacy required=false flag; unresolved new feature declarations need resolution and cannot skip generation/filter/audit sizing. Record GPU counts only from explicit allocation evidence, including all trainer/inference GPUs allocated for the timed phase; null for shared Spindle when allocation is unknown. CPU-only phases may explicitly use 0. Keep projected wall seconds, projected GPU-hours and observed usage separate. Do not invent timings or GPU-hours to fill this contract. Paired arms and batch order (applies if any arm has a phase before the steps it shares with another arm): - Arms that are compared (treatment vs baseline at the same seed) must run their shared adaptation steps on the same batches in the same order. Iterate a warmup or any other treatment-only phase separately from the shared steps, never as one stream like `batches[:WARMUP + N]` with a `step < WARMUP` switch (that shifts the treatment's adaptation batches by WARMUP). Use this pattern: adapt_batches = batches[:ADAPT_STEPS] # identical for every arm warmup_batches = batches[ADAPT_STEPS:ADAPT_STEPS + WARMUP] # treatment-only, disjoint from adaptation for b in warmup_batches: # empty for the baseline (WARMUP = 0) train_step(b, warmup_loss) for b in adapt_batches: train_step(b, adaptation_loss) - For every training arm, report "adaptation_manifests" in the structured output, one entry per arm: {"arm": "", "pair": "", "warmup_batches": , "adaptation_batch_ids": [""], "adaptation_batch_hash": hashlib.sha256(json.dumps(adaptation_batch_ids).encode()).hexdigest()} Record the IDs from the batches the training loop actually consumed, not from the plan. Before you set a verdict, check that arms with the same "pair" report the same hash; if they don't, say so and set "confidence": "weak". Resolve applicability with experiment_features.check_applicability(spec,"generation_audit"). An explicit generated_training_data=true requires the audit. False can establish non-applicability when no explicit contract requires the check; missing feature evidence stays unknown. For training on generated tasks, complete generation_audit BEFORE training. Running generated Python only checks execution; it does not verify labels. Save all candidates as JSONL in evidence.files kind generated_tasks: item_id (unique string), prompt, answer, disposition (accepted/rejected/execution_error). Retain generated code and execution errors when available. Save the FULL frozen evaluation set as JSONL (item_id,prompt), kind generated_tasks; this is for overlap checking, never training. Freeze both files before sampling. Report generation_audit with version=1, stage="before_training", dataset_file, evaluation_file, audit_file (a new immutable .json name), sample_seed (integer), counts={generated,accepted,rejected,execution_errors}, samples=[{item_id,independent_answer,resolver_id,method:"independent_resolve",reasoning,blind_to_label:true}], label_error_count, overlap_count. Select min(accepted_count, spec.generation_audit.min_sample_size or 100) accepted tasks deterministically with research_exchange.generation_audit.select_sample(tasks,size,seed), which sorts by SHA256 of the JSON [seed,item_id]. Re-solve those problems from their TEXT without seeing the stored answer or generated code (human or a separate solver invocation); record solver identity and worked solution. Never reuse the generator's Python as independent evidence. Report observed disagreements and the sample denominator; answer agreement with a declared solution does not establish semantic truth. New specs must explicitly set generation_audit.answer_comparison to numeric_exact for strict scalar numbers/fractions (zero tolerance), or categorical_exact for nonempty string labels. Categorical comparison is exact and case-sensitive, with no whitespace normalization or synonym mapping. Choose from the label contract, never the experiment/dataset name; missing or unsupported strategies remain unverified. Use answer_agreement(label, independent_answer, strategy) with that declared strategy, and evaluation_overlap for NFKC/casefold/whitespace-normalized exact prompt overlap against the full held-out set. This does not detect paraphrases or semantic leakage. Report duplicate and overlap counts, and persist the dataset and audit manifest through evidence before cleanup. Failed/missing audits block a definitive scientific verdict. Call generation_audit.validate(report, spec.generation_audit, tasks=tasks, evaluation=evaluation, require_comparison=True) and require status="passed" before the first optimizer update. Do not invent passing re-solve evidence to get past this check. If any sampled label is wrong or overlaps evaluation, repair/reject affected tasks and freeze NEW dataset and audit file versions, then repeat the audit before training. Do not train on known bad labels as-is.