feat(spatial): 加 declared 输入模式,训练时就不给泄漏通道,再谈充分性
This commit is contained in:
1 parent
efe1ee6801
commit
7e73e9286a
5 files changed
+75
-13
No files matched your search
@@ -32,7 +32,8 @@
|
|||||||
"test_families": [
|
"test_families": [
|
||||||
"area.sup2h",
|
"area.sup2h",
|
||||||
"dof.c6h"
|
"dof.c6h"
|
||||||
]
|
],
|
||||||
|
"availability": "leaked"
|
||||||
},
|
},
|
||||||
"optim": {
|
"optim": {
|
||||||
"lr": 0.003,
|
"lr": 0.003,
|
||||||
|
|||||||
@@ -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"
|
||||||
|
}
|
||||||
+11
-5
@@ -124,7 +124,7 @@ def edge_features(sc: Scenario, ed, removed: bool, dangling: bool = False) -> li
|
|||||||
return f
|
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.
|
"""The observation's own admission of what it is missing.
|
||||||
|
|
||||||
``hidden_layers`` and ``hidden_faces`` are in the digest but were never in
|
``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 (
|
f[base + 5] = 1.0 if (scope.get("layers") or []) and (
|
||||||
tot_parts > sum(rendered.values()) or tot_rel > sum(rel_r.values())
|
tot_parts > sum(rendered.values()) or tot_rel > sum(rel_r.values())
|
||||||
or missing_layers) else 0.0
|
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
|
return f
|
||||||
|
|
||||||
|
|
||||||
def collate(batch, max_entities: int = 32):
|
def collate(batch, max_entities: int = 32, availability: str = "leaked"):
|
||||||
B = len(batch)
|
B = len(batch)
|
||||||
N = max(1, max(len(sc.obs.entities) for sc in 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:
|
if N > max_entities:
|
||||||
raise ValueError(f"scene needs {N} entity slots > max_entities {max_entities}; "
|
raise ValueError(f"scene needs {N} entity slots > max_entities {max_entities}; "
|
||||||
"bucket it instead of truncating")
|
"bucket it instead of truncating")
|
||||||
@@ -200,7 +206,7 @@ def collate(batch, max_entities: int = 32):
|
|||||||
|
|
||||||
for i, sc in enumerate(batch):
|
for i, sc in enumerate(batch):
|
||||||
ids = {e.eid: j for j, e in enumerate(sc.obs.entities)}
|
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):
|
for j, e in enumerate(sc.obs.entities):
|
||||||
feat[i, j] = torch.tensor(entity_features(sc, e))
|
feat[i, j] = torch.tensor(entity_features(sc, e))
|
||||||
pad_mask[i, j] = False
|
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
|
# 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,
|
# slot via the sentinel endpoint ``N``; their far end is never an entity,
|
||||||
# so they can never be mistaken for a traversable edge
|
# 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
|
k = len(sc.obs.edges) + j
|
||||||
edge_index[i, k, 0] = ids.get(dl.a, 0)
|
edge_index[i, k, 0] = ids.get(dl.a, 0)
|
||||||
edge_index[i, k, 1] = N
|
edge_index[i, k, 1] = N
|
||||||
|
|||||||
+4
-3
@@ -33,10 +33,10 @@ ANSWERS = ("true", "false", "unknown")
|
|||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def family_row(model, family: str, seed: int, n: int, max_entities: int = 32,
|
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)]
|
batch = [generator.make(family, seed=seed, index=i) for i in range(n)]
|
||||||
device = next(model.parameters()).device
|
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()}
|
t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()}
|
||||||
if ablate:
|
if ablate:
|
||||||
# a mechanism that survives its own removal was never used. The dangling
|
# 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))
|
print("-" * len(head))
|
||||||
for fam in generator.FAMILIES:
|
for fam in generator.FAMILIES:
|
||||||
ndang = sum(len(generator.make(fam, cfg["seed"], i).obs.dangling) for i in range(8)) / 8
|
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} "
|
print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} "
|
||||||
f"{ndang:4.1f} "
|
f"{ndang:4.1f} "
|
||||||
f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} "
|
f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} "
|
||||||
|
|||||||
+8
-4
@@ -70,11 +70,12 @@ def _ece(probs, correct, n_bin: int = 5) -> float:
|
|||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
@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()
|
model.eval()
|
||||||
batch = make_batch(families, seed + 1, 0, n)[:n]
|
batch = make_batch(families, seed + 1, 0, n)[:n]
|
||||||
device = next(model.parameters()).device
|
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()}
|
tensors = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in tensors.items()}
|
||||||
_, losses, out = batch_loss(model, tensors)
|
_, losses, out = batch_loss(model, tensors)
|
||||||
pred = out["answer"].argmax(-1).tolist()
|
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,
|
batch = make_batch(config["data"]["train_families"], config["seed"], step,
|
||||||
config["optim"]["batch"])
|
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()}
|
tensors = {k: v.to(device) if torch.is_tensor(v) else v for k, v in tensors.items()}
|
||||||
loss, parts, _ = batch_loss(model, tensors)
|
loss, parts, _ = batch_loss(model, tensors)
|
||||||
opt.zero_grad(set_to_none=True)
|
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})")
|
f"(ans {parts['answer']:.3f} chg {parts['change']:.3f} ev {parts['evidence']:.3f})")
|
||||||
save(ckpt, model, opt, total_steps, config)
|
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:
|
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"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}")
|
print(f"done in {time.time() - t0:.1f}s device={device}")
|
||||||
|
|||||||
Reference in new issue
Block a user