minigrid / code /minigrid_protocol.py
zhangdw's picture
Publish MiniGrid fairness v1: frozen 256 evaluation and complete 2886-task train pool
7e962a2 verified
Raw History Blame Contribute Delete
2.22 kB
"""MiniGrid v1 grammar and native policy action IDs (drop/done are not actions)."""
import re
from dataclasses import dataclass
ACTIONS = {"left": 0, "right": 1, "forward": 2, "pickup": 3, "toggle": 5}
_ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
def normalize_action(action):
normalized = str(action).strip().translate(_ASCII_LOWER)
if normalized not in ACTIONS:
raise ValueError("MiniGrid action must be left, right, forward, pickup, or toggle")
return normalized
@dataclass(frozen=True)
class ParsedAction:
action: str | None
reason: str = ""
attempted_action: str = "unavailable"
@property
def valid(self):
return self.action is not None
def parse_response(response, *, hit_limit=False):
# Padding/terminal special tokens are removed by the tokenizer, never prose.
text = str(response)
blocks = re.findall(r"<action>(.*?)</action>", text, re.S)
attempted = "unavailable"
if len(blocks) == 1 and text.count("<action>") == text.count("</action>") == 1:
try:
attempted = normalize_action(blocks[0])
except ValueError:
pass
reason = ""
tags = ("<think>", "</think>", "<action>", "</action>")
if hit_limit and not blocks:
reason = "truncated_action"
elif any(text.count(tag) > 1 for tag in tags):
reason = "multiple_blocks"
elif not all(tag in text for tag in tags[:2]):
reason = "missing_think_block"
elif not all(tag in text for tag in tags[2:]):
reason = "missing_action_block"
else:
match = re.fullmatch(r"\s*<think>(.*?)</think>\s*<action>(.*?)</action>\s*", text, re.S)
if match is None or any(tag in match[1] or tag in match[2] for tag in tags):
reason = "malformed_format"
else:
payload = match[2].strip().translate(_ASCII_LOWER)
if payload in ACTIONS:
return ParsedAction(payload, attempted_action=payload)
words = re.findall("[a-z]+", payload)
reason = "multiple_actions" if sum(word in ACTIONS for word in words) >= 2 else "unsupported_action"
return ParsedAction(None, reason, attempted)