File size: 13,867 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
"""Deterministic executor for official CLEVR functional programs."""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from typing import Any

from ..dsl.ast import Arg, AstNode, Program
from ..sources.base import World
from .base import (
    AnswerValue,
    ExecutionResult,
    ExecutionStatus,
    ExecutorError,
    _InvalidReferent,
    _MissingInformation,
    _Trace,
    literal_value,
    serialize_answer,
)

NAME = "clevr_executor"
VERSION = "clevr_dsl_v1/1"
_ATTRIBUTES = frozenset({"color", "material", "shape", "size"})
_RELATIONS = frozenset({"left", "right", "front", "behind"})


class ClevrExecutor:
    """Evaluate a CLEVR AST over a normalized ``clevr_world_v1`` scene."""

    name = NAME
    version = VERSION

    def execute(self, program: Program, *, world: World) -> ExecutionResult:
        trace = _Trace()
        referent_cardinality: int | None = None
        status: ExecutionStatus
        try:
            if program.dsl != "clevr_dsl_v1" or program.compile_status != "compiled":
                raise ExecutorError("executor requires a compiled clevr_dsl_v1 program")
            if world.get("world_schema") != "clevr_world_v1":
                raise ExecutorError(
                    f"clevr executor cannot read world_schema {world.get('world_schema')!r}"
                )
            referent_cardinality = self._check_referent(program, world, trace)
            value = self._eval(program.program, world, trace)
            answer = self._project_answer(program.program, value)
            _steps, dependencies, trace_hash = trace.finish()
            return ExecutionResult(
                status="UNIQUE",
                answer_value=answer,
                answer_canonical=serialize_answer(
                    answer,
                    return_type=program.program.return_type,
                ),
                dependency_node_ids=dependencies,
                referent_cardinality=referent_cardinality,
                trace_sha256=trace_hash,
                executor_name=self.name,
                executor_version=self.version,
            )
        except _MissingInformation:
            status = "MISSING_INFORMATION"
        except _InvalidReferent:
            status = "INVALID_REFERENT"
        except ExecutorError:
            status = "ERROR"
        _steps, dependencies, trace_hash = trace.finish()
        return ExecutionResult(
            status=status,
            answer_value=None,
            answer_canonical=None,
            dependency_node_ids=dependencies,
            referent_cardinality=(
                referent_cardinality
                if referent_cardinality is not None
                else self._safe_referent_cardinality(program, world)
            ),
            trace_sha256=trace_hash,
            executor_name=self.name,
            executor_version=self.version,
        )

    def execute_selector(self, selector: AstNode, *, world: World) -> tuple[str, ...]:
        """Resolve an object/object-set selector without applying ``UNIQUE``."""

        trace = _Trace()
        if selector.op == "UNIQUE":
            if len(selector.args) != 1 or not isinstance(selector.args[0], AstNode):
                raise ExecutorError("UNIQUE selector is malformed")
            value = self._eval(selector.args[0], world, trace)
        else:
            value = self._eval(selector, world, trace)
        if isinstance(value, Mapping):
            node_id = value.get("id")
            return (str(node_id),) if node_id else ()
        if isinstance(value, tuple):
            return tuple(
                str(item["id"]) for item in value if isinstance(item, Mapping) and item.get("id")
            )
        raise ExecutorError(f"selector {selector.op!r} did not produce objects")

    def _check_referent(self, program: Program, world: World, trace: _Trace) -> int | None:
        selector = program.referent_selector
        required = program.required_referent_cardinality
        if selector is None:
            return None
        refs = self.execute_selector(selector, world=world)
        trace.record("REFERENT", refs, len(refs))
        if required is not None and len(refs) != required:
            raise _InvalidReferent(
                f"scalar referent cardinality {len(refs)} != required {required}"
            )
        return len(refs)

    def _safe_referent_cardinality(self, program: Program, world: World) -> int | None:
        if program.referent_selector is None:
            return None
        try:
            return len(self.execute_selector(program.referent_selector, world=world))
        except (ExecutorError, _MissingInformation, _InvalidReferent):
            return None

    def _eval(self, node: Arg, world: World, trace: _Trace) -> Any:
        if not isinstance(node, AstNode):
            raise ExecutorError(f"expected AST node, got {type(node).__name__}")
        op = node.op
        if op == "LITERAL":
            return literal_value(node)
        if op == "SCENE":
            objects = _objects(world)
            trace.record("SCENE", (), len(objects))
            return objects
        if op.startswith("FILTER_"):
            return self._filter(op.removeprefix("FILTER_").lower(), node, world, trace)
        if op == "UNIQUE":
            unique_values = _object_set(self._eval_arg(node, 0, world, trace), op)
            trace.record(op, unique_values, len(unique_values))
            if len(unique_values) != 1:
                raise _InvalidReferent(f"UNIQUE received {len(unique_values)} objects")
            return unique_values[0]
        if op == "RELATE":
            source = _object(self._eval_arg(node, 0, world, trace), op)
            relation = _string(self._eval_arg(node, 1, world, trace), op)
            related_values = _related(world, str(source["id"]), relation)
            trace.record(op, (source, *related_values), len(related_values))
            return related_values
        if op.startswith("SAME_"):
            attribute = op.removeprefix("SAME_").lower()
            source = _object(self._eval_arg(node, 0, world, trace), op)
            target = _attribute(source, attribute)
            same_values: list[Mapping[str, Any]] = []
            for candidate in _objects(world):
                if candidate.get("id") == source.get("id"):
                    continue
                if _attribute(candidate, attribute) == target:
                    same_values.append(candidate)
            same_result = _ordered(same_values)
            trace.record(op, (source, *same_result), len(same_result))
            return same_result
        if op in {"UNION", "INTERSECT"}:
            left = _object_set(self._eval_arg(node, 0, world, trace), op)
            right = _object_set(self._eval_arg(node, 1, world, trace), op)
            left_by_id = {str(item["id"]): item for item in left}
            right_by_id = {str(item["id"]): item for item in right}
            ids = (
                set(left_by_id).union(right_by_id)
                if op == "UNION"
                else set(left_by_id).intersection(right_by_id)
            )
            set_result = tuple((left_by_id | right_by_id)[node_id] for node_id in sorted(ids))
            trace.record(op, set_result, len(set_result))
            return set_result
        if op == "COUNT":
            count_values = _object_set(self._eval_arg(node, 0, world, trace), op)
            trace.record(op, count_values, len(count_values))
            return len(count_values)
        if op == "EXIST":
            exist_values = _object_set(self._eval_arg(node, 0, world, trace), op)
            exists = bool(exist_values)
            trace.record(op, exist_values, exists)
            return exists
        if op.startswith("QUERY_"):
            attribute = op.removeprefix("QUERY_").lower()
            obj = _object(self._eval_arg(node, 0, world, trace), op)
            value = _attribute(obj, attribute)
            trace.record(op, obj, value)
            return value
        if op.startswith("EQUAL_"):
            left = self._eval_arg(node, 0, world, trace)
            right = self._eval_arg(node, 1, world, trace)
            comparison = _comparable(left) == _comparable(right)
            trace.record(op, (), comparison)
            return comparison
        if op in {"LESS_THAN", "GREATER_THAN"}:
            left_integer = _integer(self._eval_arg(node, 0, world, trace), op)
            right_integer = _integer(self._eval_arg(node, 1, world, trace), op)
            comparison = (
                left_integer < right_integer if op == "LESS_THAN" else left_integer > right_integer
            )
            trace.record(op, (), comparison)
            return comparison
        raise ExecutorError(f"unsupported CLEVR op {op!r}")

    def _eval_arg(
        self,
        node: AstNode,
        position: int,
        world: World,
        trace: _Trace,
    ) -> Any:
        try:
            arg = node.args[position]
        except IndexError as exc:
            raise ExecutorError(f"{node.op} has no operand {position}") from exc
        if not isinstance(arg, AstNode):
            raise ExecutorError(f"{node.op} operand {position} is not an AST node")
        return self._eval(arg, world, trace)

    def _filter(
        self,
        attribute: str,
        node: AstNode,
        world: World,
        trace: _Trace,
    ) -> tuple[Mapping[str, Any], ...]:
        values = _object_set(self._eval_arg(node, 0, world, trace), node.op)
        wanted = _string(self._eval_arg(node, 1, world, trace), node.op)
        selected = tuple(item for item in values if _attribute(item, attribute) == wanted)
        trace.record(node.op, selected, len(selected))
        return selected

    def _project_answer(self, root: AstNode, value: Any) -> AnswerValue:
        if root.return_type == "integer":
            return _integer(value, root.op)
        if root.return_type == "boolean":
            return bool(value)
        if root.return_type == "string":
            return _string(value, root.op)
        raise ExecutorError(
            f"CLEVR root {root.op!r} has non-answer return type {root.return_type!r}"
        )


