Download tools/probe_simulation.py from ccnets/causal-gpt-rl-unity-envs: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/datasets/ccnets/causal-gpt-rl-unity-envs/resolve/main/tools/probe_simulation.py
- Command line
-
hf download hf://datasets/ccnets/causal-gpt-rl-unity-envs/tools/probe_simulation.py
-
curl -L -o probe_simulation.py https://huggingface.co/datasets/ccnets/causal-gpt-rl-unity-envs/resolve/main/tools/probe_simulation.py
13.2 kB
| """Probe a model-removed build with per-behavior stock policies, including grids. | |
| Unlike the vector collection wrapper, this preserves spatial observations and | |
| allows heterogeneous roles. This is a simulation smoke test, not a collector. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| from mlagents_envs.environment import UnityEnvironment, ActionTuple | |
| from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel | |
| from mlagents_envs.side_channel.stats_side_channel import StatsSideChannel | |
| class StockPolicy: | |
| def __init__(self, path, spec, rng): | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = 1 | |
| options.inter_op_num_threads = 1 | |
| options.log_severity_level = 3 | |
| self.session = ort.InferenceSession(str(path), sess_options=options, | |
| providers=["CPUExecutionProvider"]) | |
| self.path, self.spec, self.rng = path, spec, rng | |
| self.inputs = self.session.get_inputs() | |
| self.outputs = {o.name: o for o in self.session.get_outputs()} | |
| self.memory = {} | |
| self.memory_shape = None | |
| self.memory_resets = 0 | |
| self.mapping = [] | |
| remaining = list(range(len(spec.observation_specs))) | |
| for item in self.inputs: | |
| if item.name == "action_masks": | |
| continue | |
| if "recurrent" in item.name: | |
| if item.name != "recurrent_in" or "recurrent_out" not in self.outputs: | |
| raise ValueError("Unsupported recurrent I/O contract") | |
| self.memory_shape = tuple(int(n) for n in item.shape[1:]) | |
| continue | |
| shape = tuple(int(n) for n in item.shape[1:]) | |
| matches = [] | |
| for index in remaining: | |
| obs_shape = tuple(spec.observation_specs[index].shape) | |
| if shape == obs_shape: | |
| matches.append((index, False)) | |
| elif len(obs_shape) == 3 and shape == (obs_shape[2], obs_shape[0], obs_shape[1]): | |
| matches.append((index, True)) | |
| if not matches: | |
| raise ValueError(f"{path.name}: input {item.name} {shape} does not match " | |
| f"live observations {[o.shape for o in spec.observation_specs]}") | |
| index, transpose = matches[0] | |
| remaining.remove(index) | |
| self.mapping.append((item.name, index, transpose)) | |
| if remaining: | |
| raise ValueError(f"{path.name}: unconsumed live observation sensors {remaining}") | |
| def forget(self, agent_ids): | |
| for agent_id in agent_ids: | |
| if self.memory.pop(int(agent_id), None) is not None: | |
| self.memory_resets += 1 | |
| def act(self, decision): | |
| n = len(decision) | |
| feeds = {} | |
| for name, index, transpose in self.mapping: | |
| values = decision.obs[index] | |
| if not np.isfinite(values).all(): | |
| raise ValueError("Non-finite observation") | |
| feeds[name] = (values.transpose(0, 3, 1, 2) if transpose else values).astype(np.float32) | |
| for item in self.inputs: | |
| if item.name == "action_masks": | |
| feeds[item.name] = (np.concatenate([~m for m in decision.action_mask], axis=1) | |
| if decision.action_mask is not None else | |
| np.ones((n, sum(self.spec.action_spec.discrete_branches)))).astype(np.float32) | |
| if self.memory_shape is not None: | |
| feeds["recurrent_in"] = np.stack([ | |
| self.memory.get(int(agent_id), np.zeros(self.memory_shape, dtype=np.float32)) | |
| for agent_id in decision.agent_id | |
| ]) | |
| names = [name for name in ("continuous_actions", "discrete_actions") if name in self.outputs] | |
| if self.memory_shape is not None: | |
| names.append("recurrent_out") | |
| values = dict(zip(names, self.session.run(names, feeds))) | |
| if self.memory_shape is not None: | |
| memory = values["recurrent_out"] | |
| if memory.shape != (n,) + self.memory_shape or not np.isfinite(memory).all(): | |
| raise ValueError(f"Bad recurrent output: {memory.shape}") | |
| for agent_id, state in zip(decision.agent_id, memory): | |
| self.memory[int(agent_id)] = state.copy() | |
| actions = ActionTuple() | |
| if self.spec.action_spec.continuous_size: | |
| continuous = values["continuous_actions"] | |
| if continuous.shape != (n, self.spec.action_spec.continuous_size): | |
| raise ValueError(f"Bad continuous action shape {continuous.shape}") | |
| if not np.isfinite(continuous).all(): | |
| raise ValueError("Non-finite continuous action") | |
| actions.add_continuous(np.clip(continuous, -1, 1).astype(np.float32)) | |
| branches = self.spec.action_spec.discrete_branches | |
| if len(branches): | |
| raw = values["discrete_actions"] | |
| if raw.shape == (n, len(branches)): | |
| discrete = raw.astype(np.int32) | |
| elif raw.shape == (n, sum(branches)): | |
| columns, offset = [], 0 | |
| for branch_index, width in enumerate(branches): | |
| logits = raw[:, offset:offset + width].astype(np.float64) | |
| if decision.action_mask is not None: | |
| logits = np.where(decision.action_mask[branch_index], -np.inf, logits) | |
| probabilities = np.exp(logits - logits.max(axis=1, keepdims=True)) | |
| probabilities /= probabilities.sum(axis=1, keepdims=True) | |
| columns.append([self.rng.choice(width, p=row) for row in probabilities]) | |
| offset += width | |
| discrete = np.array(columns, dtype=np.int32).T | |
| else: | |
| raise ValueError(f"Bad discrete action shape {raw.shape}") | |
| for column, width in enumerate(branches): | |
| if not np.all((discrete[:, column] >= 0) & (discrete[:, column] < width)): | |
| raise ValueError("Discrete action out of range") | |
| if decision.action_mask is not None and np.any( | |
| decision.action_mask[column][np.arange(n), discrete[:, column]] | |
| ): | |
| raise ValueError("Policy selected a masked action") | |
| actions.add_discrete(discrete) | |
| return actions | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--build", required=True, type=Path) | |
| parser.add_argument("--policies", type=Path, help="External stock policy directory; unused in random mode") | |
| parser.add_argument("--report", required=True, type=Path) | |
| parser.add_argument("--ticks", type=int, default=1000) | |
| parser.add_argument("--worker-id", type=int, default=650) | |
| parser.add_argument("--seed", type=int, default=23) | |
| parser.add_argument("--random", action="store_true") | |
| parser.add_argument("--graphics", action="store_true", help="Show the simulation window") | |
| parser.add_argument("--render", action="store_true", help="Render camera sensors in batchmode") | |
| parser.add_argument("--time-scale", type=float, default=20.0) | |
| args = parser.parse_args() | |
| manifest = json.loads((args.build.parent / "simulation-build.json").read_text()) | |
| if args.policies is None: | |
| args.policies = args.build.parent.parent / "policies" / manifest["environment"] | |
| policy_files = {b["name"]: args.policies / Path(b["stockPolicy"]).name | |
| for b in manifest["behaviors"]} | |
| rng = np.random.default_rng(args.seed) | |
| channel = EngineConfigurationChannel() | |
| stats_channel = StatsSideChannel() | |
| channel.set_configuration_parameters(time_scale=args.time_scale, width=1280, height=720) | |
| report = {"build": str(args.build.resolve()), "mode": "random" if args.random else "stock", | |
| "rendering": args.graphics or args.render, | |
| "seed": args.seed, "behaviors": {}, "ticks": 0, "passed": False} | |
| args.report.parent.mkdir(parents=True, exist_ok=True) | |
| env = None | |
| try: | |
| env = UnityEnvironment(file_name=str(args.build), no_graphics=not (args.graphics or args.render), seed=args.seed, | |
| worker_id=args.worker_id, side_channels=[channel, stats_channel], timeout_wait=90, | |
| additional_args=["-batchmode"] if args.render and not args.graphics else None, | |
| log_folder=str(args.report.parent / "player-logs")) | |
| env.reset() | |
| policies = {} | |
| for name, spec in env.behavior_specs.items(): | |
| path = policy_files[name.split("?team=")[0]] | |
| if not args.random: | |
| policies[name] = StockPolicy(path, spec, rng) | |
| decision, terminal = env.get_steps(name) | |
| report["behaviors"][name] = { | |
| "observation_shapes": [list(o.shape) for o in spec.observation_specs], | |
| "observation_dimension_properties": [[str(d) for d in o.dimension_property] | |
| for o in spec.observation_specs], | |
| "observation_ranges": [[None, None] for o in spec.observation_specs], | |
| "continuous_size": spec.action_spec.continuous_size, | |
| "discrete_branches": [int(x) for x in spec.action_spec.discrete_branches], | |
| "initial_agents": len(decision), "decision_rows": 0, "terminals": 0, | |
| "interruptions": 0, "agent_reward_sum": 0.0, "group_reward_sum": 0.0, | |
| "policy": None if args.random else str(path), | |
| "policy_sha256": None if args.random else hashlib.sha256(path.read_bytes()).hexdigest(), | |
| } | |
| if not report["behaviors"]: | |
| raise ValueError("No external ML-Agents behaviors exposed") | |
| print(json.dumps(report["behaviors"], indent=2), flush=True) | |
| # Read rewards once per tick, before submitting the next decisions. | |
| for tick in range(args.ticks + 1): | |
| for name, spec in env.behavior_specs.items(): | |
| decision, terminal = env.get_steps(name) | |
| row = report["behaviors"][name] | |
| if not args.random: | |
| policies[name].forget(terminal.agent_id) | |
| row["terminals"] += int(np.sum(~terminal.interrupted)) | |
| row["interruptions"] += int(np.sum(terminal.interrupted)) | |
| for steps in (decision, terminal): | |
| if not np.isfinite(steps.reward).all() or not np.isfinite(steps.group_reward).all(): | |
| raise ValueError("Non-finite reward") | |
| row["agent_reward_sum"] += float(np.sum(steps.reward, dtype=np.float64)) | |
| row["group_reward_sum"] += float(np.sum(steps.group_reward, dtype=np.float64)) | |
| if tick == args.ticks or len(decision) == 0: | |
| continue | |
| row["decision_rows"] += len(decision) | |
| for index, observation in enumerate(decision.obs): | |
| minimum, maximum = float(observation.min()), float(observation.max()) | |
| old_min, old_max = row["observation_ranges"][index] | |
| row["observation_ranges"][index] = [minimum if old_min is None else min(old_min, minimum), | |
| maximum if old_max is None else max(old_max, maximum)] | |
| actions = spec.action_spec.random_action(len(decision)) if args.random else policies[name].act(decision) | |
| env.set_actions(name, actions) | |
| if tick == args.ticks: | |
| break | |
| env.step() | |
| report["ticks"] = tick + 1 | |
| if (tick + 1) % 200 == 0: | |
| print(f"ticks={tick + 1}", flush=True) | |
| if not all(b["decision_rows"] > 0 for b in report["behaviors"].values()): | |
| raise ValueError("One or more behaviors never accepted an action") | |
| for name, policy in policies.items(): | |
| report["behaviors"][name]["recurrent_memory_shape"] = policy.memory_shape | |
| report["behaviors"][name]["recurrent_memory_resets"] = policy.memory_resets | |
| if manifest["environment"] == "GridWorld": | |
| if not (args.graphics or args.render): | |
| raise ValueError("GridWorld camera observations require --render or --graphics") | |
| for row in report["behaviors"].values(): | |
| for shape, value_range in zip(row["observation_shapes"], row["observation_ranges"]): | |
| if len(shape) == 3 and value_range[1] - value_range[0] <= 1e-6: | |
| raise ValueError("GridWorld camera produced constant observations") | |
| report["passed"] = True | |
| except Exception as error: | |
| report["error"] = f"{type(error).__name__}: {error}" | |
| raise | |
| finally: | |
| if env is not None: | |
| env.close() | |
| args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") | |
| print(json.dumps(report, indent=2), flush=True) | |
| if __name__ == "__main__": | |
| main() | |