minigrid / code /minigrid_fairness.py
zhangdw's picture
Publish MiniGrid fairness v1: frozen 256 evaluation and complete 2886-task train pool
7e962a2 verified
Raw History Blame Contribute Delete
9.55 kB
"""Canonical semantic state, native restoration and offline BFS for MiniGrid v1.
Grid encoding is MiniGrid's x-major [type, color, state] integer encoding.
The five permitted actions are deterministic: RNG state is not decision state.
Task identity hashes the complete initial state; split identity omits only direction.
"""
from __future__ import annotations
import copy
import hashlib
import json
from collections import deque
import numpy as np
PROTOCOL = "minigrid-doorkey-8x8-h64-v1"
STATE_SCHEMA = "minigrid-semantic-state-v1"
ENV_ID = "MiniGrid-DoorKey-8x8-v0"
MINIGRID_VERSION = "3.0.0"
GYMNASIUM_VERSION = "1.2.3"
MISSION = "use the key to open the door and then get to the goal"
MAX_STEPS = 64
def canonical_json(value):
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def digest(value):
return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
def new_env():
import gymnasium as gym
import minigrid
from minigrid.wrappers import RGBImgObsWrapper
if minigrid.__version__ != MINIGRID_VERSION or gym.__version__ != GYMNASIUM_VERSION:
raise RuntimeError(f"MiniGrid v1 requires minigrid=={MINIGRID_VERSION}, gymnasium=={GYMNASIUM_VERSION}")
return RGBImgObsWrapper(gym.make(ENV_ID, max_steps=MAX_STEPS, highlight=False, render_mode="rgb_array").unwrapped, tile_size=56)
def snapshot(env):
base = env.unwrapped
return {
"schema": STATE_SCHEMA,
"env_id": ENV_ID,
"mission": base.mission,
"width": base.width,
"height": base.height,
"max_steps": int(base.max_steps),
"step_count": int(base.step_count),
"grid": base.grid.encode().tolist(),
"agent_pos": [int(x) for x in base.agent_pos],
"agent_dir": int(base.agent_dir),
"carrying": list(base.carrying.encode()) if base.carrying is not None else None,
}
def validate_state(state, *, initial=False):
from minigrid.core.constants import COLOR_TO_IDX, OBJECT_TO_IDX
from minigrid.core.grid import Grid
required = {"schema", "env_id", "mission", "width", "height", "max_steps", "step_count", "grid", "agent_pos", "agent_dir", "carrying"}
if set(state) != required or state["schema"] != STATE_SCHEMA or state["env_id"] != ENV_ID or state["mission"] != MISSION:
raise ValueError("Incompatible MiniGrid semantic schema/mission")
if (state["width"], state["height"], state["max_steps"]) != (8, 8, 64):
raise ValueError("MiniGrid fairness requires 8x8 and horizon 64")
scalars = [*state["agent_pos"], state["agent_dir"], state["step_count"]]
if len(state["agent_pos"]) != 2 or any(type(v) is not int for v in scalars):
raise ValueError("MiniGrid state coordinates and counters must be integers")
if state["agent_dir"] not in range(4) or not 0 <= state["step_count"] <= 64 or (initial and state["step_count"] != 0):
raise ValueError("Invalid direction or step count")
array = np.asarray(state["grid"])
if array.shape != (8, 8, 3) or array.dtype.kind not in "iu" or np.any(array < 0) or np.any(array > 255):
raise ValueError("Invalid MiniGrid grid encoding")
allowed = [OBJECT_TO_IDX[x] for x in ("empty", "wall", "door", "key", "goal")]
if not np.isin(array[:, :, 0], allowed).all():
raise ValueError("Unexpected object type")
grid, _ = Grid.decode(array.astype(np.uint8))
if not np.array_equal(grid.encode(), array):
raise ValueError("Noncanonical object encoding")
if np.any(array[[0, -1], :, 0] != OBJECT_TO_IDX["wall"]) or np.any(array[:, [0, -1], 0] != OBJECT_TO_IDX["wall"]):
raise ValueError("Missing boundary walls")
doors = np.argwhere(array[:, :, 0] == OBJECT_TO_IDX["door"])
keys = np.argwhere(array[:, :, 0] == OBJECT_TO_IDX["key"])
goals = np.argwhere(array[:, :, 0] == OBJECT_TO_IDX["goal"])
carrying = state["carrying"]
if len(doors) != 1 or len(goals) != 1 or len(keys) + (carrying is not None) != 1:
raise ValueError("DoorKey requires one door, goal, and key")
if carrying is not None and carrying != [OBJECT_TO_IDX["key"], COLOR_TO_IDX["yellow"], 0]:
raise ValueError("Only yellow key inventory is supported")
for x, y in [*doors, *keys]:
if array[x, y, 1] != COLOR_TO_IDX["yellow"]:
raise ValueError("Door and key must be yellow")
x, y = state["agent_pos"]
if not (0 < x < 7 and 0 < y < 7):
raise ValueError("Agent is outside interior")
cell = grid.get(x, y)
if cell is not None and not cell.can_overlap():
raise ValueError("Agent overlaps a blocked cell")
if initial and (carrying is not None or array[tuple(doors[0])][2] != 2 or (cell is not None and cell.type == "goal")):
raise ValueError("Initial DoorKey state must be unsolved, locked and empty-handed")
def restore(env, state, *, validate=True):
from minigrid.core.grid import Grid
from minigrid.core.world_object import WorldObj
if validate:
validate_state(state)
base = env.unwrapped
base.grid, _ = Grid.decode(np.asarray(state["grid"], dtype=np.uint8))
base.agent_pos = np.asarray(state["agent_pos"], dtype=int)
base.agent_dir = state["agent_dir"]
base.carrying = WorldObj.decode(*state["carrying"]) if state["carrying"] else None
base.step_count = state["step_count"]
base.max_steps = state["max_steps"]
base.mission = state["mission"]
def task_id(state):
return digest(state)
def split_group_id(state):
return digest({k: v for k, v in state.items() if k != "agent_dir"})
def decision_key(task, state):
return canonical_json({"task_id": task, "state": state})
def validate_task(row, *, split=None):
if row.get("metadata", {}).get("protocol") != PROTOCOL:
raise ValueError("Incompatible MiniGrid task protocol")
validate_state(row["initial_state"], initial=True)
metadata = row["metadata"]
if metadata.get("task_id") != task_id(row["initial_state"]) or metadata.get("split_group_id") != split_group_id(row["initial_state"]):
raise ValueError("MiniGrid task content hash mismatch")
if split is not None and metadata.get("split") != split:
raise ValueError("MiniGrid split mismatch")
if not isinstance(metadata.get("shortest_length"), int) or not 1 <= metadata["shortest_length"] <= 64:
raise ValueError("Unreachable or unverified MiniGrid task")
def shortest_solution(env, initial):
"""BFS transitions use MiniGrid's actual step, including native turn/toggle.
The visited key excludes elapsed time: BFS first reaches each physical state
with the greatest remaining budget. A longer duplicate cannot improve reachability.
Restore mutates only dynamic fields here; walls/goal are constant for a task.
"""
from minigrid.core.world_object import Key
restore(env, initial)
base = env.unwrapped
door_pos = next((x, y) for x in range(8) for y in range(8) if (base.grid.get(x, y) is not None and base.grid.get(x, y).type == "door"))
key_pos = next((x, y) for x in range(8) for y in range(8) if (base.grid.get(x, y) is not None and base.grid.get(x, y).type == "key"))
door = base.grid.get(*door_pos)
key_obj = Key("yellow")
start = (*initial["agent_pos"], initial["agent_dir"], False, 2)
queue = deque([(start, ())])
seen = {start}
for_state = (0, 1, 2, 3, 5)
while queue:
current, path = queue.popleft()
if len(path) >= 64:
continue
for action in for_state:
x, y, direction, held, door_state = current
base.agent_pos = np.array([x, y])
base.agent_dir = direction
base.carrying = key_obj if held else None
base.grid.set(*key_pos, None if held else key_obj)
door.is_open = door_state == 0
door.is_locked = door_state == 2
base.step_count = len(path)
# Unwrapped avoids full image rendering; native dynamics/reward are identical.
_, reward, terminated, _, _ = base.step(action)
next_path = path + (action,)
if terminated and reward > 0:
restore(env, initial, validate=False)
return next_path
following = (*map(int, base.agent_pos), int(base.agent_dir), base.carrying is not None, int(door.encode()[2]))
if following not in seen:
seen.add(following)
queue.append((following, next_path))
restore(env, initial, validate=False)
return None
class TaskSampler:
"""Private, checkpointable task sampler, independent of validation/global RNG."""
def __init__(self, rows, seed):
self.rows = rows
self.rng = np.random.RandomState(seed)
self.draws = 0
self.pool_hash = digest([r["metadata"]["task_id"] for r in rows])
def sample(self, count):
indices = self.rng.choice(len(self.rows), size=count, replace=False)
self.draws += count
return [self.rows[i] for i in indices]
def state_dict(self):
return {"schema": "minigrid-task-sampler-v1", "pool_hash": self.pool_hash, "draws": self.draws, "rng": copy.deepcopy(self.rng.get_state())}
def load_state_dict(self, state):
if state["schema"] != "minigrid-task-sampler-v1" or state["pool_hash"] != self.pool_hash:
raise ValueError("Sampler checkpoint does not match the pinned MiniGrid task pool")
self.rng.set_state(state["rng"])
self.draws = int(state["draws"])