def _objects(world: World) -> tuple[Mapping[str, Any], ...]:
    raw = world.get("objects")
    if not isinstance(raw, list):
        raise ExecutorError("CLEVR world objects is not an array")
    values: list[Mapping[str, Any]] = []
    seen: set[str] = set()
    for item in raw:
        if not isinstance(item, Mapping) or not item.get("id"):
            raise ExecutorError("CLEVR world contains an object without an id")
        node_id = str(item["id"])
        if node_id in seen:
            raise ExecutorError(f"CLEVR world has duplicate object id {node_id!r}")
        seen.add(node_id)
        values.append(item)
    return _ordered(values)


def _ordered(values: Sequence[Mapping[str, Any]]) -> tuple[Mapping[str, Any], ...]:
    return tuple(sorted(values, key=lambda item: str(item.get("id", ""))))


def _object_set(value: Any, op: str) -> tuple[Mapping[str, Any], ...]:
    if not isinstance(value, tuple) or any(not isinstance(item, Mapping) for item in value):
        raise ExecutorError(f"{op} expected an object set")
    return _ordered(value)


def _object(value: Any, op: str) -> Mapping[str, Any]:
    if not isinstance(value, Mapping) or not value.get("id"):
        raise ExecutorError(f"{op} expected one object")
    return value


