push code/train/evaluater.py
Browse files- code/train/evaluater.py +612 -18
code/train/evaluater.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
"""Evaluation related functions."""
|
| 2 |
|
|
|
|
|
|
|
| 3 |
from flax.training import common_utils
|
| 4 |
import jax
|
| 5 |
from jax import numpy as jnp
|
|
@@ -10,6 +12,240 @@ from train import model
|
|
| 10 |
import pdb
|
| 11 |
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def valid_solution(output_seq):
|
| 15 |
"""
|
|
@@ -80,7 +316,8 @@ def verify_sudoku_board(puzzle, row_num, col_num, num):
|
|
| 80 |
assert puzzle[row_num * 9 + col_num] == num
|
| 81 |
|
| 82 |
|
| 83 |
-
def get_eval_metrics(state, eval_data_iter, p_eval_step, config
|
|
|
|
| 84 |
"""This function computes given evaluation metrics (e.g, accuracy) in eval metrics for each batch and appends the metric in the list of eval_metrics.
|
| 85 |
|
| 86 |
Args:
|
|
@@ -88,14 +325,30 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 88 |
eval_data_iter: data iterator for evaluation dataset
|
| 89 |
p_eval_step: pmap function for forward pass of model for evaluation
|
| 90 |
config: general experiment config file
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
Returns:
|
| 93 |
eval_metrics: contains list of evaluation metrics for each batch
|
| 94 |
"""
|
| 95 |
|
| 96 |
eval_metrics = {
|
| 97 |
-
"acc": [], #
|
| 98 |
"loc_acc": [], # Location acc: model picks the ground-truth next cell (r,c)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
"val_given_loc_acc": [], # Correct digit AMONG steps where location matched
|
| 100 |
"cand_bit_acc": [], # Per-digit accuracy of predicted candidate masks
|
| 101 |
"cand_set_acc": [], # Exact candidate-SET match per empty cell (all 9 bits)
|
|
@@ -126,6 +379,59 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 126 |
inset_ok = np.zeros(max(K, 1), dtype=np.int64)
|
| 127 |
inset_tot = np.zeros(max(K, 1), dtype=np.int64)
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
# Per-round-bin cell accuracy, for the round-count DATA curriculum: bin b is
|
| 130 |
# unlocked at stage b, so bin_ok[b]/bin_tot[b] measures competence on the
|
| 131 |
# puzzles that stage b introduced. This is the promotion signal for the arm
|
|
@@ -150,6 +456,17 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 150 |
levels = np.array(batch_tuple[3]).reshape(-1)
|
| 151 |
rbins = (np.array(batch_tuple[5]).reshape(-1)
|
| 152 |
if len(batch_tuple) > 5 else np.zeros_like(levels))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
total_pred, sucess_pred = 0, 0
|
| 154 |
# Location = did the model emit the ground-truth next (r,c) cell.
|
| 155 |
loc_tot, loc_ok, val_given_loc_ok = 0, 0, 0
|
|
@@ -249,6 +566,147 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 249 |
slot_ok_ch += (set_match & valid_ch).sum(axis=(0, 2))
|
| 250 |
slot_tot_ch += valid_ch.sum(axis=(0, 2))
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
min_start_index = int(np.min(start_index))
|
| 253 |
cur_input_seq = input_seq[:, :(min_start_index*3)]
|
| 254 |
for i in range(min_start_index * 3, config.seq_len):
|
|
@@ -342,6 +800,47 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 342 |
def strip_latent_slots(seq, si):
|
| 343 |
return np.concatenate([seq[:3*si], seq[3*si + K:]])
|
| 344 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
# ---- Print one concrete example answer the model generated ----
|
| 346 |
if eval_epoch == 0:
|
| 347 |
j = 0
|
|
@@ -355,12 +854,13 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 355 |
n_tot += 1; n_ok += int(ok)
|
| 356 |
if len(shown) < 12:
|
| 357 |
shown.append(f"({r},{c})->{v}[true {tv}]{'ok' if ok else 'X'}")
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
|
|
|
| 364 |
|
| 365 |
# Instance arm: emitted digit next to the deepest stage's
|
| 366 |
# candidate set, so it is visible whether the model is sitting
|
|
@@ -375,8 +875,9 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 375 |
if (bits >> d) & 1)
|
| 376 |
shown.append(f"(r{r},c{c})->{int(pred[3*t3+2])} "
|
| 377 |
f"in{{{cset}}}")
|
| 378 |
-
|
| 379 |
-
|
|
|
|
| 380 |
|
| 381 |
# ---- Candidate-set (multi-value) prediction for this puzzle ----
|
| 382 |
# Show, at the last active latent slot, predicted vs target
|
|
@@ -396,8 +897,9 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 396 |
cand_shown.append(f"(r{r},c{c}) pred{{{pset}}} true{{{tset}}}")
|
| 397 |
if len(cand_shown) >= 8:
|
| 398 |
break
|
| 399 |
-
|
| 400 |
-
|
|
|
|
| 401 |
|
| 402 |
correct_eval_sudoku_puzzle = 0
|
| 403 |
|
|
@@ -415,9 +917,10 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 415 |
per_level = {lvl: (level_ok[lvl] / level_tot[lvl] if level_tot[lvl] else -1.0)
|
| 416 |
for lvl in range(3, 9)}
|
| 417 |
eval_metrics["per_level_acc"] = per_level
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
|
|
|
| 421 |
|
| 422 |
# Per-depth candidate-set accuracy, keyed by stage (slot j -> stage j+1) so
|
| 423 |
# the curriculum controller can index it directly by stage number.
|
|
@@ -432,7 +935,98 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 432 |
per_stage_inset = {s + 1: (float(inset_ok[s] / inset_tot[s])
|
| 433 |
if inset_tot[s] else -1.0) for s in range(K)}
|
| 434 |
eval_metrics["per_stage_inset_acc"] = per_stage_inset
|
| 435 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
print("PER-STAGE in-set rate (emitted digit is a stage-s candidate):",
|
| 437 |
{s: (f"{v:.3f}" if v >= 0 else "n/a")
|
| 438 |
for s, v in per_stage_inset.items()}, flush=True)
|
|
@@ -440,11 +1034,11 @@ def get_eval_metrics(state, eval_data_iter, p_eval_step, config):
|
|
| 440 |
per_bin = {b: (bin_ok[b] / bin_tot[b] if bin_tot[b] else -1.0)
|
| 441 |
for b in range(1, n_bins + 1)}
|
| 442 |
eval_metrics["per_bin_acc"] = per_bin
|
| 443 |
-
if any(v >= 0 for v in per_bin.values()):
|
| 444 |
print("PER-ROUND-BIN cell acc:",
|
| 445 |
{b: (f"{v:.3f}" if v >= 0 else "n/a") for b, v in per_bin.items()},
|
| 446 |
flush=True)
|
| 447 |
-
if K > 0:
|
| 448 |
print("PER-DEPTH cand-set acc:",
|
| 449 |
{s: (f"{v:.3f}" if v >= 0 else "n/a") for s, v in per_slot.items()},
|
| 450 |
flush=True)
|
|
|
|
| 1 |
"""Evaluation related functions."""
|
| 2 |
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
from flax.training import common_utils
|
| 6 |
import jax
|
| 7 |
from jax import numpy as jnp
|
|
|
|
| 12 |
import pdb
|
| 13 |
|
| 14 |
|
| 15 |
+
def _verbose_eval():
|
| 16 |
+
return os.environ.get("SUDOKU_VERBOSE_EVAL", "0") == "1"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _lcs_len(a, b):
|
| 20 |
+
"""Length of the longest common subsequence of two cell sequences.
|
| 21 |
+
|
| 22 |
+
Measures order agreement while tolerating insertions, so a single early
|
| 23 |
+
deviation costs one step instead of desyncing every later comparison the
|
| 24 |
+
way a positional match does.
|
| 25 |
+
"""
|
| 26 |
+
prev = [0] * (len(b) + 1)
|
| 27 |
+
for x in a:
|
| 28 |
+
cur = [0]
|
| 29 |
+
for k, y in enumerate(b):
|
| 30 |
+
cur.append(prev[k] + 1 if x == y else max(cur[k], prev[k + 1]))
|
| 31 |
+
prev = cur
|
| 32 |
+
return prev[-1]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _inst_ce_stats(logp_digits, bits, qcounts):
|
| 36 |
+
"""CE(q || p) against the ceiling log|S|, per cell.
|
| 37 |
+
|
| 38 |
+
q is the empirical per-cell digit distribution of this puzzle's stored
|
| 39 |
+
instances at this stage: the POST-constraint distribution the data actually
|
| 40 |
+
teaches. That is the whole point of using it instead of Uniform(S). By
|
| 41 |
+
Gibbs, CE(Uniform(S) || p) >= log|S| for every p, so comparing that to
|
| 42 |
+
log|S| is a tautology (it is exactly `excess >= 0`). CE(q || p) instead has
|
| 43 |
+
floor H(q), and H(q) < log|S| strictly whenever the constraints prune
|
| 44 |
+
anything, so the comparison
|
| 45 |
+
|
| 46 |
+
CE(q || p) <= log|S| equivalently KL(q || p) <= log|S| - H(q)
|
| 47 |
+
|
| 48 |
+
is both satisfiable and meaningful: the model's divergence from the truth
|
| 49 |
+
must be smaller than the information the constraints carry. It is also a
|
| 50 |
+
complete test on its own, unlike mass/spread, because it punishes every
|
| 51 |
+
failure mode at once -- dropping a candidate that instances do use sends
|
| 52 |
+
-log p(d) up, and leaking mass outside S lowers p on the digits that are
|
| 53 |
+
actually targets.
|
| 54 |
+
|
| 55 |
+
Two populations are accumulated, because the stage-level question and the
|
| 56 |
+
per-cell question are not the same test.
|
| 57 |
+
|
| 58 |
+
POPULATION (the *_pop keys, and the promotion gate): every |S| >= 2 cell that
|
| 59 |
+
has instances. The gate is the stage average
|
| 60 |
+
|
| 61 |
+
mean CE(q||p) <= mean log|S|,
|
| 62 |
+
|
| 63 |
+
which is exactly "the value cross-entropy this stage is minimizing has been
|
| 64 |
+
driven below the entropy of the uniform candidate set". Nothing is excluded,
|
| 65 |
+
because an average has no per-cell feasibility problem: a cell with no
|
| 66 |
+
headroom simply has to be paid for by cells that do have some.
|
| 67 |
+
|
| 68 |
+
HEADROOM SUBSET (ceq_ok / ceq_gap): the same cells minus those where the bar
|
| 69 |
+
equals the floor, i.e. H(q) = log|S| (q already uniform on S, so by Gibbs
|
| 70 |
+
only p == q exactly could pass) and |S| = 1 (ceiling is log 1 = 0). That
|
| 71 |
+
subset is the right denominator for a *per-cell* pass rate, since 8-27% of
|
| 72 |
+
cells depending on stage would otherwise be unpassable by construction and
|
| 73 |
+
cap the rate below 1. It is a strictly harder test than the average and is
|
| 74 |
+
reported as a diagnostic. The exclusion depends only on q and S, never on p.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
logp_digits: (n, 9) log-probabilities of digits 1..9 under the model.
|
| 78 |
+
bits: (n,) int bitmask; bit d-1 set iff digit d is a candidate.
|
| 79 |
+
qcounts: (n, 9) instance-digit counts; column d-1 counts digit d.
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
Sums over each population plus the counts they divide by.
|
| 83 |
+
"""
|
| 84 |
+
out = {"ceq": 0.0, "hq": 0.0, "ceq_ok": 0, "ceq_gap": 0.0, "ceq_count": 0,
|
| 85 |
+
"puz_ok": 0, "puz_count": 0, "ceq_skip": 0,
|
| 86 |
+
"ceq_pop": 0.0, "hq_pop": 0.0, "logm_pop": 0.0, "pop_count": 0,
|
| 87 |
+
"hinge": 0.0, "hinge_floor": 0.0, "hinge_cnt": 0}
|
| 88 |
+
in_s = ((bits[:, None] >> np.arange(9)) & 1).astype(np.float64)
|
| 89 |
+
size = in_s.sum(axis=1)
|
| 90 |
+
tot = qcounts.sum(axis=1)
|
| 91 |
+
cand = (size >= 2) & (tot > 0)
|
| 92 |
+
if not cand.any():
|
| 93 |
+
return out
|
| 94 |
+
q_all = qcounts[cand].astype(np.float64) / tot[cand][:, None]
|
| 95 |
+
h_all = -(q_all * np.log(np.maximum(q_all, 1e-12))).sum(axis=1)
|
| 96 |
+
l_all = np.log(size[cand])
|
| 97 |
+
ce_all = -(q_all * logp_digits[cand]).sum(axis=1)
|
| 98 |
+
# Population sums: the stage-average gate compares these two directly.
|
| 99 |
+
out["ceq_pop"] = float(ce_all.sum())
|
| 100 |
+
out["hq_pop"] = float(h_all.sum())
|
| 101 |
+
out["logm_pop"] = float(l_all.sum())
|
| 102 |
+
out["pop_count"] = int(cand.sum())
|
| 103 |
+
# Per-puzzle hinge, the same comparison as the gate but resolved on THIS
|
| 104 |
+
# puzzle before any averaging across puzzles. Because max(0,.) is convex,
|
| 105 |
+
# averaging these over puzzles is >= the violation of the pooled average
|
| 106 |
+
# (Jensen), so it is a strictly stronger test: a puzzle still above its own
|
| 107 |
+
# bar can no longer be paid for by puzzles that have slack to spare.
|
| 108 |
+
out["hinge"] = float(max(0.0, ce_all.mean() - l_all.mean()))
|
| 109 |
+
# What the hinge would still read at p == q, i.e. for a model that has
|
| 110 |
+
# matched the instance distribution exactly. Depends only on q and S, never
|
| 111 |
+
# on p, so it is the floor no model can beat and the only defensible way to
|
| 112 |
+
# set a tolerance on `hinge`. Puzzles whose constraints barely bite have
|
| 113 |
+
# H(q) ~ log|S| and contribute a floor > 0 all by themselves.
|
| 114 |
+
out["hinge_floor"] = float(max(0.0, h_all.mean() - l_all.mean()))
|
| 115 |
+
out["hinge_cnt"] = 1
|
| 116 |
+
# Per-cell pass rate, over the cells where passing is possible at all.
|
| 117 |
+
room = (l_all - h_all) > 1e-9
|
| 118 |
+
out["ceq_skip"] = int((~room).sum())
|
| 119 |
+
if not room.any():
|
| 120 |
+
return out
|
| 121 |
+
gap = l_all[room] - ce_all[room]
|
| 122 |
+
out["ceq"] = float(ce_all[room].sum())
|
| 123 |
+
out["hq"] = float(h_all[room].sum())
|
| 124 |
+
out["ceq_ok"] = int((gap >= 0).sum())
|
| 125 |
+
out["ceq_gap"] = float(gap.sum())
|
| 126 |
+
out["ceq_count"] = int(room.sum())
|
| 127 |
+
out["puz_ok"] = int(bool((gap >= 0).all()))
|
| 128 |
+
out["puz_count"] = 1
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _cand_value_stats(logp_digits, bits):
|
| 133 |
+
"""Value-head statistics against one stage's candidate sets.
|
| 134 |
+
|
| 135 |
+
S is the RAW wave-solver candidate set at that cell (the bitmask in
|
| 136 |
+
cand_targets), NOT the support of the filtered instances after constraint
|
| 137 |
+
solving. A digit can be in S and still never appear in a surviving
|
| 138 |
+
instance; we still want p uniform over S, because that is the
|
| 139 |
+
pre-constraint superposition.
|
| 140 |
+
|
| 141 |
+
The instance target at a cell is drawn uniformly from S, so the CE the
|
| 142 |
+
trainer minimizes is
|
| 143 |
+
CE = -(1/|S|) sum_{d in S} log p(d) >= log|S|,
|
| 144 |
+
with equality iff p == Uniform(S); collapsing onto one candidate sends it
|
| 145 |
+
to infinity. So CE - log|S| == KL(Uniform(S) || p) is zero exactly at
|
| 146 |
+
true superposition and grows from leakage outside S or collapse inside it.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
logp_digits: (n, 9) log-probabilities of digits 1..9 under the model.
|
| 150 |
+
bits: (n,) int bitmask; bit d-1 set iff digit d is a candidate.
|
| 151 |
+
|
| 152 |
+
Returns:
|
| 153 |
+
Dict of sums over the n cells plus the counts they divide by. `spread`
|
| 154 |
+
(normalized within-set entropy, 1.0 = uniform over S) is only defined
|
| 155 |
+
for |S| >= 2, hence its own count.
|
| 156 |
+
"""
|
| 157 |
+
in_s = ((bits[:, None] >> np.arange(9)) & 1).astype(np.float64) # (n, 9)
|
| 158 |
+
size = in_s.sum(axis=1)
|
| 159 |
+
p_d = np.exp(logp_digits)
|
| 160 |
+
mass = (in_s * p_d).sum(axis=1)
|
| 161 |
+
ce = -(in_s * logp_digits).sum(axis=1) / size
|
| 162 |
+
# excess splits exactly into the two things we want driven to zero:
|
| 163 |
+
# excess = CE - log|S| = log(1/mass) + KL(Uniform(S) || p/mass)
|
| 164 |
+
# \_________/ \_________/
|
| 165 |
+
# leak outside non-uniformity inside
|
| 166 |
+
# Both terms are >= 0, so excess == 0 iff all mass is on S AND spread
|
| 167 |
+
# uniformly over it. Derivation: writing p(d) = mass * q(d) for d in S,
|
| 168 |
+
# CE = -log(mass) - (1/|S|) sum log q(d) = -log(mass) + log|S| + KL(U||q).
|
| 169 |
+
excess = ce - np.log(size)
|
| 170 |
+
# Entropy of the model's digit distribution, renormalized over digits 1..9
|
| 171 |
+
# (the log_softmax ran over the full vocab, which also holds the latent and
|
| 172 |
+
# coordinate tokens). This is deliberately NOT the `spread` numerator below:
|
| 173 |
+
# that one renormalizes onto S, so it satisfies H <= log|S| by construction
|
| 174 |
+
# and cannot detect leakage. Over all 9 digits H can reach log 9, and
|
| 175 |
+
# H(p) > log|S| ==> p carries mass outside S,
|
| 176 |
+
# since Uniform(S) is the max-entropy distribution supported on S. So the
|
| 177 |
+
# bound is a necessary condition for having learned the stage's constraints,
|
| 178 |
+
# and it tightens as the curriculum shrinks |S|.
|
| 179 |
+
p_dig = p_d / np.maximum(p_d.sum(axis=1, keepdims=True), 1e-12)
|
| 180 |
+
h_full = -(p_dig * np.log(np.maximum(p_dig, 1e-12))).sum(axis=1)
|
| 181 |
+
out = {
|
| 182 |
+
"ce": float(ce.sum()),
|
| 183 |
+
"floor": float(np.log(size).sum()),
|
| 184 |
+
"mass": float(mass.sum()),
|
| 185 |
+
"count": int(size.size),
|
| 186 |
+
"spread": 0.0,
|
| 187 |
+
"spread_count": 0,
|
| 188 |
+
# Same quantities restricted to genuinely superposed cells (|S| >= 2).
|
| 189 |
+
# Singleton cells are already determined at this stage, so there is
|
| 190 |
+
# nothing to be uniform about; as the curriculum deepens they come to
|
| 191 |
+
# dominate the pooled average and dilute the superposition signal.
|
| 192 |
+
"excess_multi": 0.0,
|
| 193 |
+
"mass_multi": 0.0,
|
| 194 |
+
"kl_multi": 0.0,
|
| 195 |
+
# Entropy-ceiling aggregates. The inequality is per cell, and averaging
|
| 196 |
+
# H and log|S| separately is NOT equivalent to it: a mean gap can stay
|
| 197 |
+
# positive while many individual cells violate. So count cells.
|
| 198 |
+
"hbound_ok": 0, # cells satisfying H(p) <= log|S|
|
| 199 |
+
"hgap": 0.0, # sum of log|S| - H(p), the margin in nats
|
| 200 |
+
"hbound_all": 0, # 1 iff every |S|>=2 cell here satisfies it
|
| 201 |
+
"hbound_groups": 0, # number of (puzzle, stage) groups counted
|
| 202 |
+
}
|
| 203 |
+
multi = size >= 2
|
| 204 |
+
if multi.any():
|
| 205 |
+
m = np.maximum(mass[multi], 1e-12)
|
| 206 |
+
q = in_s[multi] * p_d[multi] / m[:, None]
|
| 207 |
+
h = -(q * np.log(np.maximum(q, 1e-12))).sum(axis=1)
|
| 208 |
+
out["spread"] = float((h / np.log(size[multi])).sum())
|
| 209 |
+
out["spread_count"] = int(multi.sum())
|
| 210 |
+
out["excess_multi"] = float(excess[multi].sum())
|
| 211 |
+
out["mass_multi"] = float(mass[multi].sum())
|
| 212 |
+
# KL(Uniform(S) || q): the non-uniformity term of the split above.
|
| 213 |
+
# Stricter than 1 - spread, because it weights every candidate equally
|
| 214 |
+
# and so blows up when the model drops one candidate to ~0.
|
| 215 |
+
out["kl_multi"] = float((excess[multi] + np.log(m)).sum())
|
| 216 |
+
gap = np.log(size[multi]) - h_full[multi]
|
| 217 |
+
out["hbound_ok"] = int((gap >= 0).sum())
|
| 218 |
+
out["hgap"] = float(gap.sum())
|
| 219 |
+
out["hbound_all"] = int(bool((gap >= 0).all()))
|
| 220 |
+
out["hbound_groups"] = 1
|
| 221 |
+
return out
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _wave_order_score(emitted, truth, waves, max_wave):
|
| 225 |
+
"""How many emitted cells came from the earliest still-unfilled wave.
|
| 226 |
+
|
| 227 |
+
A cell's wave is the propagation depth that determines it. Cells sharing a
|
| 228 |
+
wave are order-interchangeable, so the solver order in the data is only one
|
| 229 |
+
valid linearization; crediting any cell from the frontier wave measures
|
| 230 |
+
"is the model respecting propagation depth" without penalizing an arbitrary
|
| 231 |
+
tie-break. Cells that repeat or are not real empty cells score nothing.
|
| 232 |
+
"""
|
| 233 |
+
left = dict(zip(truth, waves))
|
| 234 |
+
per_wave = np.bincount(np.asarray(waves, dtype=np.int64),
|
| 235 |
+
minlength=max_wave + 1)
|
| 236 |
+
min_w, ok = 0, 0
|
| 237 |
+
for cell in emitted:
|
| 238 |
+
while min_w <= max_wave and per_wave[min_w] == 0:
|
| 239 |
+
min_w += 1
|
| 240 |
+
if min_w > max_wave:
|
| 241 |
+
break
|
| 242 |
+
cw = left.pop(cell, None)
|
| 243 |
+
if cw is None:
|
| 244 |
+
continue
|
| 245 |
+
per_wave[cw] -= 1
|
| 246 |
+
ok += int(cw == min_w)
|
| 247 |
+
return ok
|
| 248 |
+
|
| 249 |
|
| 250 |
def valid_solution(output_seq):
|
| 251 |
"""
|
|
|
|
| 316 |
assert puzzle[row_num * 9 + col_num] == num
|
| 317 |
|
| 318 |
|
| 319 |
+
def get_eval_metrics(state, eval_data_iter, p_eval_step, config,
|
| 320 |
+
curriculum=None):
|
| 321 |
"""This function computes given evaluation metrics (e.g, accuracy) in eval metrics for each batch and appends the metric in the list of eval_metrics.
|
| 322 |
|
| 323 |
Args:
|
|
|
|
| 325 |
eval_data_iter: data iterator for evaluation dataset
|
| 326 |
p_eval_step: pmap function for forward pass of model for evaluation
|
| 327 |
config: general experiment config file
|
| 328 |
+
curriculum: current CurriculumState, or None. When given, the stage it
|
| 329 |
+
names gets a second CE(q||p) pass scored the way training feeds the
|
| 330 |
+
model -- instance-valued prefix, that stage's latent depth -- and
|
| 331 |
+
reported under the *_inst keys. The promotion gate reads those.
|
| 332 |
|
| 333 |
Returns:
|
| 334 |
eval_metrics: contains list of evaluation metrics for each batch
|
| 335 |
"""
|
| 336 |
|
| 337 |
eval_metrics = {
|
| 338 |
+
"acc": [], # Unique-solution placement (parent leftover; not printed as val_acc)
|
| 339 |
"loc_acc": [], # Location acc: model picks the ground-truth next cell (r,c)
|
| 340 |
+
# Permutation-tolerant location diagnostics. The upstream code scored
|
| 341 |
+
# only "acc" -- the digit at the cell the model chose -- and never
|
| 342 |
+
# compared (r,c) to the target order, because the solver order is one
|
| 343 |
+
# arbitrary linearization of a partial order: cells that become
|
| 344 |
+
# determined in the same propagation wave are interchangeable. loc_acc
|
| 345 |
+
# above therefore reads ~0.04 even when the model emits a valid
|
| 346 |
+
# permutation of the right cells, since one early deviation desyncs the
|
| 347 |
+
# rest of the positional comparison. These three replace it.
|
| 348 |
+
"loc_coverage": [], # distinct emitted cells that are really empty / #empty
|
| 349 |
+
"loc_dup": [], # fraction of emitted cells that repeat an earlier one
|
| 350 |
+
"loc_lcs": [], # longest common subsequence with target order / #empty
|
| 351 |
+
"loc_wave": [], # emitted cell sits in the earliest unfilled wave
|
| 352 |
"val_given_loc_acc": [], # Correct digit AMONG steps where location matched
|
| 353 |
"cand_bit_acc": [], # Per-digit accuracy of predicted candidate masks
|
| 354 |
"cand_set_acc": [], # Exact candidate-SET match per empty cell (all 9 bits)
|
|
|
|
| 379 |
inset_ok = np.zeros(max(K, 1), dtype=np.int64)
|
| 380 |
inset_tot = np.zeros(max(K, 1), dtype=np.int64)
|
| 381 |
|
| 382 |
+
# Per-stage value-distribution stats, measured TEACHER-FORCED so the cell is
|
| 383 |
+
# given and the value head is scored in isolation from the model's choice of
|
| 384 |
+
# location. For a cell whose stage-s candidate set is S, the instance target
|
| 385 |
+
# is drawn uniformly from S, so the CE the trainer minimizes is
|
| 386 |
+
# CE = -(1/|S|) sum_{d in S} log p(d) >= log|S|,
|
| 387 |
+
# with equality iff p == Uniform(S). Collapsing onto a single candidate
|
| 388 |
+
# sends CE to infinity. So (CE - log|S|) == KL(Uniform(S) || p) is a single
|
| 389 |
+
# number that is 0 exactly at true superposition and grows from either
|
| 390 |
+
# leakage outside S or mode collapse inside it.
|
| 391 |
+
vce_sum = np.zeros(max(K, 1), dtype=np.float64) # sum of CE vs Uniform(S)
|
| 392 |
+
vfloor_sum = np.zeros(max(K, 1), dtype=np.float64) # sum of log|S|
|
| 393 |
+
vmass_sum = np.zeros(max(K, 1), dtype=np.float64) # sum of prob mass on S
|
| 394 |
+
vspread_sum = np.zeros(max(K, 1), dtype=np.float64) # sum of H(p|S)/log|S|
|
| 395 |
+
vcnt = np.zeros(max(K, 1), dtype=np.int64)
|
| 396 |
+
vspread_cnt = np.zeros(max(K, 1), dtype=np.int64) # only |S| >= 2 cells
|
| 397 |
+
# Same, restricted to |S| >= 2 (the cells that carry real superposition).
|
| 398 |
+
vexc_m_sum = np.zeros(max(K, 1), dtype=np.float64)
|
| 399 |
+
vmass_m_sum = np.zeros(max(K, 1), dtype=np.float64)
|
| 400 |
+
vkl_m_sum = np.zeros(max(K, 1), dtype=np.float64)
|
| 401 |
+
# Entropy ceiling H(p) <= log|S|, counted per cell and per (puzzle, stage).
|
| 402 |
+
vhok_sum = np.zeros(max(K, 1), dtype=np.int64)
|
| 403 |
+
vhgap_sum = np.zeros(max(K, 1), dtype=np.float64)
|
| 404 |
+
vhall_sum = np.zeros(max(K, 1), dtype=np.int64)
|
| 405 |
+
vhgrp_sum = np.zeros(max(K, 1), dtype=np.int64)
|
| 406 |
+
# CE(q||p) vs the ceiling log|S|, q = the instances' own digit frequencies.
|
| 407 |
+
vceq_sum = np.zeros(max(K, 1), dtype=np.float64)
|
| 408 |
+
vhq_sum = np.zeros(max(K, 1), dtype=np.float64)
|
| 409 |
+
vceq_ok = np.zeros(max(K, 1), dtype=np.int64)
|
| 410 |
+
vceq_gap = np.zeros(max(K, 1), dtype=np.float64)
|
| 411 |
+
vceq_cnt = np.zeros(max(K, 1), dtype=np.int64)
|
| 412 |
+
vceq_all = np.zeros(max(K, 1), dtype=np.int64)
|
| 413 |
+
vceq_grp = np.zeros(max(K, 1), dtype=np.int64)
|
| 414 |
+
# Population sums over every |S|>=2 cell: the stage-average promotion gate.
|
| 415 |
+
vceq_pop = np.zeros(max(K, 1), dtype=np.float64)
|
| 416 |
+
vhq_pop = np.zeros(max(K, 1), dtype=np.float64)
|
| 417 |
+
vlogm_pop = np.zeros(max(K, 1), dtype=np.float64)
|
| 418 |
+
vpop_cnt = np.zeros(max(K, 1), dtype=np.int64)
|
| 419 |
+
# Per-puzzle hinge mean(max(0, CE_i - log|S|_i)), and the p==q floor it can
|
| 420 |
+
# never go below. Denominator is puzzles, not cells.
|
| 421 |
+
vhinge_sum = np.zeros(max(K, 1), dtype=np.float64)
|
| 422 |
+
vhinge_floor = np.zeros(max(K, 1), dtype=np.float64)
|
| 423 |
+
vhinge_cnt = np.zeros(max(K, 1), dtype=np.int64)
|
| 424 |
+
# Same statistics from the train-matched pass (instance prefix, stage depth).
|
| 425 |
+
# Only the gate stage is filled; the rest stay at -1 via _per_stage's count.
|
| 426 |
+
vceq_pop_i = np.zeros(max(K, 1), dtype=np.float64)
|
| 427 |
+
vlogm_pop_i = np.zeros(max(K, 1), dtype=np.float64)
|
| 428 |
+
vhq_pop_i = np.zeros(max(K, 1), dtype=np.float64)
|
| 429 |
+
vpop_cnt_i = np.zeros(max(K, 1), dtype=np.int64)
|
| 430 |
+
vhinge_sum_i = np.zeros(max(K, 1), dtype=np.float64)
|
| 431 |
+
vhinge_floor_i = np.zeros(max(K, 1), dtype=np.float64)
|
| 432 |
+
vhinge_cnt_i = np.zeros(max(K, 1), dtype=np.int64)
|
| 433 |
+
gate_stage = (int(curriculum.stage) if curriculum is not None else 0)
|
| 434 |
+
|
| 435 |
# Per-round-bin cell accuracy, for the round-count DATA curriculum: bin b is
|
| 436 |
# unlocked at stage b, so bin_ok[b]/bin_tot[b] measures competence on the
|
| 437 |
# puzzles that stage b introduced. This is the promotion signal for the arm
|
|
|
|
| 456 |
levels = np.array(batch_tuple[3]).reshape(-1)
|
| 457 |
rbins = (np.array(batch_tuple[5]).reshape(-1)
|
| 458 |
if len(batch_tuple) > 5 else np.zeros_like(levels))
|
| 459 |
+
# (bs, K, 81, 9) instance-digit counts; zeros when the run has no
|
| 460 |
+
# instance pool, in which case CE(q||p) is simply not reported.
|
| 461 |
+
q_counts = (np.array(batch_tuple[6]).astype(np.int64)
|
| 462 |
+
if len(batch_tuple) > 6 else None)
|
| 463 |
+
# (bs, R, seq_len) instance-valued copies of input_seq; all zeros on
|
| 464 |
+
# runs without an instance pool, in which case the train-matched
|
| 465 |
+
# CE pass is skipped and only the legacy keys are reported.
|
| 466 |
+
inst_seqs = (np.array(batch_tuple[7])
|
| 467 |
+
if len(batch_tuple) > 7 else None)
|
| 468 |
+
if inst_seqs is not None and not inst_seqs.any():
|
| 469 |
+
inst_seqs = None
|
| 470 |
total_pred, sucess_pred = 0, 0
|
| 471 |
# Location = did the model emit the ground-truth next (r,c) cell.
|
| 472 |
loc_tot, loc_ok, val_given_loc_ok = 0, 0, 0
|
|
|
|
| 566 |
slot_ok_ch += (set_match & valid_ch).sum(axis=(0, 2))
|
| 567 |
slot_tot_ch += valid_ch.sum(axis=(0, 2))
|
| 568 |
|
| 569 |
+
# ---- Teacher-forced value distribution vs the candidate set ----
|
| 570 |
+
# One forward pass on the ground-truth solver-order sequence. The
|
| 571 |
+
# prefix pins down which cell each value slot refers to, so this
|
| 572 |
+
# measures the value head alone: location cannot contaminate it,
|
| 573 |
+
# and no sampling is needed because the full softmax is available.
|
| 574 |
+
if K > 0 and cand_targets is not None:
|
| 575 |
+
tf_logits, _ = run_model(input_seq, latent_vals, active_full)
|
| 576 |
+
# log_softmax over the whole vocab, matching the training CE.
|
| 577 |
+
tf_shift = tf_logits - tf_logits.max(axis=-1, keepdims=True)
|
| 578 |
+
tf_logp = tf_shift - np.log(
|
| 579 |
+
np.exp(tf_shift).sum(axis=-1, keepdims=True))
|
| 580 |
+
for j in range(bs):
|
| 581 |
+
si = int(start_index[j].reshape(-1)[0])
|
| 582 |
+
n_out = 81 - si
|
| 583 |
+
if n_out <= 0:
|
| 584 |
+
continue
|
| 585 |
+
base = 3 * si + K
|
| 586 |
+
t = np.arange(n_out)
|
| 587 |
+
v_pos = base + 3 * t + 2 # value token positions
|
| 588 |
+
if v_pos[-1] >= config.seq_len:
|
| 589 |
+
keep = v_pos < config.seq_len
|
| 590 |
+
t, v_pos = t[keep], v_pos[keep]
|
| 591 |
+
if t.size == 0:
|
| 592 |
+
continue
|
| 593 |
+
# Token ids are the numbers themselves: rows/cols 0..8 and
|
| 594 |
+
# digits 1..9, so digit d lives at vocab index d.
|
| 595 |
+
cells = (input_seq[j, base + 3 * t] * 9
|
| 596 |
+
+ input_seq[j, base + 3 * t + 1]).astype(np.int64)
|
| 597 |
+
ok_cell = (cells >= 0) & (cells < 81)
|
| 598 |
+
# logits at index p-1 predict the token at position p.
|
| 599 |
+
logp_d = tf_logp[j, v_pos - 1, 1:10] # (n, 9)
|
| 600 |
+
for s in range(K):
|
| 601 |
+
bits = cand_targets[j, s, np.where(ok_cell, cells, 0)]
|
| 602 |
+
# bits <= 0 marks a clue cell, which is not supervised.
|
| 603 |
+
sel = ok_cell & (bits > 0)
|
| 604 |
+
if not sel.any():
|
| 605 |
+
continue
|
| 606 |
+
st = _cand_value_stats(logp_d[sel], bits[sel])
|
| 607 |
+
vce_sum[s] += st["ce"]
|
| 608 |
+
vfloor_sum[s] += st["floor"]
|
| 609 |
+
vmass_sum[s] += st["mass"]
|
| 610 |
+
vcnt[s] += st["count"]
|
| 611 |
+
vspread_sum[s] += st["spread"]
|
| 612 |
+
vspread_cnt[s] += st["spread_count"]
|
| 613 |
+
vexc_m_sum[s] += st["excess_multi"]
|
| 614 |
+
vmass_m_sum[s] += st["mass_multi"]
|
| 615 |
+
vkl_m_sum[s] += st["kl_multi"]
|
| 616 |
+
vhok_sum[s] += st["hbound_ok"]
|
| 617 |
+
vhgap_sum[s] += st["hgap"]
|
| 618 |
+
vhall_sum[s] += st["hbound_all"]
|
| 619 |
+
vhgrp_sum[s] += st["hbound_groups"]
|
| 620 |
+
if q_counts is not None:
|
| 621 |
+
qs = _inst_ce_stats(
|
| 622 |
+
logp_d[sel], bits[sel],
|
| 623 |
+
q_counts[j, s, np.where(ok_cell, cells, 0)][sel])
|
| 624 |
+
vceq_sum[s] += qs["ceq"]
|
| 625 |
+
vhq_sum[s] += qs["hq"]
|
| 626 |
+
vceq_ok[s] += qs["ceq_ok"]
|
| 627 |
+
vceq_gap[s] += qs["ceq_gap"]
|
| 628 |
+
vceq_cnt[s] += qs["ceq_count"]
|
| 629 |
+
vceq_all[s] += qs["puz_ok"]
|
| 630 |
+
vceq_grp[s] += qs["puz_count"]
|
| 631 |
+
vceq_pop[s] += qs["ceq_pop"]
|
| 632 |
+
vhq_pop[s] += qs["hq_pop"]
|
| 633 |
+
vlogm_pop[s] += qs["logm_pop"]
|
| 634 |
+
vpop_cnt[s] += qs["pop_count"]
|
| 635 |
+
vhinge_sum[s] += qs["hinge"]
|
| 636 |
+
vhinge_floor[s] += qs["hinge_floor"]
|
| 637 |
+
vhinge_cnt[s] += qs["hinge_cnt"]
|
| 638 |
+
|
| 639 |
+
# ---- The gate's own CE(q||p), on the footing training uses ----
|
| 640 |
+
# Two corrections to the pass above, both of which inflate it:
|
| 641 |
+
# prefix: it reads p off the solution-valued sequence, so every
|
| 642 |
+
# earlier empty cell hands the model the true digit and the
|
| 643 |
+
# current cell is settled by elimination, then charged against
|
| 644 |
+
# a q that conditions on no such thing. Instance-valued
|
| 645 |
+
# sequences are what training feeds; p is averaged over R of
|
| 646 |
+
# them to recover a marginal comparable to q.
|
| 647 |
+
# depth: it runs all K slots (k_budget = K above) and compares
|
| 648 |
+
# that one full-depth prediction against every stage's q. The
|
| 649 |
+
# stage being gated is only training `stage` of them.
|
| 650 |
+
if (K > 0 and cand_targets is not None and q_counts is not None
|
| 651 |
+
and inst_seqs is not None and gate_stage):
|
| 652 |
+
# The q being scored is the stage's, but the depth p is read at
|
| 653 |
+
# is the depth the stage TRAINS at: num_passes = min(pps*stage,
|
| 654 |
+
# K), the same formula train_and_evaluate uses. These coincide
|
| 655 |
+
# at pps=1; at pps=K every stage trains at full depth and the
|
| 656 |
+
# gate must read there too, or it scores a depth the weights
|
| 657 |
+
# were never fit at.
|
| 658 |
+
s0 = min(gate_stage, K) - 1
|
| 659 |
+
pps = int(getattr(config, "passes_per_stage", 1))
|
| 660 |
+
depth_gate = min(max(pps * gate_stage, 1), K)
|
| 661 |
+
R = int(inst_seqs.shape[1])
|
| 662 |
+
act_gate = np.arange(K)[None, :] < depth_gate
|
| 663 |
+
act_gate = np.broadcast_to(act_gate, (bs, K))
|
| 664 |
+
lv_gate = np.zeros((bs, K, config.emb_dim), dtype=np.float32)
|
| 665 |
+
if recurrent:
|
| 666 |
+
for j in range(depth_gate):
|
| 667 |
+
act_j = act_gate & (np.arange(K)[None, :] < j)
|
| 668 |
+
_, hidden = run_model(build_seq_masked, lv_gate, act_j)
|
| 669 |
+
lv_gate[:, j] = hidden[bidx, si3 - 1 + j]
|
| 670 |
+
p_mix = None
|
| 671 |
+
for r in range(R):
|
| 672 |
+
lg, _ = run_model(np.asarray(inst_seqs[:, r]), lv_gate,
|
| 673 |
+
act_gate)
|
| 674 |
+
sh = lg - lg.max(axis=-1, keepdims=True)
|
| 675 |
+
pr = np.exp(sh)
|
| 676 |
+
pr /= pr.sum(axis=-1, keepdims=True)
|
| 677 |
+
p_mix = pr if p_mix is None else p_mix + pr
|
| 678 |
+
logp_mix = np.log(np.maximum(p_mix / max(R, 1), 1e-30))
|
| 679 |
+
for j in range(bs):
|
| 680 |
+
si = int(start_index[j].reshape(-1)[0])
|
| 681 |
+
n_out = 81 - si
|
| 682 |
+
if n_out <= 0:
|
| 683 |
+
continue
|
| 684 |
+
base = 3 * si + K
|
| 685 |
+
t = np.arange(n_out)
|
| 686 |
+
v_pos = base + 3 * t + 2
|
| 687 |
+
if v_pos[-1] >= config.seq_len:
|
| 688 |
+
keep = v_pos < config.seq_len
|
| 689 |
+
t, v_pos = t[keep], v_pos[keep]
|
| 690 |
+
if t.size == 0:
|
| 691 |
+
continue
|
| 692 |
+
cells = (input_seq[j, base + 3 * t] * 9
|
| 693 |
+
+ input_seq[j, base + 3 * t + 1]).astype(np.int64)
|
| 694 |
+
ok_cell = (cells >= 0) & (cells < 81)
|
| 695 |
+
bits = cand_targets[j, s0, np.where(ok_cell, cells, 0)]
|
| 696 |
+
sel = ok_cell & (bits > 0)
|
| 697 |
+
if not sel.any():
|
| 698 |
+
continue
|
| 699 |
+
qs = _inst_ce_stats(
|
| 700 |
+
logp_mix[j, v_pos - 1, 1:10][sel], bits[sel],
|
| 701 |
+
q_counts[j, s0, np.where(ok_cell, cells, 0)][sel])
|
| 702 |
+
vceq_pop_i[s0] += qs["ceq_pop"]
|
| 703 |
+
vhq_pop_i[s0] += qs["hq_pop"]
|
| 704 |
+
vlogm_pop_i[s0] += qs["logm_pop"]
|
| 705 |
+
vpop_cnt_i[s0] += qs["pop_count"]
|
| 706 |
+
vhinge_sum_i[s0] += qs["hinge"]
|
| 707 |
+
vhinge_floor_i[s0] += qs["hinge_floor"]
|
| 708 |
+
vhinge_cnt_i[s0] += qs["hinge_cnt"]
|
| 709 |
+
|
| 710 |
min_start_index = int(np.min(start_index))
|
| 711 |
cur_input_seq = input_seq[:, :(min_start_index*3)]
|
| 712 |
for i in range(min_start_index * 3, config.seq_len):
|
|
|
|
| 800 |
def strip_latent_slots(seq, si):
|
| 801 |
return np.concatenate([seq[:3*si], seq[3*si + K:]])
|
| 802 |
|
| 803 |
+
# ---- Permutation-tolerant location diagnostics ----
|
| 804 |
+
# A cell's wave = the first stage at which its candidate set becomes
|
| 805 |
+
# a singleton, i.e. the propagation depth that determines it. Cells
|
| 806 |
+
# sharing a wave are order-interchangeable, so "did you name a cell
|
| 807 |
+
# from the earliest wave that is still unfilled" is the meaningful
|
| 808 |
+
# ordering signal; the exact index within the wave is arbitrary.
|
| 809 |
+
cov_b, dup_b, lcs_b, wav_b = [], [], [], []
|
| 810 |
+
for j in range(bs):
|
| 811 |
+
si = int(start_index[j].reshape(-1)[0])
|
| 812 |
+
pred = strip_latent_slots(cur_input_seq[j], si)
|
| 813 |
+
true = strip_latent_slots(input_seq[j], si)
|
| 814 |
+
emitted = [(int(pred[3 * k]), int(pred[3 * k + 1]))
|
| 815 |
+
for k in range(si, 81)]
|
| 816 |
+
truth = [(int(true[3 * k]), int(true[3 * k + 1]))
|
| 817 |
+
for k in range(si, 81)]
|
| 818 |
+
if not truth or not emitted:
|
| 819 |
+
continue
|
| 820 |
+
n_true = len(truth)
|
| 821 |
+
cov_b.append(len(set(emitted) & set(truth)) / n_true)
|
| 822 |
+
dup_b.append(1.0 - len(set(emitted)) / len(emitted))
|
| 823 |
+
# LCS is quadratic, so sample a few examples per batch.
|
| 824 |
+
if j < 32:
|
| 825 |
+
lcs_b.append(_lcs_len(emitted, truth) / n_true)
|
| 826 |
+
|
| 827 |
+
if cand_targets is None or K == 0:
|
| 828 |
+
continue
|
| 829 |
+
cids = np.array([r * 9 + c for r, c in truth], dtype=np.int64)
|
| 830 |
+
bits = cand_targets[j][:, cids] # (K, n)
|
| 831 |
+
singleton = (bits > 0) & ((bits & (bits - 1)) == 0)
|
| 832 |
+
w = np.where(singleton.any(axis=0), singleton.argmax(axis=0), K)
|
| 833 |
+
wav_b.append(
|
| 834 |
+
_wave_order_score(emitted, truth, w, K) / n_true)
|
| 835 |
+
|
| 836 |
+
if cov_b:
|
| 837 |
+
eval_metrics["loc_coverage"].append(float(np.mean(cov_b)))
|
| 838 |
+
eval_metrics["loc_dup"].append(float(np.mean(dup_b)))
|
| 839 |
+
if lcs_b:
|
| 840 |
+
eval_metrics["loc_lcs"].append(float(np.mean(lcs_b)))
|
| 841 |
+
if wav_b:
|
| 842 |
+
eval_metrics["loc_wave"].append(float(np.mean(wav_b)))
|
| 843 |
+
|
| 844 |
# ---- Print one concrete example answer the model generated ----
|
| 845 |
if eval_epoch == 0:
|
| 846 |
j = 0
|
|
|
|
| 854 |
n_tot += 1; n_ok += int(ok)
|
| 855 |
if len(shown) < 12:
|
| 856 |
shown.append(f"({r},{c})->{v}[true {tv}]{'ok' if ok else 'X'}")
|
| 857 |
+
if _verbose_eval():
|
| 858 |
+
print(f"EXAMPLE (level={int(levels[j])}, k={int(k_budget[j])}): "
|
| 859 |
+
f"model emitted {n_tot} (r,c)->v triples for the empty cells "
|
| 860 |
+
f"(format: (row,col)->value[true T]); first 12:", flush=True)
|
| 861 |
+
print(" ", " ".join(shown), flush=True)
|
| 862 |
+
print(f"EXAMPLE cells-correct={n_ok}/{n_tot} "
|
| 863 |
+
f"valid_full_grid={valid_solution(pred)}", flush=True)
|
| 864 |
|
| 865 |
# Instance arm: emitted digit next to the deepest stage's
|
| 866 |
# candidate set, so it is visible whether the model is sitting
|
|
|
|
| 875 |
if (bits >> d) & 1)
|
| 876 |
shown.append(f"(r{r},c{c})->{int(pred[3*t3+2])} "
|
| 877 |
f"in{{{cset}}}")
|
| 878 |
+
if _verbose_eval():
|
| 879 |
+
print(f"EXAMPLE emitted vs stage-{K} candidate set:",
|
| 880 |
+
" ".join(shown), flush=True)
|
| 881 |
|
| 882 |
# ---- Candidate-set (multi-value) prediction for this puzzle ----
|
| 883 |
# Show, at the last active latent slot, predicted vs target
|
|
|
|
| 897 |
cand_shown.append(f"(r{r},c{c}) pred{{{pset}}} true{{{tset}}}")
|
| 898 |
if len(cand_shown) >= 8:
|
| 899 |
break
|
| 900 |
+
if _verbose_eval():
|
| 901 |
+
print(f"EXAMPLE candidate-set @slot{kj} (pred vs true):",
|
| 902 |
+
" ".join(cand_shown), flush=True)
|
| 903 |
|
| 904 |
correct_eval_sudoku_puzzle = 0
|
| 905 |
|
|
|
|
| 917 |
per_level = {lvl: (level_ok[lvl] / level_tot[lvl] if level_tot[lvl] else -1.0)
|
| 918 |
for lvl in range(3, 9)}
|
| 919 |
eval_metrics["per_level_acc"] = per_level
|
| 920 |
+
if _verbose_eval():
|
| 921 |
+
print("PER-LEVEL cell acc:",
|
| 922 |
+
{lvl: (f"{v:.3f}" if v >= 0 else "n/a") for lvl, v in per_level.items()},
|
| 923 |
+
flush=True)
|
| 924 |
|
| 925 |
# Per-depth candidate-set accuracy, keyed by stage (slot j -> stage j+1) so
|
| 926 |
# the curriculum controller can index it directly by stage number.
|
|
|
|
| 935 |
per_stage_inset = {s + 1: (float(inset_ok[s] / inset_tot[s])
|
| 936 |
if inset_tot[s] else -1.0) for s in range(K)}
|
| 937 |
eval_metrics["per_stage_inset_acc"] = per_stage_inset
|
| 938 |
+
|
| 939 |
+
# Per-stage value-distribution metrics, keyed by stage to match the above.
|
| 940 |
+
# val_excess = CE(uniform-over-candidates || model) - log|S| >= 0 is the
|
| 941 |
+
# superposition score: 0 means the model spreads exactly uniformly over the
|
| 942 |
+
# stage's candidate set, and it rises if probability leaks outside the set
|
| 943 |
+
# or collapses onto one member of it.
|
| 944 |
+
def _per_stage(num, den):
|
| 945 |
+
return {s + 1: (float(num[s] / den[s]) if den[s] else -1.0)
|
| 946 |
+
for s in range(K)}
|
| 947 |
+
|
| 948 |
+
per_stage_vce = _per_stage(vce_sum, vcnt)
|
| 949 |
+
per_stage_vfloor = _per_stage(vfloor_sum, vcnt)
|
| 950 |
+
per_stage_vexcess = {
|
| 951 |
+
s: (per_stage_vce[s] - per_stage_vfloor[s]
|
| 952 |
+
if per_stage_vce[s] >= 0 else -1.0) for s in per_stage_vce}
|
| 953 |
+
eval_metrics["per_stage_val_ce"] = per_stage_vce
|
| 954 |
+
eval_metrics["per_stage_val_floor"] = per_stage_vfloor
|
| 955 |
+
eval_metrics["per_stage_val_excess"] = per_stage_vexcess
|
| 956 |
+
eval_metrics["per_stage_val_mass"] = _per_stage(vmass_sum, vcnt)
|
| 957 |
+
eval_metrics["per_stage_val_spread"] = _per_stage(vspread_sum, vspread_cnt)
|
| 958 |
+
# Superposition metrics on |S| >= 2 cells only. excess_multi is the single
|
| 959 |
+
# number to drive to 0: it equals log(1/mass_multi) + kl_multi, so it falls
|
| 960 |
+
# only when leakage outside the set AND non-uniformity inside it both fall.
|
| 961 |
+
eval_metrics["per_stage_val_excess_multi"] = _per_stage(
|
| 962 |
+
vexc_m_sum, vspread_cnt)
|
| 963 |
+
eval_metrics["per_stage_val_mass_multi"] = _per_stage(
|
| 964 |
+
vmass_m_sum, vspread_cnt)
|
| 965 |
+
eval_metrics["per_stage_val_kl_multi"] = _per_stage(vkl_m_sum, vspread_cnt)
|
| 966 |
+
# Entropy ceiling, three views of the same per-cell inequality:
|
| 967 |
+
# hbound fraction of |S|>=2 cells with H(p) <= log|S| <- gate on this
|
| 968 |
+
# hgap mean margin log|S| - H(p) in nats, <0 means violated on average
|
| 969 |
+
# hbound_puz fraction of (puzzle, stage) groups where EVERY such cell passes
|
| 970 |
+
# The cell fraction is the right gate: the puzzle view compounds (~50 cells,
|
| 971 |
+
# so 95% per cell leaves ~8% of puzzles clean) and the mean margin hides
|
| 972 |
+
# individual violations behind the cells that pass comfortably.
|
| 973 |
+
eval_metrics["per_stage_val_hbound"] = _per_stage(vhok_sum, vspread_cnt)
|
| 974 |
+
eval_metrics["per_stage_val_hgap"] = _per_stage(vhgap_sum, vspread_cnt)
|
| 975 |
+
eval_metrics["per_stage_val_hbound_puz"] = _per_stage(vhall_sum, vhgrp_sum)
|
| 976 |
+
# The single promotion criterion: CE(q||p) <= log|S| per cell, counted.
|
| 977 |
+
# ceq mean CE(q||p), to compare against floor H(q) and ceiling log|S|
|
| 978 |
+
# hq mean H(q), the best CE any model could achieve on this data
|
| 979 |
+
# ceq_ok fraction of |S|>=2 cells clearing the ceiling <- gate on this
|
| 980 |
+
# ceq_gap mean slack log|S| - CE(q||p); negative means worse than uniform
|
| 981 |
+
# ceq_puz fraction of puzzles where every such cell clears it
|
| 982 |
+
# This subsumes mass and spread: leak lowers p on real targets, and dropping
|
| 983 |
+
# a candidate the instances use sends -log p(d) up, so both are penalized by
|
| 984 |
+
# the one number. log|S| needs no tuning and recalibrates per stage.
|
| 985 |
+
eval_metrics["per_stage_val_ceq"] = _per_stage(vceq_sum, vceq_cnt)
|
| 986 |
+
eval_metrics["per_stage_val_hq"] = _per_stage(vhq_sum, vceq_cnt)
|
| 987 |
+
eval_metrics["per_stage_val_ceq_ok"] = _per_stage(vceq_ok, vceq_cnt)
|
| 988 |
+
eval_metrics["per_stage_val_ceq_gap"] = _per_stage(vceq_gap, vceq_cnt)
|
| 989 |
+
eval_metrics["per_stage_val_ceq_puz"] = _per_stage(vceq_all, vceq_grp)
|
| 990 |
+
# THE PROMOTION GATE, as a stage average over every |S|>=2 cell:
|
| 991 |
+
# ceq_pop <= logm_pop <=> ceq_margin >= 0
|
| 992 |
+
# This is the stage-level reading of "the value cross-entropy is below the
|
| 993 |
+
# uniform-candidate entropy". ceq_ok above is the stricter per-cell rate.
|
| 994 |
+
per_stage_ceq_pop = _per_stage(vceq_pop, vpop_cnt)
|
| 995 |
+
per_stage_logm_pop = _per_stage(vlogm_pop, vpop_cnt)
|
| 996 |
+
eval_metrics["per_stage_val_ceq_pop"] = per_stage_ceq_pop
|
| 997 |
+
eval_metrics["per_stage_val_hq_pop"] = _per_stage(vhq_pop, vpop_cnt)
|
| 998 |
+
eval_metrics["per_stage_val_logm_pop"] = per_stage_logm_pop
|
| 999 |
+
eval_metrics["per_stage_val_ceq_margin"] = {
|
| 1000 |
+
s: (per_stage_logm_pop[s] - per_stage_ceq_pop[s]
|
| 1001 |
+
if per_stage_ceq_pop[s] >= 0 else -99.0) for s in per_stage_ceq_pop}
|
| 1002 |
+
# Per-puzzle hinge: mean over puzzles of max(0, CE_i - log|S|_i). Zero iff no
|
| 1003 |
+
# puzzle is still above its own bar, so unlike ceq_margin it cannot be passed
|
| 1004 |
+
# by cross-puzzle cancellation. `hinge_floor` is the same statistic at p == q
|
| 1005 |
+
# and bounds how low `hinge` can ever go on this data.
|
| 1006 |
+
eval_metrics["per_stage_val_hinge"] = _per_stage(vhinge_sum, vhinge_cnt)
|
| 1007 |
+
eval_metrics["per_stage_val_hinge_floor"] = _per_stage(
|
| 1008 |
+
vhinge_floor, vhinge_cnt)
|
| 1009 |
+
# Train-matched readout: only the gate stage is populated, the rest read
|
| 1010 |
+
# -1 and the promotion logic falls back to the legacy key for those.
|
| 1011 |
+
eval_metrics["per_stage_val_hinge_inst"] = _per_stage(
|
| 1012 |
+
vhinge_sum_i, vhinge_cnt_i)
|
| 1013 |
+
eval_metrics["per_stage_val_hinge_floor_inst"] = _per_stage(
|
| 1014 |
+
vhinge_floor_i, vhinge_cnt_i)
|
| 1015 |
+
per_stage_ceq_pop_i = _per_stage(vceq_pop_i, vpop_cnt_i)
|
| 1016 |
+
per_stage_logm_pop_i = _per_stage(vlogm_pop_i, vpop_cnt_i)
|
| 1017 |
+
eval_metrics["per_stage_val_ceq_pop_inst"] = per_stage_ceq_pop_i
|
| 1018 |
+
eval_metrics["per_stage_val_hq_pop_inst"] = _per_stage(
|
| 1019 |
+
vhq_pop_i, vpop_cnt_i)
|
| 1020 |
+
eval_metrics["per_stage_val_ceq_margin_inst"] = {
|
| 1021 |
+
s: (per_stage_logm_pop_i[s] - per_stage_ceq_pop_i[s]
|
| 1022 |
+
if per_stage_ceq_pop_i[s] >= 0 else -99.0)
|
| 1023 |
+
for s in per_stage_ceq_pop_i}
|
| 1024 |
+
if _verbose_eval() and K > 0 and any(v >= 0 for v in per_stage_vce.values()):
|
| 1025 |
+
print("PER-STAGE val_excess (0 = uniform over candidate set):",
|
| 1026 |
+
{s: (f"{v:.3f}" if per_stage_vce[s] >= 0 else "n/a")
|
| 1027 |
+
for s, v in per_stage_vexcess.items()}, flush=True)
|
| 1028 |
+
|
| 1029 |
+
if _verbose_eval() and K > 0 and any(v >= 0 for v in per_stage_inset.values()):
|
| 1030 |
print("PER-STAGE in-set rate (emitted digit is a stage-s candidate):",
|
| 1031 |
{s: (f"{v:.3f}" if v >= 0 else "n/a")
|
| 1032 |
for s, v in per_stage_inset.items()}, flush=True)
|
|
|
|
| 1034 |
per_bin = {b: (bin_ok[b] / bin_tot[b] if bin_tot[b] else -1.0)
|
| 1035 |
for b in range(1, n_bins + 1)}
|
| 1036 |
eval_metrics["per_bin_acc"] = per_bin
|
| 1037 |
+
if _verbose_eval() and any(v >= 0 for v in per_bin.values()):
|
| 1038 |
print("PER-ROUND-BIN cell acc:",
|
| 1039 |
{b: (f"{v:.3f}" if v >= 0 else "n/a") for b, v in per_bin.items()},
|
| 1040 |
flush=True)
|
| 1041 |
+
if _verbose_eval() and K > 0:
|
| 1042 |
print("PER-DEPTH cand-set acc:",
|
| 1043 |
{s: (f"{v:.3f}" if v >= 0 else "n/a") for s, v in per_slot.items()},
|
| 1044 |
flush=True)
|