File size: 8,785 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
"""Typed compiler for CLEVR's source-native functional programs.

Official CLEVR questions contain a dependency-indexed program whose nodes have
``inputs``, ``function`` and ``value_inputs`` fields.  The compiler below
translates that DAG into the project's immutable :class:`AstNode` tree without
guessing or calling a model.  Only the released CLEVR function vocabulary is
accepted; malformed arity, forward references, and unknown functions produce an
``unsupported`` program with a deterministic reason code.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from dataclasses import dataclass, replace
from typing import Any

from ..ingest.base import NormalizedItem
from ..sources.base import World
from .ast import AstNode, Dsl, Program, ProgramError, lit
from .canonicalize import canonical_program_sha256
from .typecheck import OpSignature, typecheck

DSL: Dsl = "clevr_dsl_v1"


@dataclass(frozen=True)
class _NativeSignature:
    inputs: tuple[str, ...]
    return_type: str
    value_input: str | None = None


_NATIVE_SIGNATURES: dict[str, _NativeSignature] = {
    "scene": _NativeSignature((), "object_set"),
    "filter_color": _NativeSignature(("object_set",), "object_set", "string"),
    "filter_material": _NativeSignature(("object_set",), "object_set", "string"),
    "filter_shape": _NativeSignature(("object_set",), "object_set", "string"),
    "filter_size": _NativeSignature(("object_set",), "object_set", "string"),
    "unique": _NativeSignature(("object_set",), "object"),
    "relate": _NativeSignature(("object",), "object_set", "string"),
    "same_color": _NativeSignature(("object",), "object_set"),
    "same_material": _NativeSignature(("object",), "object_set"),
    "same_shape": _NativeSignature(("object",), "object_set"),
    "same_size": _NativeSignature(("object",), "object_set"),
    "union": _NativeSignature(("object_set", "object_set"), "object_set"),
    "intersect": _NativeSignature(("object_set", "object_set"), "object_set"),
    "count": _NativeSignature(("object_set",), "integer"),
    "exist": _NativeSignature(("object_set",), "boolean"),
    "query_color": _NativeSignature(("object",), "string"),
    "query_material": _NativeSignature(("object",), "string"),
    "query_shape": _NativeSignature(("object",), "string"),
    "query_size": _NativeSignature(("object",), "string"),
    "equal_color": _NativeSignature(("string", "string"), "boolean"),
    "equal_material": _NativeSignature(("string", "string"), "boolean"),
    "equal_shape": _NativeSignature(("string", "string"), "boolean"),
    "equal_size": _NativeSignature(("string", "string"), "boolean"),
    "equal_integer": _NativeSignature(("integer", "integer"), "boolean"),
    "equal_object": _NativeSignature(("object", "object"), "boolean"),
    "less_than": _NativeSignature(("integer", "integer"), "boolean"),
    "greater_than": _NativeSignature(("integer", "integer"), "boolean"),
}

SIGNATURES: dict[str, OpSignature] = {
    name.upper(): OpSignature(
        arg_types=signature.inputs
        + ((signature.value_input,) if signature.value_input is not None else ()),
        return_type=signature.return_type,
        commutative=name
        in {
            "union",
            "intersect",
            "equal_color",
            "equal_material",
            "equal_shape",
            "equal_size",
            "equal_integer",
            "equal_object",
        },
        selector_kind=(
            "scalar"
            if name == "unique"
            else "set"
            if signature.return_type == "object_set"
            else "none"
        ),
    )
    for name, signature in _NATIVE_SIGNATURES.items()
}

COMMUTATIVE_OPS = frozenset(
    name.upper() for name, signature in SIGNATURES.items() if signature.commutative
)
ALIASES: dict[str, str] = {}
IDENTITY_CASTS: frozenset[str] = frozenset()

_UNSUPPORTED_NODE = AstNode(op="UNSUPPORTED", args=(), return_type="")


def compile_clevr(item: NormalizedItem, world: World) -> Program:
    """Compile the native program stored on a normalized CLEVR item."""

    raw_steps = item.provenance.get("program")
    if not isinstance(raw_steps, list):
        return _unsupported(item, "native_program_missing")
    return compile_clevr_steps(
        raw_steps,
        world=world,
        base_id=item.base_id,
        question_sha256=item.question_sha256,
        choices_sha256=item.choices_sha256,
    )


def compile_clevr_steps(
    raw_steps: Sequence[Mapping[str, Any]],
    *,
    world: World,
    base_id: str,
    question_sha256: str,
    choices_sha256: str,
) -> Program:
    """Compile one official ``program`` array into a typed tree.

    Every dependency must point backward to an already compiled node.  This
    preserves the official DAG evaluation order and makes forward references or
    cycles a typed reject instead of relying on Python recursion behavior.
    """

    nodes: list[AstNode] = []
    unique_nodes: list[AstNode] = []
    try:
        if not raw_steps:
            raise ProgramError("native_program_empty")
        for index, raw in enumerate(raw_steps):
            if not isinstance(raw, Mapping):
                raise ProgramError(f"node_{index}_not_object")
            function = raw.get("function")
            if not isinstance(function, str) or function not in _NATIVE_SIGNATURES:
                raise ProgramError(f"node_{index}_unsupported_function_{function}")
            signature = _NATIVE_SIGNATURES[function]
            raw_inputs = raw.get("inputs")
            raw_values = raw.get("value_inputs")
            if not isinstance(raw_inputs, list) or any(
                isinstance(value, bool) or not isinstance(value, int) for value in raw_inputs
            ):
                raise ProgramError(f"node_{index}_inputs_not_integer_array")
            if len(raw_inputs) != len(signature.inputs):
                raise ProgramError(f"node_{index}_{function}_input_arity_{len(raw_inputs)}")
            if any(value < 0 or value >= index for value in raw_inputs):
                raise ProgramError(f"node_{index}_has_forward_or_invalid_input")
            if not isinstance(raw_values, list):
                raise ProgramError(f"node_{index}_value_inputs_not_array")
            expected_values = 1 if signature.value_input is not None else 0
            if len(raw_values) != expected_values:
                raise ProgramError(f"node_{index}_{function}_value_arity_{len(raw_values)}")

            args: list[AstNode] = [nodes[value] for value in raw_inputs]
            if signature.value_input is not None:
                value = raw_values[0]
                if not isinstance(value, str) or not value:
                    raise ProgramError(f"node_{index}_{function}_value_not_string")
                args.append(lit(value, return_type=signature.value_input))
            node = AstNode(
                op=function.upper(),
                args=tuple(args),
                return_type=signature.return_type,
            )
            nodes.append(node)
            if function == "unique":
                unique_nodes.append(node)

        referent = unique_nodes[-1] if unique_nodes else None
        candidate = Program(
            dsl=DSL,
            program=nodes[-1],
            base_id=base_id,
            question_sha256=question_sha256,
            choices_sha256=choices_sha256,
            compile_status="compiled",
            referent_selector=referent,
            required_referent_cardinality=1 if referent is not None else None,
        )
        checked = typecheck(candidate, world=world)
        return replace(
            checked,
            canonical_program_sha256=canonical_program_sha256(checked, world=world),
        )
    except (ProgramError, ValueError) as exc:
        return Program(
            dsl=DSL,
            program=_UNSUPPORTED_NODE,
            base_id=base_id,
            question_sha256=question_sha256,
            choices_sha256=choices_sha256,
            compile_status="unsupported",
            reason_code=_reason(str(exc)),
        )


def _unsupported(item: NormalizedItem, reason: str) -> Program:
    return Program(
        dsl=DSL,
        program=_UNSUPPORTED_NODE,
        base_id=item.base_id,
        question_sha256=item.question_sha256,
        choices_sha256=item.choices_sha256,
        compile_status="unsupported",
        reason_code=reason,
    )


def _reason(message: str) -> str:
    return (
        message.strip()
        .lower()
        .replace(" ", "_")
        .replace(":", "_")
        .replace("'", "")
        .replace('"', "")
    )


__all__ = [
    "ALIASES",
    "COMMUTATIVE_OPS",
    "DSL",
    "IDENTITY_CASTS",
    "SIGNATURES",
    "compile_clevr",
    "compile_clevr_steps",
]