diff --git a/CHANGELOG.md b/CHANGELOG.md index 947695e0..9be477e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,8 +49,8 @@ and `to_dataframe`, #648): generated columns are now `delta:` and `pct_change:` instead of `_delta` and `_pct_change`, so a metric literally named `a_delta` no longer overwrites the change column for `a`. - Metric value columns keep their bare names, except a metric named `strategy`, - `component` or `description`, or starting with `metric:`, `delta:` or + Metric value columns keep their bare names, except an empty name or a metric named + `strategy`, `component` or `description`, or starting with `metric:`, `delta:` or `pct_change:`, which is written as `metric:`. No two values share a column. `results.json` is unchanged. - When the study's impact metric has no measured change, the fallback metric is @@ -65,13 +65,29 @@ the previous results and shows an error, and a read that finishes after a newer upload, drop or demo load is ignored. It rounds displayed numbers half to even, as Python's formatting does, so a 12.25% change shows as +12.2% in both the viewer and - the heatmap annotation (#650). + the heatmap annotation (#650). Two exceptions remain: values of 1e21 or more show in + exponent notation (`1e+21`), where Python prints every digit, and on browsers older + than ES2020 exact ties round away from zero (#666). See [refusal metrics and compatibility](docs/refusal-metrics.md) for empty-batch, confidence-interval, and canonical substring-protocol behavior. ### Fixed +- Results, evaluation and preset follow-ups (#666). The results viewer shows `-0.0` as + `-0.00` and an infinite change as `+inf`, as Python does, keeps rendering where + `toFixed(100)` is unsupported, and shows an error, rather than the previous file's + results, when a file read cannot start. A metric named `""` is written to + `results.csv` as the column `metric:`, and CSV metric columns are sorted by name + even when a metric first appears in a later result. `metrics: []` in a study is + rejected when the config is parsed, before any model or dataset loads. When a + wrapper model rejects `position_ids`, evaluation logs a warning before retrying + without them, and it also recognises the `'position_ids' is an invalid keyword + argument` wording. Evaluation runs the model in eval mode (dropout off) and restores + each submodule's previous mode afterwards. Classification evaluation gives + left-padded rows positions from their first real token, as perplexity evaluation + does. `get_study_preset` and `list_study_presets` return copies, so editing one + cannot change the shared preset. - Restore-point cleanup no longer reports success while snapshot files remain (#639). `DiskSnapshot.close()` marks the snapshot closed only after its directory is gone; otherwise it raises `SnapshotError` naming the leftover diff --git a/README.md b/README.md index 63a2e394..3f8e27e9 100644 --- a/README.md +++ b/README.md @@ -1039,7 +1039,8 @@ leaves out, and `--preset` replaces any `preset` or `study_preset` named in the preset name is an error. When a study omits `metrics`, causal-LM studies use the preset's metrics (perplexity), while `model.task: classification` studies always use their task defaults, accuracy and F1, with or without a preset. An explicit empty list (`metrics: []`) is not a -request for the defaults: evaluation rejects it with an error, so omit `metrics` to use them. +request for the defaults: loading the study rejects it with an error, before any model or +dataset loads, so omit `metrics` (or set it to `null`) to use them. Classification models keep the label count saved in their checkpoint unless `model.num_labels` is set; a checkpoint with no saved label metadata loads as a two-label classifier, the transformers default. diff --git a/docs/index.html b/docs/index.html index 0cae6ba4..33323be1 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1902,7 +1902,15 @@ function loadResultsFile(file) { showResultsError('Could not load this file: it could not be read.'); }; activeResultsReader = reader; - reader.readAsText(file); + // readAsText can throw synchronously (for example InvalidStateError); show it + // like a failed read instead of leaving the previous file's results on screen. + try { + reader.readAsText(file); + } catch (err) { + if (!current()) return; + activeResultsReader = null; + showResultsError('Could not load this file: it could not be read.'); + } } function loadResults(event) { loadResultsFile(event.target.files[0]); } @@ -2006,14 +2014,26 @@ const resultLabel = value => (value === undefined || value === null) ? '' : Stri // Formats like Python's format(value, '.Nf'), which the report and heatmap use. Both // round the exact binary value, but on an exact tie (12.25 to one digit) toFixed rounds // away from zero (12.3) and Python rounds to even (12.2); ties are resolved to even here. -// Values of 1e21 or more fall back to toFixed (exponent notation; Python prints digits). +// Negative zero keeps its sign (-0.00) and non-finite values print as inf, -inf and nan, +// as in Python. (A JSON integer literal -0 also shows as -0.00, while Python reads it as +// the integer 0; save_json never writes one.) Exceptions: values of 1e21 or more fall back +// to toFixed (exponent notation; Python prints digits), and on engines where toFixed(100) +// throws (pre-ES2020) ties use toFixed's away-from-zero rounding. function toFixedHalfEven(value, digits) { + if (Number.isNaN(value)) return 'nan'; + if (!Number.isFinite(value)) return value > 0 ? 'inf' : '-inf'; + if (Object.is(value, -0)) return '-' + (0).toFixed(digits); const fixed = value.toFixed(digits); const magnitude = Math.abs(value); - if (!Number.isFinite(value) || magnitude >= 1e21) return fixed; + if (magnitude >= 1e21) return fixed; // toFixed(100) is exact for any tie at `digits` places: such a value has digits + 1 // decimals, and every other double differs from a tie well before 100 places. - const exact = magnitude.toFixed(100); + let exact; + try { + exact = magnitude.toFixed(100); + } catch (err) { + return fixed; + } const point = exact.indexOf('.'); const tail = exact.slice(point + 1 + digits); if (!/^50*$/.test(tail)) return fixed; @@ -2022,7 +2042,12 @@ function toFixedHalfEven(value, digits) { if (lastDigit % 2 !== 0) return fixed; return (value < 0 ? '-' : '') + truncated; } -const signed = (value, digits) => (value >= 0 ? '+' : '') + toFixedHalfEven(value, digits); +// Like Python's '+' format flag: a sign is added unless the text already has one, so +// -0 shows as -0.0000 and -Infinity as -inf. +const signed = (value, digits) => { + const text = toFixedHalfEven(value, digits); + return text.startsWith('-') ? text : '+' + text; +}; function renderResults(data) { document.getElementById('results-display').style.display = 'block'; diff --git a/obliteratus/config.py b/obliteratus/config.py index 094c434e..20c9bd6c 100644 --- a/obliteratus/config.py +++ b/obliteratus/config.py @@ -113,6 +113,13 @@ class StudyConfig: def __post_init__(self) -> None: if self.metrics is None: self.metrics = default_metrics(self.model.task) + elif len(self.metrics) == 0: + # Fail before any model, snapshot or dataset loads; the evaluator + # rejects an empty list too (#633, #666). + raise ValueError( + "metrics must name at least one metric; omit metrics or set it " + "to null to use the task defaults." + ) @classmethod def from_yaml(cls, path: str | Path, preset: str | None = None) -> StudyConfig: diff --git a/obliteratus/evaluation/evaluator.py b/obliteratus/evaluation/evaluator.py index a8086881..6c53bfa4 100644 --- a/obliteratus/evaluation/evaluator.py +++ b/obliteratus/evaluation/evaluator.py @@ -3,6 +3,7 @@ from __future__ import annotations import inspect +import logging import torch from tqdm import tqdm @@ -10,6 +11,8 @@ from tqdm import tqdm from obliteratus import device as dev from obliteratus.models.loader import ModelHandle +logger = logging.getLogger(__name__) + def _has_left_padding(real: torch.Tensor) -> bool: """Return whether any row has padding before a real token.""" @@ -35,10 +38,75 @@ def _position_ids_support(model) -> str: return "none" +# Wordings of a call rejecting a keyword argument: CPython functions and methods +# ("f() got an unexpected keyword argument 'x'"), and C-implemented callables +# ("'x' is an invalid keyword argument for f()"). +_KEYWORD_REJECTIONS = ("unexpected keyword argument", "invalid keyword argument") + + def _rejects_position_ids(error: TypeError) -> bool: - """Return whether a ``TypeError`` is a call rejecting ``position_ids``.""" + """Return whether a ``TypeError`` is a call rejecting ``position_ids``. + + The message cannot show which call rejected it: a submodule deep inside a + ``**kwargs`` wrapper raises the same text. A match therefore only ever + triggers a logged fallback; any other ``TypeError`` is re-raised. + """ message = str(error) - return "unexpected keyword argument" in message and "position_ids" in message + return "position_ids" in message and any( + wording in message for wording in _KEYWORD_REJECTIONS + ) + + +def _left_padded_positions(attention_mask: torch.Tensor) -> torch.Tensor: + """Positions counted from each row's first real token (0 on padding).""" + return (attention_mask.long().cumsum(-1) - 1).clamp(min=0) + + +def _forward(model, forward_kwargs: dict, support: str): + """Call ``model``, adding left-padding-aware ``position_ids`` when possible. + + Left padding shifts real tokens to later positions, so an absolute-position + model would embed them at the wrong positions. When a batch is left padded + and ``model.forward`` can take ``position_ids`` (``support`` from + :func:`_position_ids_support`), each row gets positions counted from its + first real token. + + A ``**kwargs``-only wrapper is tried with positions; if its inner model + rejects them (#634), a warning is logged and the batch is run again without + them. That retry runs the wrapper's code and any forward pre-hooks a second + time for this one batch; the returned support is then ``"none"`` so later + batches are called once, without positions. Returns ``(outputs, support)``. + """ + attention_mask = forward_kwargs.get("attention_mask") + if ( + support == "none" + or attention_mask is None + or "position_ids" in forward_kwargs + or not _has_left_padding(attention_mask.bool()) + ): + return model(**forward_kwargs), support + try: + outputs = model( + **forward_kwargs, position_ids=_left_padded_positions(attention_mask), + ) + except TypeError as error: + if support != "kwargs" or not _rejects_position_ids(error): + raise + logger.warning( + "The model rejected position_ids (%s); evaluating without them. " + "Left-padded rows of an absolute-position model may then be " + "embedded at shifted positions.", + error, + ) + return model(**forward_kwargs), "none" + return outputs, support + + +def _module_modes(model) -> list[tuple[torch.nn.Module, bool]]: + """Every submodule of ``model`` with its training flag (empty if not a Module).""" + if not isinstance(model, torch.nn.Module): + return [] + return [(module, module.training) for module in model.modules()] class Evaluator: @@ -82,13 +150,23 @@ class Evaluator: @torch.no_grad() def evaluate(self) -> dict[str, float]: - """Run evaluation and return a dict of metric_name -> score.""" - if self.handle.task == "causal_lm": - return self._evaluate_causal_lm() - elif self.handle.task == "classification": - return self._evaluate_classification() - else: + """Run evaluation and return a dict of metric_name -> score. + + The model runs in eval mode (dropout off); each submodule's previous + training flag is restored afterwards, even if evaluation fails. + """ + if self.handle.task not in ("causal_lm", "classification"): raise ValueError(f"Unsupported task: {self.handle.task}") + modes = _module_modes(self.handle.model) + if modes: + self.handle.model.eval() + try: + if self.handle.task == "causal_lm": + return self._evaluate_causal_lm() + return self._evaluate_classification() + finally: + for module, training in modes: + module.training = training def _evaluate_causal_lm(self) -> dict[str, float]: model = self.handle.model @@ -187,31 +265,11 @@ class Evaluator: "attention_mask": attention_mask, "labels": labels, } - # Left padding shifts real tokens to later positions. Absolute- - # position models would then embed them at the wrong positions, - # so give each row positions counted from its first real token. - # A ``**kwargs``-only wrapper is tried with positions; if its inner - # model rejects them, evaluation continues without them (#634). - pass_positions = ( - position_ids_support != "none" and _has_left_padding(real) + # Left-padded rows get positions from their first real token; see + # ``_forward`` for the ``**kwargs`` wrapper fallback (#634). + outputs, position_ids_support = _forward( + model, forward_kwargs, position_ids_support, ) - if pass_positions: - forward_kwargs["position_ids"] = ( - attention_mask.long().cumsum(-1) - 1 - ).clamp(min=0) - - try: - outputs = model(**forward_kwargs) - except TypeError as error: - if not ( - pass_positions - and position_ids_support == "kwargs" - and _rejects_position_ids(error) - ): - raise - position_ids_support = "none" - del forward_kwargs["position_ids"] - outputs = model(**forward_kwargs) if outputs.loss is None: raise RuntimeError( @@ -257,6 +315,7 @@ class Evaluator: all_preds = [] all_labels = [] + position_ids_support = _position_ids_support(model) for i in tqdm(range(0, len(ds), self.batch_size), desc="Evaluating"): batch = ds[i : i + self.batch_size] @@ -271,7 +330,12 @@ class Evaluator: padding=True, ).to(device) - outputs = model(**encodings) + # Left-padded rows get positions from their first real token, as + # in perplexity evaluation; models that pool the last real token + # (e.g. GPT-2 classifiers) then score them as if right padded. + outputs, position_ids_support = _forward( + model, dict(encodings), position_ids_support, + ) preds = outputs.logits.argmax(dim=-1).cpu().tolist() all_preds.extend(preds) all_labels.extend(labels) diff --git a/obliteratus/reporting/report.py b/obliteratus/reporting/report.py index c6609c99..21f02ac8 100644 --- a/obliteratus/reporting/report.py +++ b/obliteratus/reporting/report.py @@ -93,16 +93,18 @@ def _normalize_metrics(metrics: dict[str, Any]) -> tuple[dict[str, float | None] # Flat CSV layout (#648). Generated columns are namespaced as ``delta:`` # and ``pct_change:``. A metric keeps its bare name as its column unless -# that name is a fixed column or starts with a namespace prefix; it is then -# written as ``metric:``. Bare, ``metric:``, ``delta:`` and ``pct_change:`` -# names are disjoint, so no metric name can overwrite another column. +# that name is empty, a fixed column or starts with a namespace prefix; it is +# then written as ``metric:`` (so ``""`` is ``metric:``, never a blank +# header that pandas reads back as ``Unnamed: n``). Bare, ``metric:``, +# ``delta:`` and ``pct_change:`` names are disjoint, so no metric name can +# overwrite another column. _CSV_FIXED_COLUMNS = ("strategy", "component", "description") _CSV_RESERVED_PREFIXES = ("metric:", "delta:", "pct_change:") def _csv_metric_column(name: str) -> str: """The CSV column holding the raw value of metric ``name``.""" - if name in _CSV_FIXED_COLUMNS or name.startswith(_CSV_RESERVED_PREFIXES): + if not name or name in _CSV_FIXED_COLUMNS or name.startswith(_CSV_RESERVED_PREFIXES): return f"metric:{name}" return name @@ -227,15 +229,19 @@ class AblationReport: def to_dataframe(self) -> pd.DataFrame: """Convert results to a DataFrame with namespaced change columns. - Columns are ``strategy``, ``component``, ``description``, then per - metric (by name) its value, ``delta:`` and - ``pct_change:``. See :func:`_csv_metric_column` for how a - metric whose name is reserved is written. + Columns are ``strategy``, ``component``, ``description``, then for + every metric in any result, sorted by name, its value, + ``delta:`` and ``pct_change:``. A change column is + present only when some result has that change. See + :func:`_csv_metric_column` for how a metric whose name is reserved is + written. """ rows = [] + metric_names: set[str] = set() baseline_metrics, _ = _normalize_metrics(self.baseline_metrics) for r in self.results: metrics, _ = _normalize_metrics(r.metrics) + metric_names.update(metrics) row = { "strategy": _sanitize_label(r.strategy), "component": _sanitize_label(r.component), @@ -252,7 +258,17 @@ class AblationReport: ) * 100 rows.append(row) - return pd.DataFrame(rows) + if not rows: + return pd.DataFrame(rows) + present = set().union(*rows) + columns = list(_CSV_FIXED_COLUMNS) + for name in sorted(metric_names): + columns.append(_csv_metric_column(name)) + columns.extend( + column for column in (f"delta:{name}", f"pct_change:{name}") + if column in present + ) + return pd.DataFrame(rows, columns=columns) def _measured_changes(self) -> list[tuple[str, dict[str, tuple[float, float | None]]]]: """Per result, its component and ``{metric: (delta, pct_change)}``. diff --git a/obliteratus/study_presets.py b/obliteratus/study_presets.py index 8aa60768..9734ef82 100644 --- a/obliteratus/study_presets.py +++ b/obliteratus/study_presets.py @@ -7,6 +7,7 @@ manually configuring every knob. from __future__ import annotations +import copy from dataclasses import dataclass, field from typing import Any @@ -234,11 +235,15 @@ for p in _PRESETS_LIST: def get_study_preset(key: str) -> StudyPreset: - """Look up a preset by its key.""" + """Look up a preset by its key. + + Returns a deep copy, so a caller editing it never changes the registered + preset or later studies (#637, #666). + """ if key not in STUDY_PRESETS: available = ", ".join(sorted(STUDY_PRESETS)) raise KeyError(f"Unknown preset {key!r}. Available: {available}") - return STUDY_PRESETS[key] + return copy.deepcopy(STUDY_PRESETS[key]) # Convenience alias @@ -246,8 +251,8 @@ get_preset = get_study_preset def list_study_presets() -> list[StudyPreset]: - """Return all presets in display order.""" - return list(STUDY_PRESETS.values()) + """Return deep copies of all presets in display order.""" + return copy.deepcopy(list(STUDY_PRESETS.values())) # Convenience alias diff --git a/tests/test_config.py b/tests/test_config.py index f78a1bcc..725c9152 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -293,3 +293,15 @@ def test_parsed_presets_do_not_share_mutable_state(): preset = get_study_preset("quick") assert [s["params"] for s in preset.strategies] == [{}, {}] assert preset.metrics == ["perplexity"] + + +def test_explicit_empty_metrics_list_is_rejected_when_the_study_is_parsed(): + """#666: ``metrics: []`` fails at config time, before any model or dataset loads.""" + with pytest.raises(ValueError, match="omit metrics or set it to null"): + StudyConfig.from_dict({**_study_without("metrics"), "metrics": []}) + with pytest.raises(ValueError, match="omit metrics or set it to null"): + _direct_study("classification", metrics=[]) + # Omitted and null metrics keep meaning the task defaults. + assert StudyConfig.from_dict({**_study_without("metrics"), "metrics": None}).metrics == [ + "perplexity", + ] diff --git a/tests/test_evaluator.py b/tests/test_evaluator.py index 7b20cde3..d7add751 100644 --- a/tests/test_evaluator.py +++ b/tests/test_evaluator.py @@ -425,3 +425,141 @@ def test_report_creates_nested_output_directory(monkeypatch, tmp_path): assert output_dir.is_dir() report.save_plots.assert_called_once_with(output_dir) + + +class _AttemptCountingWrapper(nn.Module): + """A ``**kwargs`` model whose inner call rejects ``position_ids`` with ``message``.""" + + def __init__(self, message: str): + super().__init__() + self.anchor = nn.Parameter(torch.zeros(())) + self.message = message + self.attempts: list[bool] = [] + + def forward(self, **kwargs): + self.attempts.append("position_ids" in kwargs) + if "position_ids" in kwargs: + raise TypeError(self.message) + return SimpleNamespace(loss=torch.tensor(math.log(2.0))) + + +def _two_left_padded_batches(model: nn.Module): + left_padded = _encoding([[0, 0, 1, 2], [3, 4, 5, 6]], [[0, 0, 1, 1], [1, 1, 1, 1]]) + evaluator, _dataset, _tokenizer, _model = _evaluator( + ["a", "bb", "c", "dd"], + [left_padded, _encoding(left_padded["input_ids"], left_padded["attention_mask"])], + [], + batch_size=2, + ) + evaluator.handle.model = model + return evaluator + + +_CPYTHON_REJECTION = "forward() got an unexpected keyword argument 'position_ids'" + + +def test_position_ids_fallback_retries_once_across_batches(): + """#666: after one rejection, later batches are called once, without positions.""" + model = _AttemptCountingWrapper(_CPYTHON_REJECTION) + + result = _two_left_padded_batches(model).evaluate() + + assert result["perplexity"] == pytest.approx(2.0) + # Batch 1: rejected attempt with positions, then the retry. Batch 2: one call. + assert model.attempts == [True, False, False] + + +def test_position_ids_fallback_logs_a_warning(caplog): + """#666: falling back to no positions is logged, never silent.""" + model = _AttemptCountingWrapper(_CPYTHON_REJECTION) + + with caplog.at_level("WARNING", logger="obliteratus.evaluation.evaluator"): + _two_left_padded_batches(model).evaluate() + + warnings = [r for r in caplog.records if r.levelname == "WARNING"] + assert len(warnings) == 1 + assert "position_ids" in warnings[0].getMessage() + assert _CPYTHON_REJECTION in warnings[0].getMessage() + + +@pytest.mark.parametrize("message", [ + "Wrapper.forward() got an unexpected keyword argument 'position_ids'", + "'position_ids' is an invalid keyword argument for forward()", +]) +def test_position_ids_fallback_matches_other_rejection_wordings(message): + """#666: rejection wordings other than CPython's plain-function one fall back too.""" + model = _AttemptCountingWrapper(message) + + assert math.isfinite(_two_left_padded_batches(model).evaluate()["perplexity"]) + assert model.attempts == [True, False, False] + + +def test_position_ids_type_errors_that_are_not_rejections_still_raise(): + model = _AttemptCountingWrapper("position_ids must be a LongTensor, got float") + + with pytest.raises(TypeError, match="must be a LongTensor"): + _two_left_padded_batches(model).evaluate() + assert model.attempts == [True] + + +class _ModeRecordingModel(_LossModel): + def __init__(self, losses): + super().__init__(losses) + self.child = nn.Dropout(0.5) + self.modes: list[bool] = [] + + def forward(self, *, input_ids, attention_mask, labels): + self.modes.append(self.training or self.child.training) + return super().forward(input_ids=input_ids, attention_mask=attention_mask, labels=labels) + + +def test_evaluation_runs_in_eval_mode_and_restores_module_modes(): + """#666: dropout is off while evaluating; every module's mode is restored after.""" + evaluator, _dataset, _tokenizer, _model = _evaluator( + ["alpha"], [_encoding([[1, 2]], [[1, 1]])], [], + ) + model = _ModeRecordingModel([math.log(2.0)]) + model.train() + model.child.eval() # a submodule deliberately in eval mode stays that way + evaluator.handle.model = model + + evaluator.evaluate() + + assert model.modes == [False] + assert model.training is True + assert model.child.training is False + + +def _tiny_classifier_logits(padding_side: str): + from datasets import Dataset + from transformers import GPT2Config, GPT2ForSequenceClassification + + from tests.fixtures.tiny_offline_model import FIXTURE_SEED, FIXTURE_VOCAB, _fixture_tokenizer + + torch.manual_seed(FIXTURE_SEED) + config = GPT2Config( + vocab_size=len(FIXTURE_VOCAB), n_positions=32, n_embd=16, n_layer=1, n_head=2, + n_inner=32, bos_token_id=1, eos_token_id=1, pad_token_id=0, num_labels=3, + ) + model = GPT2ForSequenceClassification(config).eval() + captured: list[torch.Tensor] = [] + model.register_forward_hook(lambda _m, _a, out: captured.append(out.logits.detach().clone())) + tokenizer = _fixture_tokenizer() + tokenizer.padding_side = padding_side + handle = SimpleNamespace(model=model, tokenizer=tokenizer, task="classification") + dataset = Dataset.from_dict( + {"text": ["hello world", "hello world safe test answer"], "label": [0, 1]}, + ) + result = Evaluator(handle=handle, dataset=dataset, batch_size=2, max_length=12).evaluate() + (logits,) = captured + return result, logits + + +@pytest.mark.cpu +def test_classification_left_padding_matches_right_padding(): + """#666: left-padded classification batches get positions from the first real token.""" + right_result, right_logits = _tiny_classifier_logits("right") + left_result, left_logits = _tiny_classifier_logits("left") + + assert torch.allclose(left_logits, right_logits, atol=1e-5) + assert left_result == right_result diff --git a/tests/test_report.py b/tests/test_report.py index cc6cd7f4..14a061a0 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -398,3 +398,32 @@ class TestCsvColumnLayout: "strategy", "component", "description", "a", "delta:a", "pct_change:a", "b", "delta:b", "pct_change:b", ] + + def test_column_order_is_by_name_across_rows(self): + """#666: a metric first seen in a later row is still placed by name.""" + report = AblationReport(model_name="m") + report.add_baseline({"a": 1.0, "b": 1.0, "c": 0.0}) + report.add_result(AblationResult("s", "r0", "d", {"c": 1.0})) + report.add_result(AblationResult("s", "r1", "d", {"b": 2.0, "a": None})) + assert list(report.to_dataframe().columns) == [ + "strategy", "component", "description", + "a", "b", "delta:b", "pct_change:b", "c", "delta:c", + ] + + def test_empty_metric_name_is_written_as_reserved_column(self, tmp_path): + """#666: a metric named "" gets the column ``metric:``, never a blank header.""" + report = _classifier_report({"": 1.0, "metric:": 2.0}, {"": 3.0, "metric:": 5.0}) + columns = list(report.to_dataframe().columns) + assert "" not in columns + assert columns[3:] == [ + "metric:", "delta:", "pct_change:", + "metric:metric:", "delta:metric:", "pct_change:metric:", + ] + out = tmp_path / "results.csv" + report.save_csv(out) + import pandas as pd + + read_back = pd.read_csv(out) + assert read_back.loc[0, "metric:"] == 3.0 + assert read_back.loc[0, "metric:metric:"] == 5.0 + assert not any(str(c).startswith("Unnamed") for c in read_back.columns) diff --git a/tests/test_results_viewer.py b/tests/test_results_viewer.py index 1f143f5c..e39e40a7 100644 --- a/tests/test_results_viewer.py +++ b/tests/test_results_viewer.py @@ -44,6 +44,7 @@ const demoEnd = html.indexOf('\n};', demoStart); if (demoStart < 0 || demoEnd < demoStart) throw new Error('DEMO_RESULTS not found'); const source = html.slice(demoStart, demoEnd + 3) + '\n' + html.slice(start, end) + '\n' + html.slice(dropStart, dropEnd); +const DEMO_RESULTS = new Function(html.slice(demoStart, demoEnd + 3) + '\nreturn DEMO_RESULTS;')(); function makeDocument() { const created = []; @@ -139,7 +140,10 @@ function load(dom, Reader = FakeFileReader) { // Files arrive as raw JSON text, exactly as the viewer's file loader reads them. const {renders: scenarios, values, timings, sequences, formats} = JSON.parse(fs.readFileSync(scenariosPath, 'utf8')); -const output = {renders: {}, values: null, timings: null, sequences: {}, formats: null}; +const output = {renders: {}, values: null, timings: null, sequences: {}, formats: null, + legacy_formats: null, native_formats: null, legacy_render: null}; +// Non-finite numbers cannot travel in JSON; the test sends them as their names. +const formatArgs = formats.map(([v, d]) => [typeof v === 'string' ? Number(v) : v, d]); for (const [name, steps] of Object.entries(sequences)) { const dom = makeDocument(); const pending = {}; @@ -166,7 +170,27 @@ for (const [name, steps] of Object.entries(sequences)) { }; } const probe = load(makeDocument()); -if (probe.toFixedHalfEven) output.formats = formats.map(([v, d]) => probe.toFixedHalfEven(v, d)); +if (probe.toFixedHalfEven) { + output.formats = formatArgs.map(([v, d]) => probe.toFixedHalfEven(v, d)); + // A pre-ES2020 engine throws RangeError for toFixed digits above 20. + const nativeToFixed = Number.prototype.toFixed; + output.native_formats = formatArgs.map(([v, d]) => nativeToFixed.call(v, d)); + Number.prototype.toFixed = function (digits) { + if (digits > 20) throw new RangeError('toFixed() digits argument must be between 0 and 20'); + return nativeToFixed.call(this, digits); + }; + try { + output.legacy_formats = formatArgs.map(([v, d]) => { + try { return probe.toFixedHalfEven(v, d); } catch (err) { return 'threw: ' + err.message; } + }); + const dom = makeDocument(); + let error = null; + try { load(dom).renderResults(DEMO_RESULTS); } catch (err) { error = String(err && err.message || err); } + output.legacy_render = {error, rows: dom.ids['results-table'].findAll('tr').length}; + } finally { + Number.prototype.toFixed = nativeToFixed; + } +} if (probe.measuredValue) { output.values = values.map(v => probe.measuredValue(v)); output.timings = timings.map(text => { @@ -689,7 +713,8 @@ def test_out_of_order_reads_keep_the_latest_load(tmp_path, first, second): def test_stale_read_error_after_demo_load_keeps_the_demo(tmp_path): - """#650: a read error that arrives after a demo load must not replace the demo.""" + """Latest-load-wins reads (#618; coverage gap noted in #650): a read error that + arrives after a demo load must not replace the demo.""" seqs = { f"{start}_error_then_demo": [ {"start": start, "id": "A", "fail": True}, {"start": "demo"}, {"finish": "A"}] @@ -703,8 +728,10 @@ def test_stale_read_error_after_demo_load_keeps_the_demo(tmp_path): @pytest.mark.parametrize("start", ["upload", "drop"]) -def test_read_that_throws_synchronously_keeps_the_prior_display(tmp_path, start): - """#650: readAsText throwing leaves the previous results shown, and later loads work.""" +def test_read_that_throws_synchronously_shows_an_error(tmp_path, start): + """#666 (was a #650 coverage-gap test for the #618 read logic): readAsText throwing + clears the previous results and shows an error instead of leaving them on screen, + and a later load still works.""" a_ok, b_ok = json.dumps(GOOD_A), json.dumps(GOOD_B) seqs = { "throw_after_success": [ @@ -716,11 +743,12 @@ def test_read_that_throws_synchronously_keeps_the_prior_display(tmp_path, start) {"start": start, "id": "B", "text": b_ok}, {"finish": "B"}], } out = _run_harness(tmp_path, {}, sequences=seqs)["sequences"] - kept = out["throw_after_success"] - assert kept["thrown"] == ["readAsText threw"] - assert kept["components"] == ["from_A"] - assert not kept["stats"].startswith("Could not load this file") + failed = out["throw_after_success"] + assert failed["thrown"] == [] + assert failed["components"] == [] + assert failed["stats"] == "Could not load this file: it could not be read." assert out["throw_then_success"]["components"] == ["from_B"] + assert out["throw_then_success"]["thrown"] == [] # Exact binary ties (where toFixed rounds away from zero and Python to even), signs, @@ -755,3 +783,47 @@ def test_percent_change_display_matches_the_heatmap_annotation(tmp_path): # Stats use two digits: 0.125 shows as 0.12, as Python formats it. small = {"model_name": "m", "baseline_metrics": {"a": 0.125}, "results": _results({"a": 1.0})} assert _render_one(tmp_path, small)["stats"].startswith("0.12Baseline a") + + +# Values Python formats specially: negative zero keeps its sign, and non-finite +# values (sent by name; JSON has no Infinity) print as inf/nan. +SPECIAL_FORMAT_CASES = [ + (-0.0, 2), (-0.0, 4), (0.0, 2), ("Infinity", 2), ("-Infinity", 4), ("NaN", 1), + (-0.001, 2), (-0.125, 2), +] + + +def test_viewer_formats_negative_zero_and_non_finite_like_python(tmp_path): + """#666: -0.0 shows as -0.00 and infinity as inf, as format(value, ".Nf") prints.""" + viewer = _run_harness(tmp_path, {}, formats=SPECIAL_FORMAT_CASES)["formats"] + assert viewer == [format(float(value), f".{digits}f") for value, digits in SPECIAL_FORMAT_CASES] + + +def test_viewer_signs_negative_zero_and_infinite_changes_like_python(tmp_path): + """#666: a -0.0 change shows as -0.0000 (not +-0.0000), an overflowing one as +inf.""" + zero = {"model_name": "m", "baseline_metrics": {"a": 0.0}, "results": _results({"a": -0.0})} + huge = {"model_name": "m", "baseline_metrics": {"a": -1e308}, "results": _results({"a": 1e308})} + out = _run_viewer(tmp_path, {"zero": [zero], "huge": [huge]}) + delta = -0.0 - 0.0 + assert out["zero"][0]["rows"] == [ + ["layer_removal", "layer_0", format(-0.0, ".4f"), format(delta, "+.4f"), "unavailable"]] + assert out["zero"][0]["rows"][0][2:4] == ["-0.0000", "-0.0000"] + big_delta = 1e308 - -1e308 + big_pct = big_delta / abs(-1e308) * 100 + # Values of 1e21 or more are exempt (JS prints exponent notation); the change columns match. + assert out["huge"][0]["rows"][0][3:] == [format(big_delta, "+.4f"), format(big_pct, "+.1f") + "%"] + assert out["huge"][0]["rows"][0][3:] == ["+inf", "+inf%"] + + +def test_viewer_formatting_survives_engines_without_toFixed_100(tmp_path): + """#666: where toFixed(100) throws (pre-ES2020), formatting falls back to toFixed.""" + cases = FORMAT_CASES + SPECIAL_FORMAT_CASES + out = _run_harness(tmp_path, {}, formats=cases) + assert out["legacy_formats"] is not None, "viewer must expose toFixedHalfEven" + assert not any(str(v).startswith("threw") for v in out["legacy_formats"]), out["legacy_formats"] + python = [format(float(value), f".{digits}f") for value, digits in cases] + for legacy, native, expected in zip(out["legacy_formats"], out["native_formats"], python): + # Either Python's half-even result, or plain toFixed when the probe is unavailable. + assert legacy in (expected, native), (legacy, native, expected) + assert out["legacy_render"]["error"] is None + assert out["legacy_render"]["rows"] > 1 diff --git a/tests/test_study_presets.py b/tests/test_study_presets.py index bba2fcca..6cf7f606 100644 --- a/tests/test_study_presets.py +++ b/tests/test_study_presets.py @@ -106,3 +106,31 @@ class TestConfigWithPreset: assert len(config.strategies) == 4 strategy_names = {s.name for s in config.strategies} assert strategy_names == {"layer_removal", "head_pruning", "ffn_ablation", "embedding_ablation"} + + +class TestPresetIsolation: + """#666: callers get copies, so editing one cannot change the shared preset (#637).""" + + def test_get_study_preset_returns_an_independent_copy(self): + preset = get_study_preset("quick") + preset.strategies[0]["params"]["layer"] = 0 + preset.strategies.append({"name": "head_pruning", "params": {}}) + preset.metrics.append("accuracy") + preset.tags.append("edited") + preset.max_samples = 1 + + fresh = get_study_preset("quick") + assert [s["params"] for s in fresh.strategies] == [{}, {}] + assert fresh.metrics == ["perplexity"] + assert "edited" not in fresh.tags + assert fresh.max_samples == 25 + assert fresh == STUDY_PRESETS["quick"] + + def test_list_study_presets_returns_independent_copies(self): + for preset in list_study_presets(): + preset.strategies.clear() + preset.metrics.clear() + + assert all(p.strategies and p.metrics for p in list_study_presets()) + assert all(p.strategies and p.metrics for p in STUDY_PRESETS.values()) + assert list_presets() == list_study_presets()