File size: 4,021 Bytes
fd5366a | 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 | # Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""State assembly: s_t = [z_t, b_t, e_t] plus the image and tool-state blocks.
The layout is fixed and versioned so that saved tensors stay interpretable and
per-modality prediction error is computable by slicing, not by convention.
"""
from __future__ import annotations
import zlib
from dataclasses import dataclass
import numpy as np
from clsa.envs.render import extract_image_features
LAYOUT_VERSION = "1.0"
TOOL_KEYS = (
"balance",
"order_amount",
"refunded",
"n_emails_sent",
"n_files",
"has_report",
"draft_present",
"contract_present",
"cart_size",
"budget",
"marketing_notifications",
"account_active",
)
TOOL_SCALE = {
"balance": 1000.0,
"order_amount": 100.0,
"n_emails_sent": 5.0,
"n_files": 5.0,
"cart_size": 3.0,
"budget": 1000.0,
}
RISK_CLASSES = ("read", "reversible", "compensable", "irreversible")
@dataclass(frozen=True)
class StateLayout:
n_z: int
n_b: int = 12
n_e: int = 9
n_img: int = 8
n_tool: int = 12
@property
def blocks(self) -> dict[str, tuple[int, int]]:
out, i = {}, 0
for name, n in (
("z", self.n_z),
("b", self.n_b),
("e", self.n_e),
("image", self.n_img),
("tool", self.n_tool),
):
out[name] = (i, i + n)
i += n
return out
@property
def dim(self) -> int:
return self.n_z + self.n_b + self.n_e + self.n_img + self.n_tool
def slice(self, name: str) -> slice:
a, b = self.blocks[name]
return slice(a, b)
def tool_vector(tool_state: dict) -> np.ndarray:
v = np.zeros(len(TOOL_KEYS), dtype=np.float32)
for i, k in enumerate(TOOL_KEYS):
val = tool_state.get(k, 0.0)
if isinstance(val, bool):
v[i] = 1.0 if val else 0.0
elif isinstance(val, (int, float)):
v[i] = float(val) / TOOL_SCALE.get(k, 1.0)
return v
def image_vector(image_ref: str | None) -> np.ndarray:
v = np.zeros(8, dtype=np.float32)
if not image_ref:
return v
from clsa.util import DATA
path = image_ref if image_ref.startswith(str(DATA.parent)) else str(DATA.parent / image_ref)
try:
f = extract_image_features(path)
except Exception:
return v
v[0] = (f.get("amount") or 0) / 1000.0
v[1] = float(f.get("digit_confidence", 0.0))
v[2] = 1.0 if f.get("stamp_present") else 0.0
toggles = f.get("toggle_states") or [False, False, False]
v[3:6] = [1.0 if t else 0.0 for t in toggles[:3]]
v[6] = float(f.get("header_rgb", [0, 0, 0])[0])
v[7] = float(f.get("body_rgb", [0, 0, 0])[2])
return v
def action_features(action: dict, risk_class: str) -> np.ndarray:
"""16-dim action embedding: hashed tool identity + risk + numeric args."""
v = np.zeros(16, dtype=np.float32)
name = action.get("name", "")
bucket = zlib.crc32(name.encode("utf-8")) % 8
v[bucket] = 1.0
if risk_class in RISK_CLASSES:
v[8 + RISK_CLASSES.index(risk_class)] = 1.0
args = action.get("args", {}) or {}
amount = 0.0
for key in ("amount", "price"):
if key in args:
try:
amount = float(args[key])
except (TypeError, ValueError):
amount = 0.0
v[12] = amount / 100.0
v[13] = min(1.0, len(args) / 4.0)
v[14] = 1.0 if not args else 0.0
v[15] = 1.0 if name in ("finish", "ask_user") else 0.0
return v
def assemble_state(
z: np.ndarray,
b: np.ndarray,
e: np.ndarray,
image: np.ndarray,
tool: np.ndarray,
) -> np.ndarray:
return np.concatenate(
[
np.asarray(z, dtype=np.float32).ravel(),
np.asarray(b, dtype=np.float32).ravel(),
np.asarray(e, dtype=np.float32).ravel(),
np.asarray(image, dtype=np.float32).ravel(),
np.asarray(tool, dtype=np.float32).ravel(),
]
)
|