def _attribute(obj: Mapping[str, Any], attribute: str) -> str:
    if attribute not in _ATTRIBUTES:
        raise ExecutorError(f"unknown CLEVR attribute {attribute!r}")
    value = obj.get(attribute)
    if value is None:
        raise _MissingInformation(f"object {obj.get('id')} {attribute} is hidden")
    if not isinstance(value, str) or not value:
        raise ExecutorError(f"object {obj.get('id')} has invalid {attribute}")
    return value


def _related(
    world: World,
    source_id: str,
    relation: str,
) -> tuple[Mapping[str, Any], ...]:
    if relation not in _RELATIONS:
        raise ExecutorError(f"unknown CLEVR relation {relation!r}")
    relationships = world.get("relationships")
    if not isinstance(relationships, Mapping):
        raise ExecutorError("CLEVR relationships is not an object")
    relation_map = relationships.get(relation)
    if not isinstance(relation_map, Mapping):
        raise ExecutorError(f"CLEVR relationship {relation!r} is missing")
    raw_targets = relation_map.get(source_id, [])
    if not isinstance(raw_targets, list):
        raise ExecutorError(f"CLEVR relationship {relation!r}/{source_id!r} is malformed")
    by_id = {str(item["id"]): item for item in _objects(world)}
    targets: list[Mapping[str, Any]] = []
    for node_id in raw_targets:
        target = by_id.get(str(node_id))
        if target is None:
            raise ExecutorError(
                f"CLEVR relationship {relation!r} references absent object {node_id!r}"
            )
        targets.append(target)
    return _ordered(targets)


def _string(value: Any, op: str) -> str:
    if not isinstance(value, str):
        raise ExecutorError(f"{op} expected a string, got {type(value).__name__}")
    return value


def _integer(value: Any, op: str) -> int:
    if isinstance(value, bool) or not isinstance(value, int):
        raise ExecutorError(f"{op} expected an integer, got {type(value).__name__}")
    return int(value)


def _comparable(value: Any) -> Any:
    if isinstance(value, Mapping):
        node_id = value.get("id")
        if not node_id:
            raise ExecutorError("object comparison received an object without an id")
        return ("object", str(node_id))
    if isinstance(value, (str, int, bool)):
        return value
    raise ExecutorError(f"value {value!r} is not comparable")


__all__ = ["ClevrExecutor"]