diff --git a/spatial/configs/dangling.json b/spatial/configs/dangling.json index 5304115..3846614 100644 --- a/spatial/configs/dangling.json +++ b/spatial/configs/dangling.json @@ -32,7 +32,8 @@ "test_families": [ "area.sup2h", "dof.c6h" - ] + ], + "availability": "leaked" }, "optim": { "lr": 0.003, diff --git a/spatial/configs/declared.json b/spatial/configs/declared.json new file mode 100644 index 0000000..0b10571 --- /dev/null +++ b/spatial/configs/declared.json @@ -0,0 +1,50 @@ +{ + "seed": 0, + "model": { + "d": 192, + "n_layer": 4, + "n_head": 6, + "dropout": 0.1, + "max_entities": 32, + "rounds": 2, + "n_evidence": 4 + }, + "data": { + "train_families": [ + "cond.p1", + "cond.p3", + "cond.p3h", + "cond.p1h", + "area.sup2", + "area.sup3", + "area.sup3h", + "area.sup2d", + "area.free", + "dof.c6", + "dof.c6r", + "dof.c6d", + "dof.set" + ], + "val_families": [ + "area.sup2h", + "dof.c6h" + ], + "test_families": [ + "area.sup2h", + "dof.c6h" + ], + "availability": "declared" + }, + "optim": { + "lr": 0.003, + "weight_decay": 0.01, + "steps": 4800, + "batch": 32, + "log_every": 400, + "warmup": 300 + }, + "eval": { + "n": 192 + }, + "out_dir": "out_spatial/declared" +} diff --git a/spatial/data.py b/spatial/data.py index dda8334..6b17706 100644 --- a/spatial/data.py +++ b/spatial/data.py @@ -124,7 +124,7 @@ def edge_features(sc: Scenario, ed, removed: bool, dangling: bool = False) -> li return f -def scene_features(sc: Scenario) -> list: +def scene_features(sc: Scenario, availability: str = "leaked") -> list: """The observation's own admission of what it is missing. ``hidden_layers`` and ``hidden_faces`` are in the digest but were never in @@ -170,13 +170,19 @@ def scene_features(sc: Scenario) -> list: f[base + 5] = 1.0 if (scope.get("layers") or []) and ( tot_parts > sum(rendered.values()) or tot_rel > sum(rel_r.values()) or missing_layers) else 0.0 + if availability != "leaked": + # training-time, not eval-time: the model must never see a channel it + # could not be given at inference. Zeroing at eval only measures whether + # a channel was necessary, never whether the rest is sufficient. + f[0:base] = [0.0] * base return f -def collate(batch, max_entities: int = 32): +def collate(batch, max_entities: int = 32, availability: str = "leaked"): B = len(batch) N = max(1, max(len(sc.obs.entities) for sc in batch)) - E = max(1, max(len(sc.obs.edges) + len(sc.obs.dangling) for sc in batch)) + E = max(1, max(len(sc.obs.edges) + (len(sc.obs.dangling) if availability == "leaked" + else 0) for sc in batch)) if N > max_entities: raise ValueError(f"scene needs {N} entity slots > max_entities {max_entities}; " "bucket it instead of truncating") @@ -200,7 +206,7 @@ def collate(batch, max_entities: int = 32): for i, sc in enumerate(batch): ids = {e.eid: j for j, e in enumerate(sc.obs.entities)} - scene[i] = torch.tensor(scene_features(sc)) + scene[i] = torch.tensor(scene_features(sc, availability)) for j, e in enumerate(sc.obs.entities): feat[i, j] = torch.tensor(entity_features(sc, e)) pad_mask[i, j] = False @@ -218,7 +224,7 @@ def collate(batch, max_entities: int = 32): # dangling relations go after the real ones and point at the unknown # slot via the sentinel endpoint ``N``; their far end is never an entity, # so they can never be mistaken for a traversable edge - for j, dl in enumerate(sc.obs.dangling): + for j, dl in enumerate(sc.obs.dangling if availability == "leaked" else ()): k = len(sc.obs.edges) + j edge_index[i, k, 0] = ids.get(dl.a, 0) edge_index[i, k, 1] = N diff --git a/spatial/report.py b/spatial/report.py index eea549b..3abaf2d 100644 --- a/spatial/report.py +++ b/spatial/report.py @@ -33,10 +33,10 @@ ANSWERS = ("true", "false", "unknown") @torch.no_grad() def family_row(model, family: str, seed: int, n: int, max_entities: int = 32, - ablate: str = None) -> dict: + ablate: str = None, availability: str = "leaked") -> dict: batch = [generator.make(family, seed=seed, index=i) for i in range(n)] device = next(model.parameters()).device - t = collate(batch, max_entities) + t = collate(batch, max_entities, availability) t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()} if ablate: # a mechanism that survives its own removal was never used. The dangling @@ -110,7 +110,8 @@ def report(config_path: str, n: int = 128, ablate: str = None, seed: int = None) print("-" * len(head)) for fam in generator.FAMILIES: ndang = sum(len(generator.make(fam, cfg["seed"], i).obs.dangling) for i in range(8)) / 8 - r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"], ablate) + r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"], ablate, + cfg["data"].get("availability", "leaked")) print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} " f"{ndang:4.1f} " f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} " diff --git a/spatial/train.py b/spatial/train.py index 0ed351d..017a3a8 100644 --- a/spatial/train.py +++ b/spatial/train.py @@ -70,11 +70,12 @@ def _ece(probs, correct, n_bin: int = 5) -> float: @torch.no_grad() -def evaluate(model, families, seed: int, n: int, max_entities: int = 32) -> dict: +def evaluate(model, families, seed: int, n: int, max_entities: int = 32, + availability: str = "leaked") -> dict: model.eval() batch = make_batch(families, seed + 1, 0, n)[:n] device = next(model.parameters()).device - tensors = collate(batch, max_entities) + tensors = collate(batch, max_entities, availability) tensors = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in tensors.items()} _, losses, out = batch_loss(model, tensors) pred = out["answer"].argmax(-1).tolist() @@ -202,7 +203,8 @@ def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = T batch = make_batch(config["data"]["train_families"], config["seed"], step, config["optim"]["batch"]) - tensors = collate(batch, config["model"]["max_entities"]) + tensors = collate(batch, config["model"]["max_entities"], + config["data"].get("availability", "leaked")) tensors = {k: v.to(device) if torch.is_tensor(v) else v for k, v in tensors.items()} loss, parts, _ = batch_loss(model, tensors) opt.zero_grad(set_to_none=True) @@ -214,7 +216,9 @@ def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = T f"(ans {parts['answer']:.3f} chg {parts['change']:.3f} ev {parts['evidence']:.3f})") save(ckpt, model, opt, total_steps, config) - metrics = evaluate(model, config["data"]["val_families"], config["seed"], config["eval"]["n"]) + metrics = evaluate(model, config["data"]["val_families"], config["seed"], config["eval"]["n"], + config["model"]["max_entities"], + config["data"].get("availability", "leaked")) if verbose: print(f"val {json.dumps({k: (round(v, 3) if isinstance(v, float) else v) for k, v in metrics.items() if k != 'loss'})}") print(f"done in {time.time() - t0:.1f}s device={device}")