Implement typed evidence latent training and benchmarks
CI / test (push) Failing after 6s

This commit is contained in:
2026-10-01 22:44:07 +08:00
parent 1d798cb73f
commit b3774e783c
22 changed files with 747 additions and 119 deletions
+4 -2
View File
@@ -23,7 +23,10 @@ def _write_split(
path = root / f"{name}.jsonl"
with path.open("w", encoding="utf-8") as handle:
for scene_number in range(start, start + size):
record = add_rule(generate_scene(scene_number, seed), seed, held_out=held_out)
scene = generate_scene(
scene_number, seed, held_out_composition=held_out
)
record = add_rule(scene, seed, held_out=held_out)
relative_image = Path("images") / f"{record['scene_id']}.png"
render_scene(record, root / relative_image, image_size=image_size)
record["image"] = str(relative_image)
@@ -67,4 +70,3 @@ def main() -> None:
if __name__ == "__main__":
main()
+35 -9
View File
@@ -9,15 +9,38 @@ import torch
from PIL import Image
from torch.utils.data import Dataset
from data.schema import OBJECT_TO_ID, PREDICATE_TO_ID, SUBJECT_TO_ID, Fact
from data.schema import (
FACT_TYPE,
OBJECT_TO_ID,
PREDICATE_TO_ID,
RULE_TYPE,
SUBJECT_TO_ID,
Fact,
Rule,
)
def fact_to_ids(value: dict[str, str]) -> tuple[int, int, int]:
def fact_to_ids(value: dict[str, str]) -> tuple[int, int, int, int, int, int]:
fact = Fact.from_dict(value)
return (
FACT_TYPE,
SUBJECT_TO_ID[fact.subject],
PREDICATE_TO_ID[fact.predicate],
OBJECT_TO_ID[fact.object],
-1,
-1,
)
def rule_to_ids(value: dict[str, str]) -> tuple[int, int, int, int, int, int]:
rule = Rule.from_dict(value)
return (
RULE_TYPE,
SUBJECT_TO_ID[rule.variable],
PREDICATE_TO_ID[rule.antecedent_predicate],
OBJECT_TO_ID[rule.antecedent_object],
PREDICATE_TO_ID[rule.consequent_predicate],
OBJECT_TO_ID[rule.consequent_object],
)
@@ -25,7 +48,9 @@ class EvidenceDataset(Dataset):
def __init__(self, manifest: Path, image_size: int = 224):
self.root = manifest.parent
self.image_size = image_size
self.records = [json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines()]
self.records = [
json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines()
]
def __len__(self) -> int:
return len(self.records)
@@ -38,11 +63,13 @@ class EvidenceDataset(Dataset):
return {
"image": image_tensor,
"rules_text": record["rules_text"],
"visual_facts": torch.tensor(
"visual_targets": torch.tensor(
[fact_to_ids(value) for value in record["visual_facts"]], dtype=torch.long
),
"text_facts": torch.tensor(
[fact_to_ids(value) for value in record["text_facts"]], dtype=torch.long
"text_targets": torch.tensor(
[fact_to_ids(value) for value in record["text_facts"]]
+ [rule_to_ids(value) for value in record["text_rules"]],
dtype=torch.long,
),
"scene_id": record["scene_id"],
}
@@ -52,8 +79,7 @@ def collate_evidence(batch: list[dict[str, Any]]) -> dict[str, Any]:
return {
"images": torch.stack([item["image"] for item in batch]),
"rules_text": [item["rules_text"] for item in batch],
"visual_facts": [item["visual_facts"] for item in batch],
"text_facts": [item["text_facts"] for item in batch],
"visual_targets": [item["visual_targets"] for item in batch],
"text_targets": [item["text_targets"] for item in batch],
"scene_id": [item["scene_id"] for item in batch],
}
+9 -5
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import random
from typing import Any
from data.schema import CLASSES, Fact
from data.schema import CLASSES, Fact, Rule
def add_rule(record: dict[str, Any], seed: int, held_out: bool = False) -> dict[str, Any]:
@@ -13,16 +13,20 @@ def add_rule(record: dict[str, Any], seed: int, held_out: bool = False) -> dict[
color_index = ("red", "blue", "green", "yellow").index(color)
class_index = (color_index + (1 if held_out else 0)) % len(CLASSES)
class_name = CLASSES[class_index]
rule = Fact(color, "implies_class", class_name)
text_fact = Fact(target["object_id"], "color", color)
rule = Rule("var_x", "color", color, "class", class_name)
result = dict(record)
result.update(
{
"rules_text": f"Every {color} object belongs to class {class_name}.",
"text_facts": [rule.to_dict()],
"rules_text": (
f"{target['object_id']} is {color}. "
f"Every {color} object belongs to class {class_name}."
),
"text_facts": [text_fact.to_dict()],
"text_rules": [rule.to_dict()],
"question": f"Which object belongs to class {class_name}?",
"answer": target["object_id"],
"combination": f"{color}->{class_name}",
}
)
return result
+20 -3
View File
@@ -5,6 +5,13 @@ from typing import Any
from data.schema import COLORS, OBJECT_IDS, RELATIONS, SHAPES, Fact, SceneObject
HELD_OUT_SHAPES = {
"red": "triangle",
"blue": "square",
"green": "star",
"yellow": "circle",
}
def _relation(first: SceneObject, second: SceneObject, rng: random.Random) -> Fact:
relation = rng.choice(RELATIONS)
@@ -23,12 +30,23 @@ def _relation(first: SceneObject, second: SceneObject, rng: random.Random) -> Fa
return Fact(first.object_id, relation, second.object_id), first, second
def generate_scene(scene_id: int, seed: int, num_objects: int = 2) -> dict[str, Any]:
def generate_scene(
scene_id: int, seed: int, num_objects: int = 2, held_out_composition: bool = False
) -> dict[str, Any]:
if num_objects != 2:
raise ValueError("The stage-one MVP currently supports exactly two objects.")
rng = random.Random((seed * 1_000_003) + scene_id)
colors = rng.sample(COLORS, k=num_objects)
shapes = rng.sample(SHAPES, k=num_objects)
if held_out_composition:
first_shape = HELD_OUT_SHAPES[colors[0]]
second_choices = [shape for shape in SHAPES if shape != first_shape]
shapes = [first_shape, rng.choice(second_choices)]
else:
shapes = []
for color in colors:
choices = [shape for shape in SHAPES if shape != HELD_OUT_SHAPES[color]]
choices = [shape for shape in choices if shape not in shapes]
shapes.append(rng.choice(choices))
objects = [
SceneObject(OBJECT_IDS[index], colors[index], shapes[index], 0, 0)
for index in range(num_objects)
@@ -49,4 +67,3 @@ def generate_scene(scene_id: int, seed: int, num_objects: int = 2) -> dict[str,
"objects": [item.to_dict() for item in objects],
"visual_facts": [fact.to_dict() for fact in facts],
}
+24 -3
View File
@@ -8,9 +8,15 @@ SHAPES = ("circle", "square", "triangle", "star")
RELATIONS = ("left_of", "right_of", "above", "below")
CLASSES = ("alpha", "beta", "gamma", "delta")
OBJECT_IDS = ("obj1", "obj2", "obj3")
VARIABLES = ("var_x",)
PREDICATES = ("color", "shape", "left_of", "right_of", "above", "below", "implies_class")
ENTITIES = OBJECT_IDS + COLORS + SHAPES + CLASSES
PREDICATES = ("color", "shape", "left_of", "right_of", "above", "below", "class")
ENTITIES = OBJECT_IDS + COLORS + SHAPES + CLASSES + VARIABLES
NULL_TYPE = 0
FACT_TYPE = 1
RULE_TYPE = 2
NUM_STATE_TYPES = 3
SUBJECT_TO_ID = {value: index for index, value in enumerate(ENTITIES)}
PREDICATE_TO_ID = {value: index for index, value in enumerate(PREDICATES)}
@@ -31,6 +37,22 @@ class Fact:
return cls(**value)
@dataclass(frozen=True)
class Rule:
variable: str
antecedent_predicate: str
antecedent_object: str
consequent_predicate: str
consequent_object: str
def to_dict(self) -> dict[str, str]:
return asdict(self)
@classmethod
def from_dict(cls, value: dict[str, str]) -> "Rule":
return cls(**value)
@dataclass(frozen=True)
class SceneObject:
object_id: str
@@ -41,4 +63,3 @@ class SceneObject:
def to_dict(self) -> dict[str, Any]:
return asdict(self)