Add files using upload-large-folder tool
Browse files- src_code_for_reproducibility/__init__.py +0 -0
- src_code_for_reproducibility/docs/source/conf.py +48 -0
- src_code_for_reproducibility/docs/source/index.rst +22 -0
- src_code_for_reproducibility/docs/source/src.environments.dond.rst +19 -0
- src_code_for_reproducibility/docs/source/src.utils.rst +24 -0
- src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/diplomacy/diplomacy_agent.py +259 -0
- src_code_for_reproducibility/markov_games/diplomacy/diplomacy_env.py +230 -0
- src_code_for_reproducibility/markov_games/diplomacy/diplomacy_logging.py +360 -0
- src_code_for_reproducibility/markov_games/diplomacy/diplomacy_logging_for_training.py +0 -0
- src_code_for_reproducibility/markov_games/ipd/__init__.py +7 -0
- src_code_for_reproducibility/markov_games/ipd/__pycache__/Ipd_hard_coded_agents.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_agent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_simulation.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_statistics.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/ipd/ipd_agent.py +115 -0
- src_code_for_reproducibility/markov_games/ipd/ipd_simulation.py +162 -0
- src_code_for_reproducibility/markov_games/ipd/ipd_statistics.py +18 -0
- src_code_for_reproducibility/markov_games/negotiation/README.md +40 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_agent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_simulation.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_agent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_hard_coded_policies.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_simulation.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/negotiation_statistics.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_agent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_simulation.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_agent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_agent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_simulation.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_simple_agent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_simple_simulation.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_simulation.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/negotiation/dond_agent.py +61 -0
- src_code_for_reproducibility/markov_games/negotiation/nego_simulation.py +241 -0
- src_code_for_reproducibility/markov_games/negotiation/negotiation_statistics.py +244 -0
- src_code_for_reproducibility/markov_games/negotiation/tas_rps_simulation.py +248 -0
- src_code_for_reproducibility/markov_games/negotiation/tas_simple_agent.py +90 -0
- src_code_for_reproducibility/training/__pycache__/__init__.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/annealing_methods.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/credit_methods.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/produce_training_stats.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/tally_basic.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/tokenize_chats.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/trainer_ad_align.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/trainer_common.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/trainer_independent.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/trainer_sum_rewards.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/training_data_utils.cpython-312.pyc +0 -0
src_code_for_reproducibility/__init__.py
ADDED
|
File without changes
|
src_code_for_reproducibility/docs/source/conf.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Configuration file for the Sphinx documentation builder.
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
sys.path.insert(0, os.path.abspath('../..'))
|
| 5 |
+
|
| 6 |
+
# -- Project information -----------------------------------------------------
|
| 7 |
+
project = 'llm_negotiation'
|
| 8 |
+
copyright = '2023, Your Name'
|
| 9 |
+
author = 'Your Name'
|
| 10 |
+
|
| 11 |
+
# -- General configuration ---------------------------------------------------
|
| 12 |
+
extensions = [
|
| 13 |
+
'sphinx.ext.autodoc',
|
| 14 |
+
'sphinx.ext.viewcode',
|
| 15 |
+
'sphinx.ext.napoleon',
|
| 16 |
+
'sphinx.ext.autosummary',
|
| 17 |
+
'sphinx.ext.intersphinx',
|
| 18 |
+
'sphinx.ext.mathjax',
|
| 19 |
+
'sphinxcontrib.mermaid',
|
| 20 |
+
'sphinx_rtd_theme',
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
templates_path = ['_templates']
|
| 24 |
+
exclude_patterns = []
|
| 25 |
+
|
| 26 |
+
# -- Options for HTML output -------------------------------------------------
|
| 27 |
+
html_theme = 'sphinx_rtd_theme'
|
| 28 |
+
html_static_path = ['_static']
|
| 29 |
+
|
| 30 |
+
# -- Napoleon settings -------------------------------------------------------
|
| 31 |
+
napoleon_google_docstring = True
|
| 32 |
+
napoleon_numpy_docstring = False
|
| 33 |
+
napoleon_include_init_with_doc = True
|
| 34 |
+
napoleon_include_private_with_doc = False
|
| 35 |
+
napoleon_include_special_with_doc = True
|
| 36 |
+
napoleon_use_admonition_for_examples = False
|
| 37 |
+
napoleon_use_admonition_for_notes = False
|
| 38 |
+
napoleon_use_admonition_for_references = False
|
| 39 |
+
napoleon_use_ivar = False
|
| 40 |
+
napoleon_use_param = True
|
| 41 |
+
napoleon_use_rtype = True
|
| 42 |
+
napoleon_preprocess_types = False
|
| 43 |
+
napoleon_type_aliases = None
|
| 44 |
+
napoleon_attr_annotations = True
|
| 45 |
+
|
| 46 |
+
# -- Path setup --------------------------------------------------------------
|
| 47 |
+
# Make sure the project's modules can be found by Sphinx
|
| 48 |
+
sys.path.insert(0, os.path.abspath('../../src'))
|
src_code_for_reproducibility/docs/source/index.rst
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Welcome to LLM Negotiation's documentation!
|
| 2 |
+
===========================================
|
| 3 |
+
This library is a collection of tools for training and evaluating LLM-based agents in multi-agent environments. It is designed to be easy to use and extend.
|
| 4 |
+
|
| 5 |
+
.. toctree::
|
| 6 |
+
:maxdepth: 3
|
| 7 |
+
:caption: Contents:
|
| 8 |
+
|
| 9 |
+
installation
|
| 10 |
+
marl_standard
|
| 11 |
+
environments
|
| 12 |
+
launch
|
| 13 |
+
usage
|
| 14 |
+
modules
|
| 15 |
+
contributing
|
| 16 |
+
|
| 17 |
+
Indices and tables
|
| 18 |
+
==================
|
| 19 |
+
|
| 20 |
+
* :ref:`genindex`
|
| 21 |
+
* :ref:`modindex`
|
| 22 |
+
* :ref:`search`
|
src_code_for_reproducibility/docs/source/src.environments.dond.rst
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
src.environments.dond package
|
| 2 |
+
=============================
|
| 3 |
+
|
| 4 |
+
.. automodule:: src.environments.dond
|
| 5 |
+
:members:
|
| 6 |
+
:undoc-members:
|
| 7 |
+
:show-inheritance:
|
| 8 |
+
|
| 9 |
+
Submodules
|
| 10 |
+
----------
|
| 11 |
+
|
| 12 |
+
.. toctree::
|
| 13 |
+
:maxdepth: 4
|
| 14 |
+
|
| 15 |
+
src.environments.dond.dond_agent
|
| 16 |
+
src.environments.dond.dond_game
|
| 17 |
+
src.environments.dond.dond_log_funcs
|
| 18 |
+
src.environments.dond.dond_statistics_funcs
|
| 19 |
+
src.environments.dond.dond_training_data_funcs
|
src_code_for_reproducibility/docs/source/src.utils.rst
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
src.utils package
|
| 2 |
+
=================
|
| 3 |
+
|
| 4 |
+
.. automodule:: src.utils
|
| 5 |
+
:members:
|
| 6 |
+
:undoc-members:
|
| 7 |
+
:show-inheritance:
|
| 8 |
+
|
| 9 |
+
Submodules
|
| 10 |
+
----------
|
| 11 |
+
|
| 12 |
+
.. toctree::
|
| 13 |
+
:maxdepth: 4
|
| 14 |
+
|
| 15 |
+
src.utils.common_imports
|
| 16 |
+
src.utils.export_ppo_training_set
|
| 17 |
+
src.utils.extra_stats
|
| 18 |
+
src.utils.inherit_args
|
| 19 |
+
src.utils.log_gpu_usage
|
| 20 |
+
src.utils.log_statistics
|
| 21 |
+
src.utils.model_to_cpu
|
| 22 |
+
src.utils.parallel_shuffle
|
| 23 |
+
src.utils.quick_stats
|
| 24 |
+
src.utils.update_start_epoch
|
src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc
ADDED
|
Binary file (1.14 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/diplomacy/diplomacy_agent.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Tuple, Optional, Any
|
| 2 |
+
import copy
|
| 3 |
+
|
| 4 |
+
class DiplomacyAgent:
|
| 5 |
+
"""Agent handler for Diplomacy game that follows the MARL standard.
|
| 6 |
+
|
| 7 |
+
This class is responsible for parsing LLM output into valid Diplomacy orders,
|
| 8 |
+
managing the agent state, and providing information for logging.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def __init__(self, policy_id: str, power_name: str, random_valid_move=False):
|
| 12 |
+
"""Initialize the agent handler for a power in the Diplomacy game.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
power_name: The name of the power this agent controls (e.g., 'FRANCE', 'ENGLAND')
|
| 16 |
+
policy_id: The identifier for the policy this agent uses
|
| 17 |
+
random_valid_move: If True, will select random valid moves instead of using LLM (default: False)
|
| 18 |
+
"""
|
| 19 |
+
self.policy_id = policy_id
|
| 20 |
+
self.power_name = power_name
|
| 21 |
+
self.orders = []
|
| 22 |
+
self.wait = True
|
| 23 |
+
self.processing_state = "WAITING_FOR_ORDERS"
|
| 24 |
+
self.parsed_orders = []
|
| 25 |
+
self.order_status = {}
|
| 26 |
+
self.message_history = []
|
| 27 |
+
self.random_valid_move = random_valid_move
|
| 28 |
+
|
| 29 |
+
def step(self, observation_from_env, policy_output=None):
|
| 30 |
+
"""Update the agent state based on the observation and LLM output.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
observation_from_env: The observation from the environment
|
| 34 |
+
policy_output: The output from the LLM
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
policy_id: The policy identifier
|
| 38 |
+
policy_input: The input to the policy
|
| 39 |
+
action: The official action to be sent to the environment
|
| 40 |
+
done: Whether the LLM action is ready to be sent to the environment
|
| 41 |
+
info: Additional information about the agent
|
| 42 |
+
"""
|
| 43 |
+
info = {}
|
| 44 |
+
|
| 45 |
+
# If random_valid_move is enabled, select random valid moves
|
| 46 |
+
if self.random_valid_move:
|
| 47 |
+
valid_orders = self._select_random_valid_moves(observation_from_env)
|
| 48 |
+
self.orders = valid_orders
|
| 49 |
+
self.wait = False
|
| 50 |
+
action = {
|
| 51 |
+
"orders": valid_orders,
|
| 52 |
+
"wait": False
|
| 53 |
+
}
|
| 54 |
+
return self.policy_id, {}, action, True, info
|
| 55 |
+
|
| 56 |
+
# If no policy output, this is the initial step - prepare prompt
|
| 57 |
+
if policy_output is None:
|
| 58 |
+
# Create initial prompt for the LLM
|
| 59 |
+
phase = observation_from_env.get('phase', '')
|
| 60 |
+
units = observation_from_env.get('units', {}).get(self.power_name, [])
|
| 61 |
+
centers = observation_from_env.get('centers', {}).get(self.power_name, [])
|
| 62 |
+
orderable_locations = observation_from_env.get('orderable_locations', {})
|
| 63 |
+
|
| 64 |
+
prompt = self._create_prompt(phase, units, centers, orderable_locations)
|
| 65 |
+
|
| 66 |
+
return self.policy_id, {"prompt": prompt}, None, False, info
|
| 67 |
+
|
| 68 |
+
# Process the LLM output to extract orders
|
| 69 |
+
success, parsed_orders = self._parse_llm_output(policy_output)
|
| 70 |
+
self.parsed_orders = parsed_orders
|
| 71 |
+
|
| 72 |
+
if not success:
|
| 73 |
+
# Need more information from LLM
|
| 74 |
+
clarification_prompt = self._create_clarification_prompt(policy_output, parsed_orders)
|
| 75 |
+
return self.policy_id, {"prompt": clarification_prompt}, None, False, info
|
| 76 |
+
|
| 77 |
+
# Validate if the orders are valid for the current phase
|
| 78 |
+
valid_orders = self._validate_orders(parsed_orders, observation_from_env)
|
| 79 |
+
|
| 80 |
+
if valid_orders:
|
| 81 |
+
# Orders are valid, prepare action for environment
|
| 82 |
+
self.orders = valid_orders
|
| 83 |
+
self.wait = False
|
| 84 |
+
action = {
|
| 85 |
+
"orders": valid_orders,
|
| 86 |
+
"wait": False
|
| 87 |
+
}
|
| 88 |
+
return self.policy_id, {}, action, True, info
|
| 89 |
+
else:
|
| 90 |
+
# Orders are invalid, ask for new ones
|
| 91 |
+
error_prompt = self._create_error_prompt(parsed_orders, observation_from_env)
|
| 92 |
+
return self.policy_id, {"prompt": error_prompt}, None, False, info
|
| 93 |
+
|
| 94 |
+
def _create_prompt(self, phase, units, centers, orderable_locations):
|
| 95 |
+
"""Create the initial prompt for the LLM.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
phase: The current game phase
|
| 99 |
+
units: List of units controlled by this power
|
| 100 |
+
centers: List of supply centers controlled by this power
|
| 101 |
+
orderable_locations: List of locations where orders can be issued
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
A prompt string for the LLM
|
| 105 |
+
"""
|
| 106 |
+
prompt = f"You are playing as {self.power_name} in Diplomacy. The current phase is {phase}.\n\n"
|
| 107 |
+
prompt += f"Your units: {', '.join(units)}\n"
|
| 108 |
+
prompt += f"Your supply centers: {', '.join(centers)}\n"
|
| 109 |
+
prompt += f"Locations you can order: {', '.join(orderable_locations)}\n\n"
|
| 110 |
+
|
| 111 |
+
if phase.endswith('M'): # Movement phase
|
| 112 |
+
prompt += "Please provide orders for your units in the form:\n"
|
| 113 |
+
prompt += "- A LON H (hold)\n"
|
| 114 |
+
prompt += "- F NTH - NWY (move)\n"
|
| 115 |
+
prompt += "- A WAL S F LON (support)\n"
|
| 116 |
+
prompt += "- F NWG C A NWY - EDI (convoy)\n"
|
| 117 |
+
elif phase.endswith('R'): # Retreat phase
|
| 118 |
+
prompt += "Please provide retreat orders for your dislodged units:\n"
|
| 119 |
+
prompt += "- A PAR R MAR (retreat to MAR)\n"
|
| 120 |
+
prompt += "- A PAR D (disband)\n"
|
| 121 |
+
elif phase.endswith('A'): # Adjustment phase
|
| 122 |
+
if len(units) < len(centers):
|
| 123 |
+
prompt += "You can build units. Please provide build orders:\n"
|
| 124 |
+
prompt += "- A PAR B (build army in PAR)\n"
|
| 125 |
+
prompt += "- F BRE B (build fleet in BRE)\n"
|
| 126 |
+
prompt += "- WAIVE (waive a build)\n"
|
| 127 |
+
elif len(units) > len(centers):
|
| 128 |
+
prompt += "You must remove units. Please provide disbandment orders:\n"
|
| 129 |
+
prompt += "- A PAR D (disband army in PAR)\n"
|
| 130 |
+
prompt += "- F BRE D (disband fleet in BRE)\n"
|
| 131 |
+
|
| 132 |
+
prompt += "\nProvide your orders as a list, one per line."
|
| 133 |
+
return prompt
|
| 134 |
+
|
| 135 |
+
def _parse_llm_output(self, llm_output):
|
| 136 |
+
"""Parse the LLM output to extract orders.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
llm_output: The raw output from the LLM
|
| 140 |
+
|
| 141 |
+
Returns:
|
| 142 |
+
success: Whether parsing was successful
|
| 143 |
+
parsed_orders: List of parsed orders
|
| 144 |
+
"""
|
| 145 |
+
# Simple parsing for now - extract lines that look like orders
|
| 146 |
+
lines = llm_output.strip().split('\n')
|
| 147 |
+
orders = []
|
| 148 |
+
|
| 149 |
+
for line in lines:
|
| 150 |
+
# Remove list markers, hyphens, etc.
|
| 151 |
+
line = line.strip('- *•').strip()
|
| 152 |
+
|
| 153 |
+
# Skip empty lines and lines that don't look like orders
|
| 154 |
+
if not line or line.startswith('I ') or line.startswith('Let\'s'):
|
| 155 |
+
continue
|
| 156 |
+
|
| 157 |
+
# Check if it looks like a Diplomacy order
|
| 158 |
+
if (' H' in line or ' -' in line or ' S ' in line or ' C ' in line or
|
| 159 |
+
' R ' in line or ' D' in line or ' B' in line or line == 'WAIVE'):
|
| 160 |
+
orders.append(line)
|
| 161 |
+
|
| 162 |
+
return len(orders) > 0, orders
|
| 163 |
+
|
| 164 |
+
def _validate_orders(self, orders, observation):
|
| 165 |
+
"""Validate if the orders are valid for the current phase.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
orders: List of orders to validate
|
| 169 |
+
observation: Current observation from the environment
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
List of valid orders or None if invalid
|
| 173 |
+
"""
|
| 174 |
+
# For simplicity, we'll assume all parsed orders are valid
|
| 175 |
+
# In a real implementation, we would use the game's validation logic
|
| 176 |
+
return orders
|
| 177 |
+
|
| 178 |
+
def _create_clarification_prompt(self, previous_output, parsed_orders):
|
| 179 |
+
"""Create a prompt asking for clarification when orders couldn't be parsed.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
previous_output: The previous LLM output
|
| 183 |
+
parsed_orders: Any orders that were successfully parsed
|
| 184 |
+
|
| 185 |
+
Returns:
|
| 186 |
+
A prompt string for the LLM
|
| 187 |
+
"""
|
| 188 |
+
prompt = f"I couldn't fully understand your orders for {self.power_name}. "
|
| 189 |
+
|
| 190 |
+
if parsed_orders:
|
| 191 |
+
prompt += f"I understood these orders:\n"
|
| 192 |
+
for order in parsed_orders:
|
| 193 |
+
prompt += f"- {order}\n"
|
| 194 |
+
|
| 195 |
+
prompt += "\nPlease provide clear, valid Diplomacy orders in the format:\n"
|
| 196 |
+
prompt += "- A LON H\n- F NTH - NWY\n- etc.\n"
|
| 197 |
+
return prompt
|
| 198 |
+
|
| 199 |
+
def _create_error_prompt(self, invalid_orders, observation):
|
| 200 |
+
"""Create a prompt when orders are invalid.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
invalid_orders: The invalid orders
|
| 204 |
+
observation: Current observation from the environment
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
A prompt string for the LLM
|
| 208 |
+
"""
|
| 209 |
+
prompt = f"The following orders for {self.power_name} are invalid:\n"
|
| 210 |
+
for order in invalid_orders:
|
| 211 |
+
prompt += f"- {order}\n"
|
| 212 |
+
|
| 213 |
+
prompt += "\nPlease provide valid orders for your units."
|
| 214 |
+
return prompt
|
| 215 |
+
|
| 216 |
+
def get_log_info(self):
|
| 217 |
+
"""Get information about the agent required to log a trajectory.
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
log_info: Information about the agent required to log a trajectory.
|
| 221 |
+
"""
|
| 222 |
+
return {
|
| 223 |
+
"power_name": self.power_name,
|
| 224 |
+
"orders": self.orders,
|
| 225 |
+
"wait": self.wait,
|
| 226 |
+
"parsing_state": self.processing_state,
|
| 227 |
+
"message_history": self.message_history
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
def render(self):
|
| 231 |
+
"""Render the current state of the agent."""
|
| 232 |
+
print(f"Power: {self.power_name}")
|
| 233 |
+
print(f"Orders: {self.orders}")
|
| 234 |
+
print(f"Wait: {self.wait}")
|
| 235 |
+
|
| 236 |
+
def close(self):
|
| 237 |
+
"""Perform any necessary cleanup."""
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
def _select_random_valid_moves(self, observation):
|
| 241 |
+
"""Select random valid moves for all units.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
observation: Current observation from the environment
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
List of valid orders
|
| 248 |
+
"""
|
| 249 |
+
import random
|
| 250 |
+
|
| 251 |
+
possible_orders = observation.get('possible_orders', {})
|
| 252 |
+
valid_orders = []
|
| 253 |
+
|
| 254 |
+
# For each location with possible orders, select one randomly
|
| 255 |
+
for location, orders in possible_orders.items():
|
| 256 |
+
if orders: # If there are any possible orders for this location
|
| 257 |
+
valid_orders.append(random.choice(orders))
|
| 258 |
+
|
| 259 |
+
return valid_orders
|
src_code_for_reproducibility/markov_games/diplomacy/diplomacy_env.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Tuple, Optional, Any
|
| 2 |
+
from diplomacy import Game
|
| 3 |
+
import random
|
| 4 |
+
|
| 5 |
+
class DiplomacyEnv:
|
| 6 |
+
"""Multi-Agent Reinforcement Learning environment for Diplomacy.
|
| 7 |
+
|
| 8 |
+
This class wraps the Diplomacy game engine to provide an interface
|
| 9 |
+
compliant with the MARL standard.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, random_seed=None, map_name="standard", game_id=None, rules=None, max_steps=50):
|
| 13 |
+
"""Initialize the Diplomacy environment.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
map_name: The name of the map to use (default: "standard")
|
| 17 |
+
game_id: Optional game ID
|
| 18 |
+
rules: Optional rules to apply to the game
|
| 19 |
+
max_steps: Maximum number of steps before forcing game end (default: 10)
|
| 20 |
+
"""
|
| 21 |
+
self.random_seed = random_seed
|
| 22 |
+
self.map_name = map_name
|
| 23 |
+
self.game_id = game_id
|
| 24 |
+
self.rules = rules or []
|
| 25 |
+
self.game = None
|
| 26 |
+
self.active_powers = []
|
| 27 |
+
self.render_mode = None
|
| 28 |
+
self.max_steps = max_steps
|
| 29 |
+
self.current_steps = 0
|
| 30 |
+
|
| 31 |
+
def reset(self):
|
| 32 |
+
"""Reset the environment to an initial state and return the initial observation.
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
observation: A dictionary where keys are agent identifiers and values are observations.
|
| 36 |
+
"""
|
| 37 |
+
# Initialize a new game
|
| 38 |
+
self.game = Game(game_id=self.game_id, map_name=self.map_name)
|
| 39 |
+
|
| 40 |
+
# Apply rules
|
| 41 |
+
for rule in self.rules:
|
| 42 |
+
self.game.add_rule(rule)
|
| 43 |
+
|
| 44 |
+
# Determine active powers (not eliminated)
|
| 45 |
+
self.active_powers = [name for name, power in self.game.powers.items()
|
| 46 |
+
if not power.is_eliminated()]
|
| 47 |
+
|
| 48 |
+
# Reset step counter
|
| 49 |
+
self.current_steps = 0
|
| 50 |
+
|
| 51 |
+
# Create initial observations for all powers
|
| 52 |
+
observations = {}
|
| 53 |
+
for power_name in self.active_powers:
|
| 54 |
+
observations[power_name] = self._create_observation(power_name)
|
| 55 |
+
|
| 56 |
+
return observations
|
| 57 |
+
|
| 58 |
+
def step(self, actions):
|
| 59 |
+
"""Take a step in the environment using the provided actions.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
actions: A dictionary where keys are agent identifiers and values are actions.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
observations: A dictionary where keys are agent identifiers and values are observations.
|
| 66 |
+
done: Whether the episode has ended.
|
| 67 |
+
info: Additional information about the environment.
|
| 68 |
+
"""
|
| 69 |
+
print(f"stepping {self.current_steps}")
|
| 70 |
+
self.current_steps += 1
|
| 71 |
+
# Apply actions (orders) for each power
|
| 72 |
+
for power_name, action in actions.items():
|
| 73 |
+
if power_name in self.active_powers:
|
| 74 |
+
orders = action.get("orders", [])
|
| 75 |
+
wait = action.get("wait", True)
|
| 76 |
+
|
| 77 |
+
# Set orders for the power
|
| 78 |
+
if orders:
|
| 79 |
+
self.game.set_orders(power_name, orders)
|
| 80 |
+
|
| 81 |
+
# Set wait flag
|
| 82 |
+
self.game.set_wait(power_name, wait)
|
| 83 |
+
|
| 84 |
+
# Check if all active powers are ready to proceed
|
| 85 |
+
if self.game.does_not_wait():
|
| 86 |
+
# Process the current phase
|
| 87 |
+
self.game.process()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# Update active powers list after processing
|
| 91 |
+
self.active_powers = [name for name, power in self.game.powers.items()
|
| 92 |
+
if not power.is_eliminated()]
|
| 93 |
+
|
| 94 |
+
# Create observations for all active powers
|
| 95 |
+
observations = {}
|
| 96 |
+
for power_name in self.active_powers:
|
| 97 |
+
observations[power_name] = self._create_observation(power_name)
|
| 98 |
+
|
| 99 |
+
# Check if the game is done (either naturally or due to max steps)
|
| 100 |
+
done = self.game.is_game_done or self.current_steps >= self.max_steps
|
| 101 |
+
|
| 102 |
+
# Create info dict
|
| 103 |
+
info = {
|
| 104 |
+
"phase": self.game.get_current_phase(),
|
| 105 |
+
"active_powers": self.active_powers,
|
| 106 |
+
"centers": self.game.get_centers(),
|
| 107 |
+
"units": self.game.get_units(),
|
| 108 |
+
"current_steps": self.current_steps,
|
| 109 |
+
"max_steps_reached": self.current_steps >= self.max_steps
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
return observations, done, info
|
| 113 |
+
|
| 114 |
+
def _create_observation(self, power_name):
|
| 115 |
+
"""Create observation for a specific power.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
power_name: The name of the power
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
An observation dictionary
|
| 122 |
+
"""
|
| 123 |
+
observation = {
|
| 124 |
+
"phase": self.game.get_current_phase(),
|
| 125 |
+
"units": self.game.get_units(),
|
| 126 |
+
"centers": self.game.get_centers(),
|
| 127 |
+
"orderable_locations": self.game.get_orderable_locations(power_name),
|
| 128 |
+
"order_status": self.game.get_order_status(power_name),
|
| 129 |
+
"possible_orders": self._get_possible_orders_for_power(power_name)
|
| 130 |
+
}
|
| 131 |
+
return observation
|
| 132 |
+
|
| 133 |
+
def _get_possible_orders_for_power(self, power_name):
|
| 134 |
+
"""Get all possible orders for a power's units.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
power_name: The name of the power
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
A dictionary mapping units to their possible orders
|
| 141 |
+
"""
|
| 142 |
+
all_possible_orders = self.game.get_all_possible_orders()
|
| 143 |
+
|
| 144 |
+
# Filter for only the locations where this power has units
|
| 145 |
+
power_units = self.game.get_units(power_name)
|
| 146 |
+
power_unit_locations = [unit[2:] for unit in power_units]
|
| 147 |
+
|
| 148 |
+
# For retreat phases, include retreating units
|
| 149 |
+
if self.game.phase_type == 'R':
|
| 150 |
+
power = self.game.get_power(power_name)
|
| 151 |
+
power_unit_locations.extend([unit[2:] for unit in power.retreats])
|
| 152 |
+
|
| 153 |
+
# For adjustment phases, include buildable locations
|
| 154 |
+
elif self.game.phase_type == 'A':
|
| 155 |
+
power = self.game.get_power(power_name)
|
| 156 |
+
# If we have more centers than units, we can build
|
| 157 |
+
if len(power.centers) > len(power.units):
|
| 158 |
+
buildable_sites = self.game._build_sites(power)
|
| 159 |
+
power_unit_locations.extend(buildable_sites)
|
| 160 |
+
# If we have more units than centers, we need to remove
|
| 161 |
+
elif len(power.units) > len(power.centers):
|
| 162 |
+
# All units are candidates for removal
|
| 163 |
+
pass
|
| 164 |
+
|
| 165 |
+
# Filter the possible orders to only those for this power's units/locations
|
| 166 |
+
power_possible_orders = {}
|
| 167 |
+
for loc, orders in all_possible_orders.items():
|
| 168 |
+
if loc[:3] in power_unit_locations:
|
| 169 |
+
power_possible_orders[loc] = orders
|
| 170 |
+
|
| 171 |
+
return power_possible_orders
|
| 172 |
+
|
| 173 |
+
def get_log_info(self):
|
| 174 |
+
"""Get additional information about the environment for logging.
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
log_info: Information about the environment required to log the game.
|
| 178 |
+
"""
|
| 179 |
+
if not self.game:
|
| 180 |
+
return {}
|
| 181 |
+
|
| 182 |
+
return {
|
| 183 |
+
"game_id": self.game.game_id,
|
| 184 |
+
"phase": self.game.get_current_phase(),
|
| 185 |
+
"map_name": self.game.map_name,
|
| 186 |
+
"centers": self.game.get_centers(),
|
| 187 |
+
"units": self.game.get_units(),
|
| 188 |
+
"powers": {name: {
|
| 189 |
+
"units": power.units,
|
| 190 |
+
"centers": power.centers,
|
| 191 |
+
"is_eliminated": power.is_eliminated(),
|
| 192 |
+
"order_status": self.game.get_order_status(name)
|
| 193 |
+
} for name, power in self.game.powers.items()},
|
| 194 |
+
"orders": self.game.get_orders(),
|
| 195 |
+
"active_powers": self.active_powers,
|
| 196 |
+
"is_game_done": self.game.is_game_done,
|
| 197 |
+
"outcome": self.game.outcome if self.game.is_game_done else None
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
def render(self, mode='human'):
|
| 201 |
+
"""Render the current state of the environment.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
mode: The rendering mode ('human', 'svg', etc.)
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
The rendered image if applicable
|
| 208 |
+
"""
|
| 209 |
+
self.render_mode = mode
|
| 210 |
+
if self.game:
|
| 211 |
+
if mode == 'human':
|
| 212 |
+
# Just print basic game state
|
| 213 |
+
print(f"Game: {self.game.game_id}")
|
| 214 |
+
print(f"Phase: {self.game.get_current_phase()}")
|
| 215 |
+
print(f"Active Powers: {self.active_powers}")
|
| 216 |
+
print("Supply Centers:")
|
| 217 |
+
for power_name, centers in self.game.get_centers().items():
|
| 218 |
+
print(f" {power_name}: {centers}")
|
| 219 |
+
print("Units:")
|
| 220 |
+
for power_name, units in self.game.get_units().items():
|
| 221 |
+
print(f" {power_name}: {units}")
|
| 222 |
+
return None
|
| 223 |
+
elif mode == 'svg':
|
| 224 |
+
# Return SVG representation
|
| 225 |
+
return self.game.render(output_format='svg')
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
def close(self):
|
| 229 |
+
"""Perform any necessary cleanup."""
|
| 230 |
+
self.game = None
|
src_code_for_reproducibility/markov_games/diplomacy/diplomacy_logging.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from utils.common_imports import *
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def diplomacy_log_match(
|
| 8 |
+
path,
|
| 9 |
+
agents_log_info,
|
| 10 |
+
env_log_info,
|
| 11 |
+
metrics_func=None,
|
| 12 |
+
metrics_func_args=None
|
| 13 |
+
):
|
| 14 |
+
"""
|
| 15 |
+
Logs the Diplomacy game data and generates HTML visualizations using the get_log_info methods.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
path (str): Base path to save the data.
|
| 19 |
+
agents_log_info (list): List of agent information dictionaries containing the get_log_info results.
|
| 20 |
+
env_log_info (dict): Environment information from its get_log_info method.
|
| 21 |
+
metrics_func (str, optional): Name of the function to calculate metrics.
|
| 22 |
+
metrics_func_args (dict, optional): Arguments for the metrics function.
|
| 23 |
+
"""
|
| 24 |
+
# Create directory structure
|
| 25 |
+
os.makedirs(path, exist_ok=True)
|
| 26 |
+
|
| 27 |
+
# Save the environment log info
|
| 28 |
+
env_log_path = os.path.join(path, "env_log.json")
|
| 29 |
+
with open(env_log_path, "w") as f:
|
| 30 |
+
json.dump(env_log_info, f, indent=4, default=_json_serialize)
|
| 31 |
+
|
| 32 |
+
# Process each agent's log info
|
| 33 |
+
for agent_log in agents_log_info:
|
| 34 |
+
power_name = agent_log["power_name"]
|
| 35 |
+
|
| 36 |
+
# Define paths for raw data and statistics subfolders
|
| 37 |
+
power_path = os.path.join(path, power_name)
|
| 38 |
+
raw_data_path = os.path.join(power_path, "raw_data")
|
| 39 |
+
statistics_path = os.path.join(power_path, "statistics")
|
| 40 |
+
|
| 41 |
+
# Ensure directories exist
|
| 42 |
+
os.makedirs(raw_data_path, exist_ok=True)
|
| 43 |
+
os.makedirs(statistics_path, exist_ok=True)
|
| 44 |
+
|
| 45 |
+
# Determine the next available file number for raw data
|
| 46 |
+
raw_files = os.listdir(raw_data_path)
|
| 47 |
+
raw_numbers = [int(f.split('_')[-1].split('.')[0]) for f in raw_files if f.startswith("log_")]
|
| 48 |
+
next_raw_number = max(raw_numbers, default=0) + 1
|
| 49 |
+
raw_file = os.path.join(raw_data_path, f"log_{next_raw_number}.json")
|
| 50 |
+
|
| 51 |
+
# Save agent log info
|
| 52 |
+
with open(raw_file, "w") as f:
|
| 53 |
+
json.dump(agent_log, f, indent=4, default=_json_serialize)
|
| 54 |
+
|
| 55 |
+
# Log metrics if a metrics function is provided
|
| 56 |
+
if metrics_func:
|
| 57 |
+
metrics_files = os.listdir(statistics_path)
|
| 58 |
+
metrics_numbers = [int(f.split('_')[-1].split('.')[0]) for f in metrics_files if f.startswith("metrics_")]
|
| 59 |
+
next_metrics_number = max(metrics_numbers, default=0) + 1
|
| 60 |
+
metrics_file = os.path.join(statistics_path, f"metrics_{next_metrics_number}.json")
|
| 61 |
+
|
| 62 |
+
metrics = globals()[metrics_func](agent_log, info, **metrics_func_args)
|
| 63 |
+
with open(metrics_file, "w") as f:
|
| 64 |
+
json.dump(metrics, f, indent=4)
|
| 65 |
+
|
| 66 |
+
# Generate the HTML visualization
|
| 67 |
+
html_content = generate_diplomacy_html(agents_log_info, env_log_info)
|
| 68 |
+
|
| 69 |
+
# Ensure the html directory exists
|
| 70 |
+
html_path = os.path.join(path, "html")
|
| 71 |
+
os.makedirs(html_path, exist_ok=True)
|
| 72 |
+
|
| 73 |
+
# Determine the next available file number for HTML
|
| 74 |
+
html_files = os.listdir(html_path)
|
| 75 |
+
html_numbers = [int(f.split('_')[-1].split('.')[0]) for f in html_files if f.startswith("game_summary_")]
|
| 76 |
+
next_html_number = max(html_numbers, default=0) + 1
|
| 77 |
+
html_file = os.path.join(html_path, f"game_summary_{next_html_number}.html")
|
| 78 |
+
|
| 79 |
+
# Save the HTML content to a file
|
| 80 |
+
with open(html_file, "w") as f:
|
| 81 |
+
f.write(html_content)
|
| 82 |
+
|
| 83 |
+
def generate_diplomacy_html(agent_infos, env_info):
|
| 84 |
+
"""
|
| 85 |
+
Generate HTML visualization for a Diplomacy game.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
agent_infos (list): List of agent information dictionaries from get_log_info.
|
| 89 |
+
env_info (dict): Environment information from get_log_info.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
str: HTML content for the game visualization.
|
| 93 |
+
"""
|
| 94 |
+
# Extract game information
|
| 95 |
+
game_id = env_info.get("game_id", "Unknown")
|
| 96 |
+
phase = env_info.get("phase", "Unknown")
|
| 97 |
+
map_name = env_info.get("map_name", "standard")
|
| 98 |
+
is_game_done = env_info.get("is_game_done", False)
|
| 99 |
+
outcome = env_info.get("outcome", [])
|
| 100 |
+
|
| 101 |
+
centers = env_info.get("centers", {})
|
| 102 |
+
units = env_info.get("units", {})
|
| 103 |
+
|
| 104 |
+
# HTML head and style
|
| 105 |
+
html_content = """
|
| 106 |
+
<!DOCTYPE html>
|
| 107 |
+
<html lang="en">
|
| 108 |
+
<head>
|
| 109 |
+
<meta charset="UTF-8">
|
| 110 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 111 |
+
<title>Diplomacy Game {game_id}</title>
|
| 112 |
+
<style>
|
| 113 |
+
body {{
|
| 114 |
+
font-family: 'Arial', sans-serif;
|
| 115 |
+
background-color: #f5f5f5;
|
| 116 |
+
color: #333333;
|
| 117 |
+
margin: 0;
|
| 118 |
+
padding: 20px;
|
| 119 |
+
}}
|
| 120 |
+
.container {{
|
| 121 |
+
display: grid;
|
| 122 |
+
grid-template-columns: repeat(3, 1fr);
|
| 123 |
+
grid-gap: 20px;
|
| 124 |
+
margin-bottom: 30px;
|
| 125 |
+
}}
|
| 126 |
+
.central-info {{
|
| 127 |
+
grid-column: span 3;
|
| 128 |
+
background: #fff;
|
| 129 |
+
padding: 20px;
|
| 130 |
+
border-radius: 10px;
|
| 131 |
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
| 132 |
+
margin-bottom: 20px;
|
| 133 |
+
}}
|
| 134 |
+
.power-column {{
|
| 135 |
+
background: #fff;
|
| 136 |
+
padding: 15px;
|
| 137 |
+
border-radius: 10px;
|
| 138 |
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
| 139 |
+
}}
|
| 140 |
+
.message {{
|
| 141 |
+
margin-bottom: 15px;
|
| 142 |
+
padding: 12px;
|
| 143 |
+
border-radius: 8px;
|
| 144 |
+
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
|
| 145 |
+
}}
|
| 146 |
+
.user {{
|
| 147 |
+
background: rgba(235, 245, 255, 0.8);
|
| 148 |
+
border-left: 4px solid #007bff;
|
| 149 |
+
}}
|
| 150 |
+
.assistant {{
|
| 151 |
+
background: rgba(240, 255, 240, 0.8);
|
| 152 |
+
border-right: 4px solid #28a745;
|
| 153 |
+
}}
|
| 154 |
+
.orders {{
|
| 155 |
+
background: rgba(255, 248, 225, 0.8);
|
| 156 |
+
border-left: 4px solid #ffc107;
|
| 157 |
+
}}
|
| 158 |
+
.role {{
|
| 159 |
+
font-weight: bold;
|
| 160 |
+
margin-bottom: 5px;
|
| 161 |
+
color: #333333;
|
| 162 |
+
}}
|
| 163 |
+
.power-name {{
|
| 164 |
+
text-align: center;
|
| 165 |
+
font-size: 1.4em;
|
| 166 |
+
margin-bottom: 15px;
|
| 167 |
+
color: #000;
|
| 168 |
+
font-weight: 600;
|
| 169 |
+
text-transform: uppercase;
|
| 170 |
+
letter-spacing: 1px;
|
| 171 |
+
}}
|
| 172 |
+
.game-info {{
|
| 173 |
+
display: grid;
|
| 174 |
+
grid-template-columns: repeat(2, 1fr);
|
| 175 |
+
grid-gap: 15px;
|
| 176 |
+
}}
|
| 177 |
+
.info-card {{
|
| 178 |
+
background: #f9f9f9;
|
| 179 |
+
padding: 15px;
|
| 180 |
+
border-radius: 8px;
|
| 181 |
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
| 182 |
+
}}
|
| 183 |
+
.supply-centers, .units-list {{
|
| 184 |
+
display: flex;
|
| 185 |
+
flex-wrap: wrap;
|
| 186 |
+
justify-content: space-between;
|
| 187 |
+
}}
|
| 188 |
+
.supply-center, .unit {{
|
| 189 |
+
flex: 0 0 30%;
|
| 190 |
+
margin-bottom: 10px;
|
| 191 |
+
padding: 8px;
|
| 192 |
+
background: #f0f0f0;
|
| 193 |
+
border-radius: 5px;
|
| 194 |
+
text-align: center;
|
| 195 |
+
}}
|
| 196 |
+
h2 {{
|
| 197 |
+
border-bottom: 2px solid #eee;
|
| 198 |
+
padding-bottom: 10px;
|
| 199 |
+
margin-top: 0;
|
| 200 |
+
}}
|
| 201 |
+
.outcome {{
|
| 202 |
+
background: #e8f5e9;
|
| 203 |
+
padding: 15px;
|
| 204 |
+
border-radius: 8px;
|
| 205 |
+
margin-top: 15px;
|
| 206 |
+
font-weight: bold;
|
| 207 |
+
text-align: center;
|
| 208 |
+
}}
|
| 209 |
+
.austria {{ border-top: 5px solid #ff5050; }}
|
| 210 |
+
.england {{ border-top: 5px solid #5050ff; }}
|
| 211 |
+
.france {{ border-top: 5px solid #50c0ff; }}
|
| 212 |
+
.germany {{ border-top: 5px solid #808080; }}
|
| 213 |
+
.italy {{ border-top: 5px solid #50ff50; }}
|
| 214 |
+
.russia {{ border-top: 5px solid #ffffff; border: 1px solid #ccc; }}
|
| 215 |
+
.turkey {{ border-top: 5px solid #c0c000; }}
|
| 216 |
+
</style>
|
| 217 |
+
</head>
|
| 218 |
+
<body>
|
| 219 |
+
<div class="central-info">
|
| 220 |
+
<h2>Game Information</h2>
|
| 221 |
+
<div class="game-info">
|
| 222 |
+
<div class="info-card">
|
| 223 |
+
<h3>Game Details</h3>
|
| 224 |
+
<p><strong>Game ID:</strong> {game_id}</p>
|
| 225 |
+
<p><strong>Phase:</strong> {phase}</p>
|
| 226 |
+
<p><strong>Map:</strong> {map_name}</p>
|
| 227 |
+
<p><strong>Status:</strong> {status}</p>
|
| 228 |
+
</div>
|
| 229 |
+
<div class="info-card">
|
| 230 |
+
<h3>Supply Centers</h3>
|
| 231 |
+
<div class="supply-centers">
|
| 232 |
+
""".format(
|
| 233 |
+
game_id=game_id,
|
| 234 |
+
phase=phase,
|
| 235 |
+
map_name=map_name,
|
| 236 |
+
status="Completed" if is_game_done else "Active"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# Add supply center information
|
| 240 |
+
for power, power_centers in centers.items():
|
| 241 |
+
html_content += f"""
|
| 242 |
+
<div class="supply-center">
|
| 243 |
+
<strong>{power}:</strong> {len(power_centers)}
|
| 244 |
+
</div>
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
html_content += """
|
| 248 |
+
</div>
|
| 249 |
+
</div>
|
| 250 |
+
</div>
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
# Add outcome if game is done
|
| 254 |
+
if is_game_done and outcome:
|
| 255 |
+
winners = outcome[1:] if len(outcome) > 1 else ["Draw"]
|
| 256 |
+
html_content += f"""
|
| 257 |
+
<div class="outcome">
|
| 258 |
+
<h3>Game Outcome</h3>
|
| 259 |
+
<p>Winners: {', '.join(winners)}</p>
|
| 260 |
+
</div>
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
html_content += """
|
| 264 |
+
</div>
|
| 265 |
+
<div class="container">
|
| 266 |
+
"""
|
| 267 |
+
|
| 268 |
+
# Add each power's information
|
| 269 |
+
for agent_log in agent_infos:
|
| 270 |
+
power_name = agent_log["power_name"]
|
| 271 |
+
power_class = power_name.lower()
|
| 272 |
+
orders = agent_log.get("orders", [])
|
| 273 |
+
message_history = agent_log.get("message_history", [])
|
| 274 |
+
|
| 275 |
+
html_content += f"""
|
| 276 |
+
<div class="power-column {power_class}">
|
| 277 |
+
<div class="power-name">{power_name}</div>
|
| 278 |
+
|
| 279 |
+
<div class="info-card">
|
| 280 |
+
<h3>Units</h3>
|
| 281 |
+
<ul>
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
# Add units information
|
| 285 |
+
power_units = units.get(power_name, [])
|
| 286 |
+
for unit in power_units:
|
| 287 |
+
html_content += f"<li>{unit}</li>"
|
| 288 |
+
|
| 289 |
+
html_content += """
|
| 290 |
+
</ul>
|
| 291 |
+
</div>
|
| 292 |
+
|
| 293 |
+
<div class="message orders">
|
| 294 |
+
<div class="role">Final Orders</div>
|
| 295 |
+
<ul>
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
# Add orders
|
| 299 |
+
for order in orders:
|
| 300 |
+
html_content += f"<li>{order}</li>"
|
| 301 |
+
|
| 302 |
+
html_content += """
|
| 303 |
+
</ul>
|
| 304 |
+
</div>
|
| 305 |
+
"""
|
| 306 |
+
|
| 307 |
+
# Add message history
|
| 308 |
+
for message in message_history:
|
| 309 |
+
if isinstance(message, dict):
|
| 310 |
+
# Skip system messages or handle differently
|
| 311 |
+
if message.get("role") == "system":
|
| 312 |
+
continue
|
| 313 |
+
|
| 314 |
+
role = message.get("role", "unknown")
|
| 315 |
+
content = message.get("content", "")
|
| 316 |
+
|
| 317 |
+
role_class = "user" if role == "user" else "assistant"
|
| 318 |
+
role_display = "Environment" if role == "user" else f"LLM ({power_name})"
|
| 319 |
+
|
| 320 |
+
# Escape HTML characters in content
|
| 321 |
+
content = content.replace("<", "<").replace(">", ">").replace("\n", "<br>")
|
| 322 |
+
|
| 323 |
+
html_content += f"""
|
| 324 |
+
<div class="message {role_class}">
|
| 325 |
+
<div class="role">{role_display}</div>
|
| 326 |
+
<p>{content}</p>
|
| 327 |
+
</div>
|
| 328 |
+
"""
|
| 329 |
+
elif isinstance(message, str):
|
| 330 |
+
# Simple string messages (may be used in some implementations)
|
| 331 |
+
html_content += f"""
|
| 332 |
+
<div class="message">
|
| 333 |
+
<p>{message}</p>
|
| 334 |
+
</div>
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
html_content += """
|
| 338 |
+
</div>
|
| 339 |
+
"""
|
| 340 |
+
|
| 341 |
+
html_content += """
|
| 342 |
+
</div>
|
| 343 |
+
</body>
|
| 344 |
+
</html>
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
return html_content
|
| 348 |
+
|
| 349 |
+
def _json_serialize(obj):
|
| 350 |
+
"""
|
| 351 |
+
A helper function to convert non-JSON-serializable objects
|
| 352 |
+
(like OrderResult) into strings or dicts.
|
| 353 |
+
"""
|
| 354 |
+
# Check for the specific object types you know are problematic
|
| 355 |
+
if obj.__class__.__name__ == "OrderResult":
|
| 356 |
+
# Return a string representation or a dict
|
| 357 |
+
return str(obj)
|
| 358 |
+
|
| 359 |
+
# Fallback: attempt to convert anything else to string
|
| 360 |
+
return str(obj)
|
src_code_for_reproducibility/markov_games/diplomacy/diplomacy_logging_for_training.py
ADDED
|
File without changes
|
src_code_for_reproducibility/markov_games/ipd/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .Ipd_hard_coded_agents import AlwaysCooperateIPDAgent, AlwaysDefectIPDAgent
|
| 2 |
+
|
| 3 |
+
__all__ = [
|
| 4 |
+
"AlwaysCooperateIPDAgent",
|
| 5 |
+
"AlwaysDefectIPDAgent",
|
| 6 |
+
]
|
| 7 |
+
|
src_code_for_reproducibility/markov_games/ipd/__pycache__/Ipd_hard_coded_agents.cpython-312.pyc
ADDED
|
Binary file (2.86 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (308 Bytes). View file
|
|
|
src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_agent.cpython-312.pyc
ADDED
|
Binary file (4.7 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_simulation.cpython-312.pyc
ADDED
|
Binary file (6.72 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_statistics.cpython-312.pyc
ADDED
|
Binary file (1.28 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/ipd/ipd_agent.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
import random
|
| 4 |
+
import re
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
from copy import deepcopy
|
| 7 |
+
from dataclasses import dataclass, field
|
| 8 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 9 |
+
|
| 10 |
+
from mllm.markov_games.agent import Agent
|
| 11 |
+
from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class IPDAgentState:
|
| 16 |
+
"""
|
| 17 |
+
TOWRITE
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
nb_retries: int
|
| 21 |
+
round_nb: int
|
| 22 |
+
chat_counter: int
|
| 23 |
+
chat_history: List[ChatTurn]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class IPDAgent(Agent):
|
| 28 |
+
seed: int
|
| 29 |
+
agent_id: str
|
| 30 |
+
agent_name: str
|
| 31 |
+
policy: Callable[[List[Dict]], str]
|
| 32 |
+
intro_prompt: str # Introduction prompt explaining the game rules
|
| 33 |
+
goal_prompt: str # Prompt explaining the agent's goal
|
| 34 |
+
strategy_prompt: str # Prompt suggesting a strategy to the agent
|
| 35 |
+
max_errors: int # Maximum number of errors allowed before default action
|
| 36 |
+
allow_reasoning: bool # Whether to allow reasoning in the response
|
| 37 |
+
max_reasoning_chars: int # Maximum number of characters for reasoning
|
| 38 |
+
cooperate_string: str # string parsed as playing cooperate by simulation
|
| 39 |
+
defect_string: str # string parsed as playing defect by simulation
|
| 40 |
+
|
| 41 |
+
def __post_init__(self):
|
| 42 |
+
self.state = IPDAgentState(
|
| 43 |
+
nb_retries=0, round_nb=0, chat_counter=0, chat_history=[]
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
async def act(self, observation) -> Tuple[Any, AgentActLog]:
|
| 47 |
+
"""
|
| 48 |
+
TOWRITE
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
action = None
|
| 52 |
+
action_is_ready = False
|
| 53 |
+
round_nb = observation.round_nb
|
| 54 |
+
|
| 55 |
+
# If it's the first round, we need to send the intro prompt
|
| 56 |
+
if round_nb == 0 and self.state.chat_counter == 0:
|
| 57 |
+
self.state.chat_history.append(
|
| 58 |
+
ChatTurn(
|
| 59 |
+
agent_id=self.agent_id,
|
| 60 |
+
role="user",
|
| 61 |
+
content=self.intro_prompt,
|
| 62 |
+
is_state_end=True,
|
| 63 |
+
)
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# If new round
|
| 67 |
+
if round_nb > self.state.round_nb:
|
| 68 |
+
coagent_action = observation.last_coagent_move
|
| 69 |
+
user_message = f"Last round, the other agent played {coagent_action}."
|
| 70 |
+
self.state.chat_history.append(
|
| 71 |
+
ChatTurn(
|
| 72 |
+
agent_id=self.agent_id,
|
| 73 |
+
role="user",
|
| 74 |
+
content=user_message,
|
| 75 |
+
is_state_end=True,
|
| 76 |
+
)
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# If not new round, try to get valid action from policy
|
| 80 |
+
output_chat_turn: ChatTurn = await self.policy(
|
| 81 |
+
state=self.state.chat_history,
|
| 82 |
+
agent_id=self.agent_id,
|
| 83 |
+
regex=f"({self.cooperate_string}|{self.defect_string})",
|
| 84 |
+
)
|
| 85 |
+
self.state.chat_history.append(output_chat_turn)
|
| 86 |
+
action = output_chat_turn.content
|
| 87 |
+
|
| 88 |
+
agent_step_log = AgentActLog(
|
| 89 |
+
chat_turns=self.state.chat_history[self.state.chat_counter :], info=None
|
| 90 |
+
)
|
| 91 |
+
self.state.chat_counter = len(self.state.chat_history)
|
| 92 |
+
self.state.round_nb = round_nb
|
| 93 |
+
|
| 94 |
+
return action, agent_step_log
|
| 95 |
+
|
| 96 |
+
def get_safe_copy(self):
|
| 97 |
+
"""
|
| 98 |
+
Return a safe copy of the agent.
|
| 99 |
+
"""
|
| 100 |
+
agent_copy = copy.copy(self)
|
| 101 |
+
agent_copy.state = copy.deepcopy(self.state)
|
| 102 |
+
return agent_copy
|
| 103 |
+
|
| 104 |
+
def reset(self):
|
| 105 |
+
self.state = IPDAgentState()
|
| 106 |
+
raise NotImplementedError
|
| 107 |
+
|
| 108 |
+
def render(self):
|
| 109 |
+
pass
|
| 110 |
+
|
| 111 |
+
def close(self):
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
def get_agent_info(self):
|
| 115 |
+
pass
|
src_code_for_reproducibility/markov_games/ipd/ipd_simulation.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import random
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from mllm.markov_games.markov_game import Simulation
|
| 9 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 10 |
+
from mllm.utils.get_coagent_id import get_coagent_id
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class IPDState:
|
| 15 |
+
"""
|
| 16 |
+
State of the Iterated Prisoner's Dilemma game.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
round_nb: int = 0
|
| 20 |
+
done: bool = False
|
| 21 |
+
last_moves: Dict[str, str] | None = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class IPDObs:
|
| 26 |
+
"""
|
| 27 |
+
Observation in Iterated Prisoner's Dilemma game.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
round_nb: int
|
| 31 |
+
last_coagent_move: str | None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class IPD(Simulation):
|
| 35 |
+
"""
|
| 36 |
+
Iterated Prisoner's Dilemma simulation following the standard.
|
| 37 |
+
|
| 38 |
+
In each round of the game, two agents simultaneously choose to either cooperate (C) or defect (D).
|
| 39 |
+
The payoffs are as follows:
|
| 40 |
+
- If both cooperate: Both receive the "reward" (usually 3 points)
|
| 41 |
+
- If both defect: Both receive the "punishment" (usually 1 point)
|
| 42 |
+
- If one cooperates and one defects: The defector receives the "temptation" (usually 5 points)
|
| 43 |
+
and the cooperator receives the "sucker" payoff (usually 0 points)
|
| 44 |
+
|
| 45 |
+
The game is played for a specified number of rounds.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
agent_ids: List[str],
|
| 51 |
+
agent_names: List[str],
|
| 52 |
+
seed: int,
|
| 53 |
+
rounds_per_game: int,
|
| 54 |
+
reward: float, # Both cooperate
|
| 55 |
+
punishment: float, # Both defect
|
| 56 |
+
temptation: float, # Defector's reward when other cooperates
|
| 57 |
+
sucker: float, # Cooperator's reward when other defects
|
| 58 |
+
cooperate_actions: List[str],
|
| 59 |
+
defect_actions: List[str],
|
| 60 |
+
):
|
| 61 |
+
self.agent_ids = agent_ids
|
| 62 |
+
self.agent_names = agent_names
|
| 63 |
+
self.seed = seed
|
| 64 |
+
self.rounds_per_game = rounds_per_game
|
| 65 |
+
self.reward = reward
|
| 66 |
+
self.punishment = punishment
|
| 67 |
+
self.temptation = temptation
|
| 68 |
+
self.sucker = sucker
|
| 69 |
+
self.cooperate_actions = cooperate_actions
|
| 70 |
+
self.defect_actions = defect_actions
|
| 71 |
+
self.state = IPDState()
|
| 72 |
+
|
| 73 |
+
def step(self, actions: Dict[str, str]) -> Tuple[bool, SimulationStepLog]:
|
| 74 |
+
"""
|
| 75 |
+
Take a step in the environment using the provided actions.
|
| 76 |
+
Here, the observations are just the states of the game.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
actions (dict): A dictionary where keys are agent identifiers and values are actions ('C' or 'D').
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
observations (dict): A dictionary where keys are agent identifiers and values are observations.
|
| 83 |
+
done (bool): Whether the episode has ended.
|
| 84 |
+
info (dict): Additional information about the environment.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
# Calculate rewards using payoff matrix
|
| 88 |
+
agent0_action = actions[self.agent_ids[0]]
|
| 89 |
+
agent1_action = actions[self.agent_ids[1]]
|
| 90 |
+
|
| 91 |
+
# Normalize actions to standard cooperate/defect/gibberish format
|
| 92 |
+
def normalize_action(action):
|
| 93 |
+
if action in self.cooperate_actions:
|
| 94 |
+
return "C"
|
| 95 |
+
elif action in self.defect_actions:
|
| 96 |
+
return "D"
|
| 97 |
+
else:
|
| 98 |
+
return "D"
|
| 99 |
+
|
| 100 |
+
norm_action0 = normalize_action(agent0_action)
|
| 101 |
+
norm_action1 = normalize_action(agent1_action)
|
| 102 |
+
|
| 103 |
+
payoffs = {
|
| 104 |
+
("C", "C"): [self.reward, self.reward],
|
| 105 |
+
("C", "D"): [self.sucker, self.temptation],
|
| 106 |
+
("D", "C"): [self.temptation, self.sucker],
|
| 107 |
+
("D", "D"): [self.punishment, self.punishment],
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
round_rewards = {
|
| 111 |
+
self.agent_ids[0]: payoffs[(norm_action0, norm_action1)][0],
|
| 112 |
+
self.agent_ids[1]: payoffs[(norm_action0, norm_action1)][1],
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
# Update game state
|
| 116 |
+
self.state.round_nb += 1
|
| 117 |
+
self.state.last_moves = copy.deepcopy(actions)
|
| 118 |
+
done = self.state.round_nb >= self.rounds_per_game
|
| 119 |
+
step_log = SimulationStepLog(
|
| 120 |
+
rewards=round_rewards,
|
| 121 |
+
info={
|
| 122 |
+
"actions": {
|
| 123 |
+
self.agent_ids[0]: norm_action0,
|
| 124 |
+
self.agent_ids[1]: norm_action1,
|
| 125 |
+
}
|
| 126 |
+
},
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
return done, step_log
|
| 130 |
+
|
| 131 |
+
def get_obs(self):
|
| 132 |
+
"""Returns all agent observations in dict
|
| 133 |
+
Returns:
|
| 134 |
+
observations
|
| 135 |
+
"""
|
| 136 |
+
observations = {}
|
| 137 |
+
for agent_id in self.agent_ids:
|
| 138 |
+
observations[agent_id] = self.get_obs_agent(agent_id)
|
| 139 |
+
return observations
|
| 140 |
+
|
| 141 |
+
def get_obs_agent(self, agent_id):
|
| 142 |
+
"""Returns observation for agent_id"""
|
| 143 |
+
if self.state.last_moves != None:
|
| 144 |
+
other_id = get_coagent_id(self.agent_ids, agent_id)
|
| 145 |
+
last_coagent_move = self.state.last_moves[other_id]
|
| 146 |
+
else:
|
| 147 |
+
last_coagent_move = None
|
| 148 |
+
obs = IPDObs(round_nb=self.state.round_nb, last_coagent_move=last_coagent_move)
|
| 149 |
+
return obs
|
| 150 |
+
|
| 151 |
+
def reset(self):
|
| 152 |
+
"""Returns initial observations and states"""
|
| 153 |
+
self.state = IPDState()
|
| 154 |
+
return self.get_obs()
|
| 155 |
+
|
| 156 |
+
def get_safe_copy(self):
|
| 157 |
+
"""
|
| 158 |
+
Return a safe copy of the simulation.
|
| 159 |
+
"""
|
| 160 |
+
simulation_copy = copy.copy(self)
|
| 161 |
+
simulation_copy.state = copy.deepcopy(self.state)
|
| 162 |
+
return simulation_copy
|
src_code_for_reproducibility/markov_games/ipd/ipd_statistics.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Dict, Callable, List, Tuple
|
| 4 |
+
|
| 5 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def avg_reward(sl: SimulationStepLog) -> List[Tuple[str, float]]:
|
| 9 |
+
for aid in sl.rewards.keys():
|
| 10 |
+
if "buffer" in str(aid) and "live" not in str(aid):
|
| 11 |
+
return None
|
| 12 |
+
# One value per agent at each step
|
| 13 |
+
rewards_dict = {f"reward-{aid}": float(v) for aid, v in (sl.rewards or {}).items()}
|
| 14 |
+
return [(key, value) for key, value in rewards_dict.items() if value is not None]
|
| 15 |
+
|
| 16 |
+
stat_functs: list[Callable[[SimulationStepLog], List[Tuple[str, float]]]] = [
|
| 17 |
+
avg_reward,
|
| 18 |
+
]
|
src_code_for_reproducibility/markov_games/negotiation/README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Negotiation Games: core mechanics and variants
|
| 2 |
+
|
| 3 |
+
This family of games feature two agents who, in each round, may briefly communicate and then simultaneously propose how to split a fixed resource (most commonly 10 coins). Rewards are the amount kept multiplied by an agent’s per-unit value. The starting speaker alternates deterministically across rounds.
|
| 4 |
+
|
| 5 |
+
Communication is optional and variant-dependent: some settings encourage rich messaging to share private information, while others remove messaging entirely to focus on allocation behavior.
|
| 6 |
+
|
| 7 |
+
Proportional splitting is used when the two proposals exceed the available total: allocations are scaled proportionally rather than discarded. This preserves a useful learning signal even when agents over-claim.
|
| 8 |
+
|
| 9 |
+
### Variants (in increasing difficulty)
|
| 10 |
+
|
| 11 |
+
- No‑Press Split
|
| 12 |
+
- Single item type (coins)
|
| 13 |
+
- No communication; agents go straight to making split proposals, with the starting player alternating deterministically.
|
| 14 |
+
- Motivation: mirrors no‑communication setups (e.g., Advantage Alignment) while keeping the split decision nontrivial.
|
| 15 |
+
- Deterministic Mode: values are fixed and public: one agent values coins at 10, the other at 1 (alternates each round).
|
| 16 |
+
- Stochastic Mode: values are random and uncorrelated.
|
| 17 |
+
|
| 18 |
+
- Trust-and-Split RPS (TAS-RPS)
|
| 19 |
+
- Single item type (coins)
|
| 20 |
+
- Each round, a rock–paper–scissors hand draw creates a strong asymmetry: the winner’s per-coin value is 10, the loser’s is 1.
|
| 21 |
+
- Each agent initially sees only their own hand and must communicate to coordinate an optimal split.
|
| 22 |
+
- Motivation: enforce large value disparity so one’s own value reveals little about the other’s (avoiding ceiling effects) and incentivize meaningful communication.
|
| 23 |
+
|
| 24 |
+
- Trust-and-Split (TAS)
|
| 25 |
+
- Single item type (coins); each round, each agent’s per-coin value is independently sampled in a broad range (e.g., 1–20).
|
| 26 |
+
- Each agent observes only their own value; they may use short messages to share and negotiate.
|
| 27 |
+
- Motivation: a simple blend that tests whether agents learn to exchange private information and coordinate proportional, value-aware splits.
|
| 28 |
+
|
| 29 |
+
- Deal-or-No-Deal (DOND)
|
| 30 |
+
- Introduced in [Deal or No Deal? End-to-End Learning for Negotiation Dialogues](https://arxiv.org/pdf/1706.05125)
|
| 31 |
+
- Multiple item types (typically "books", "hats" and "balls") with limited stocks; each agent has its own per-type values.
|
| 32 |
+
- A deal pays out only if both proposals exactly agree and respect the stock; otherwise no deal (zero reward) that round.
|
| 33 |
+
- Motivation: a known benchmark closer to real-world bargaining, where both parties must explicitly agree.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_agent.cpython-312.pyc
ADDED
|
Binary file (4.19 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_simulation.cpython-312.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_agent.cpython-312.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_hard_coded_policies.cpython-312.pyc
ADDED
|
Binary file (3.23 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_simulation.cpython-312.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/negotiation_statistics.cpython-312.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_agent.cpython-312.pyc
ADDED
|
Binary file (5.5 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_simulation.cpython-312.pyc
ADDED
|
Binary file (9.06 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_agent.cpython-312.pyc
ADDED
|
Binary file (6.14 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_agent.cpython-312.pyc
ADDED
|
Binary file (5.59 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_simulation.cpython-312.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_simple_agent.cpython-312.pyc
ADDED
|
Binary file (4.89 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_simple_simulation.cpython-312.pyc
ADDED
|
Binary file (8.68 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_simulation.cpython-312.pyc
ADDED
|
Binary file (9.03 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/negotiation/dond_agent.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import re
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any, Dict, List, Tuple
|
| 6 |
+
|
| 7 |
+
from mllm.markov_games.agent import Agent
|
| 8 |
+
from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
|
| 9 |
+
from mllm.markov_games.negotiation.dond_simulation import (
|
| 10 |
+
DealNoDealObs,
|
| 11 |
+
)
|
| 12 |
+
from mllm.markov_games.negotiation.nego_simulation import Split
|
| 13 |
+
from mllm.markov_games.negotiation.nego_agent import NegotiationAgent, NegotiationAgentState
|
| 14 |
+
|
| 15 |
+
class DealNoDealAgent(NegotiationAgent):
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
*args,
|
| 19 |
+
**kwargs,
|
| 20 |
+
):
|
| 21 |
+
super().__init__(*args, **kwargs)
|
| 22 |
+
self.intro_prompt = (
|
| 23 |
+
"You are {agent_id}. You are playing an iterated game. "
|
| 24 |
+
"At each round, you and other agent will try to distribute among yourselves items of types {item_types}. "
|
| 25 |
+
"You only know how much you value each item type, but not the other agent's values. "
|
| 26 |
+
"You can communicate with the other agent by sending up to {quota_messages_per_agent_per_round} short messages per round. "
|
| 27 |
+
"Each round, after exchanging messages, you and the other agent will submit a private proposal. "
|
| 28 |
+
"A deal is accepted only if both proposals match exactly and are within stock; otherwise no deal (0 points for both at that round). "
|
| 29 |
+
"The values of the items of the other agent at the previous round are revealed to you after each round. "
|
| 30 |
+
"Your goal is: {goal}."
|
| 31 |
+
)
|
| 32 |
+
self.new_round_prompt = ("New round {round_nb}. Items: {stock}. Your values: {values}. ")
|
| 33 |
+
self.last_round_prompt = ("Last round, other agent's values: {previous_values_coagent}. ")
|
| 34 |
+
self.send_split_prompt = ("Respond with <split>...</split> where you propose how many items of each type you want to keep.")
|
| 35 |
+
|
| 36 |
+
def get_message_regex(self, observation: DealNoDealObs) -> str:
|
| 37 |
+
return r"<message>[\s\S]{0,400}</message>"
|
| 38 |
+
|
| 39 |
+
def get_split_regex(self, observation: DealNoDealObs) -> str:
|
| 40 |
+
parts = []
|
| 41 |
+
for t in observation.item_types:
|
| 42 |
+
s = int(observation.quantities.get(t, 0))
|
| 43 |
+
allowed = "|".join(str(k) for k in range(0, s + 1))
|
| 44 |
+
rng = f"({allowed})"
|
| 45 |
+
parts.append(fr"<{t}>{rng}</{t}>")
|
| 46 |
+
items_block = "".join(parts)
|
| 47 |
+
return fr"(<split>{items_block}</split>)"
|
| 48 |
+
|
| 49 |
+
def get_split_action(self, policy_output: str, observation: DealNoDealObs) -> Split:
|
| 50 |
+
import re as _re
|
| 51 |
+
allocations: Dict[str, int] = {}
|
| 52 |
+
for t in observation.item_types:
|
| 53 |
+
m = _re.search(fr"<{t}>([0-9]+)</{t}>", policy_output)
|
| 54 |
+
if m:
|
| 55 |
+
allocations[t] = int(m.group(1))
|
| 56 |
+
else:
|
| 57 |
+
allocations[t] = 0
|
| 58 |
+
return Split(items_given_to_self=allocations)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|
src_code_for_reproducibility/markov_games/negotiation/nego_simulation.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Negotiation simulation environment
|
| 3 |
+
other agent is set at the start of every round. Even though current agent changes over message turns in a round.
|
| 4 |
+
"""
|
| 5 |
+
import copy
|
| 6 |
+
from abc import abstractmethod
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Dict, List, Tuple
|
| 9 |
+
|
| 10 |
+
from numpy.random import default_rng
|
| 11 |
+
|
| 12 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 13 |
+
from mllm.markov_games.simulation import Simulation
|
| 14 |
+
from mllm.utils.get_coagent_id import get_coagent_id
|
| 15 |
+
|
| 16 |
+
AgentId = str
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class Split:
|
| 21 |
+
items_given_to_self: Dict[str, int]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class Message:
|
| 26 |
+
message: str
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass # gets extended by variants
|
| 30 |
+
class NegotiationState:
|
| 31 |
+
round_nb: int
|
| 32 |
+
last_message: str
|
| 33 |
+
current_agent: AgentId
|
| 34 |
+
quantities: Dict[str, int]
|
| 35 |
+
values: Dict[AgentId, Dict[str, float]]
|
| 36 |
+
splits: Dict[AgentId, Split | None]
|
| 37 |
+
nb_messages_sent: Dict[AgentId, int]
|
| 38 |
+
previous_values: Dict[AgentId, Dict[str, float]] | None
|
| 39 |
+
previous_splits: Dict[AgentId, Dict[str, int] | None] | None
|
| 40 |
+
previous_points: Dict[AgentId, float] | None
|
| 41 |
+
previous_quantities: Dict[str, int] | None
|
| 42 |
+
split_phase: bool
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass # gets extended by variants
|
| 46 |
+
class NegotiationObs:
|
| 47 |
+
round_nb: int
|
| 48 |
+
last_message: str
|
| 49 |
+
quota_messages_per_agent_per_round: int
|
| 50 |
+
current_agent: AgentId
|
| 51 |
+
other_agent: str
|
| 52 |
+
quantities: Dict[str, int]
|
| 53 |
+
item_types: List[str]
|
| 54 |
+
value: Dict[str, int]
|
| 55 |
+
split_phase: bool
|
| 56 |
+
last_split_agent: Dict[str, int] | None
|
| 57 |
+
last_value_agent: Dict[str, int] | None
|
| 58 |
+
last_points_agent: float | None
|
| 59 |
+
last_split_coagent: Dict[str, int] | None
|
| 60 |
+
last_value_coagent: Dict[str, int] | None
|
| 61 |
+
last_points_coagent: float | None
|
| 62 |
+
last_quantities: Dict[str, int] | None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def compute_tas_style_rewards(
|
| 66 |
+
agent_ids: List[AgentId],
|
| 67 |
+
values: Dict[AgentId, float],
|
| 68 |
+
splits: Dict[AgentId, Split],
|
| 69 |
+
quantities: Dict[str, int],
|
| 70 |
+
) -> Dict[AgentId, float]:
|
| 71 |
+
"""
|
| 72 |
+
TAS-like reward computation: if sum of proposed coins exceeds max_coins,
|
| 73 |
+
allocate proportionally. Otherwise, use proposed amounts directly.
|
| 74 |
+
Rewards are quantity_kept * per-coin value for each agent.
|
| 75 |
+
"""
|
| 76 |
+
a0, a1 = agent_ids[0], agent_ids[1]
|
| 77 |
+
r0, r1 = 0.0, 0.0
|
| 78 |
+
|
| 79 |
+
for item in quantities:
|
| 80 |
+
max_item = quantities[item]
|
| 81 |
+
item_to_self_0 = int(
|
| 82 |
+
(splits[a0].items_given_to_self.get(item, 0))
|
| 83 |
+
if splits[a0] is not None
|
| 84 |
+
else 0
|
| 85 |
+
)
|
| 86 |
+
item_to_self_1 = int(
|
| 87 |
+
(splits[a1].items_given_to_self.get(item, 0))
|
| 88 |
+
if splits[a1] is not None
|
| 89 |
+
else 0
|
| 90 |
+
)
|
| 91 |
+
denom = max(int(max_item), item_to_self_0 + item_to_self_1)
|
| 92 |
+
q0 = float(max_item) * float(item_to_self_0) / float(denom)
|
| 93 |
+
q1 = float(max_item) * float(item_to_self_1) / float(denom)
|
| 94 |
+
if type(values[a0]) is not dict:
|
| 95 |
+
r0 += q0 * float(values[a0])
|
| 96 |
+
r1 += q1 * float(values[a1])
|
| 97 |
+
else:
|
| 98 |
+
r0 += q0 * float(values[a0][item])
|
| 99 |
+
r1 += q1 * float(values[a1][item])
|
| 100 |
+
return {a0: r0, a1: r1}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class NegotiationSimulation(Simulation):
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
agent_ids: List[AgentId],
|
| 107 |
+
agent_names: List[str],
|
| 108 |
+
seed: int,
|
| 109 |
+
nb_of_rounds: int,
|
| 110 |
+
quota_messages_per_agent_per_round: int,
|
| 111 |
+
item_types: List[str] | None = None,
|
| 112 |
+
):
|
| 113 |
+
self.seed = seed
|
| 114 |
+
self.rng = default_rng(self.seed)
|
| 115 |
+
self.agent_ids = list(agent_ids)
|
| 116 |
+
self.agent_names = agent_names
|
| 117 |
+
self.agent_id_to_name = {
|
| 118 |
+
agent_id: agent_name for agent_id, agent_name in zip(agent_ids, agent_names)
|
| 119 |
+
}
|
| 120 |
+
self.nb_of_rounds = int(nb_of_rounds)
|
| 121 |
+
self.quota_messages_per_agent_per_round = int(
|
| 122 |
+
quota_messages_per_agent_per_round
|
| 123 |
+
)
|
| 124 |
+
if item_types is not None:
|
| 125 |
+
self.item_types = [item.lower() for item in item_types]
|
| 126 |
+
else:
|
| 127 |
+
self.item_types = ["coins"]
|
| 128 |
+
self.state: NegotiationState | None = None
|
| 129 |
+
self._starting_agent_index = self.rng.choice([0, 1])
|
| 130 |
+
self.reset()
|
| 131 |
+
|
| 132 |
+
def _other(self, agent_id: AgentId) -> AgentId:
|
| 133 |
+
return get_coagent_id(self.agent_ids, agent_id)
|
| 134 |
+
|
| 135 |
+
@abstractmethod
|
| 136 |
+
def set_new_round_of_variant(self):
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
@abstractmethod
|
| 140 |
+
def get_info_of_variant(
|
| 141 |
+
self, state: NegotiationState, actions: Dict[AgentId, Any]
|
| 142 |
+
) -> Dict[str, Any]:
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
def step(self, actions: Any) -> Tuple[bool, SimulationStepLog]:
|
| 146 |
+
"""
|
| 147 |
+
Returns terminated, step_log
|
| 148 |
+
"""
|
| 149 |
+
assert self.state is not None
|
| 150 |
+
current_agent = self.state.current_agent
|
| 151 |
+
a0, a1 = self.agent_ids[0], self.agent_ids[1]
|
| 152 |
+
action = actions.get(current_agent)
|
| 153 |
+
|
| 154 |
+
# Split phase: require both splits in the same timestep
|
| 155 |
+
if self.state.split_phase:
|
| 156 |
+
action_a0 = actions.get(a0)
|
| 157 |
+
action_a1 = actions.get(a1)
|
| 158 |
+
have_both_splits = isinstance(action_a0, Split) and isinstance(
|
| 159 |
+
action_a1, Split
|
| 160 |
+
)
|
| 161 |
+
if not have_both_splits:
|
| 162 |
+
rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
|
| 163 |
+
return False, SimulationStepLog(
|
| 164 |
+
rewards=rewards, info={"type": "waiting_for_splits"}
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Record splits
|
| 168 |
+
self.state.splits[a0] = action_a0
|
| 169 |
+
self.state.splits[a1] = action_a1
|
| 170 |
+
|
| 171 |
+
# Compute rewards and end round
|
| 172 |
+
rewards = self.get_rewards(self.state.splits)
|
| 173 |
+
|
| 174 |
+
# Info
|
| 175 |
+
info = self.get_info_of_variant(self.state, actions)
|
| 176 |
+
|
| 177 |
+
# Prepare next round
|
| 178 |
+
# Alternate starting agent
|
| 179 |
+
self.state.round_nb += 1
|
| 180 |
+
self._starting_agent_index = 1 - self._starting_agent_index
|
| 181 |
+
self.state.current_agent = self.agent_ids[self._starting_agent_index]
|
| 182 |
+
self.state.previous_values = copy.deepcopy(self.state.values)
|
| 183 |
+
self.state.previous_splits = copy.deepcopy(self.state.splits)
|
| 184 |
+
self.state.previous_quantities = copy.deepcopy(self.state.quantities)
|
| 185 |
+
self.state.previous_points = copy.deepcopy(rewards)
|
| 186 |
+
self.state.last_message = ""
|
| 187 |
+
self.set_new_round_of_variant() # variant specific
|
| 188 |
+
self.state.splits = {agent_id: None for agent_id in self.agent_ids}
|
| 189 |
+
self.state.nb_messages_sent = {agent_id: 0 for agent_id in self.agent_ids}
|
| 190 |
+
is_last_timestep_in_round = True
|
| 191 |
+
done = self.state.round_nb >= self.nb_of_rounds
|
| 192 |
+
|
| 193 |
+
# Message phase
|
| 194 |
+
elif isinstance(action, Message):
|
| 195 |
+
self.state.last_message = action.message
|
| 196 |
+
self.state.nb_messages_sent[current_agent] += 1
|
| 197 |
+
|
| 198 |
+
# Move turn to other agent
|
| 199 |
+
self.state.current_agent = self._other(current_agent)
|
| 200 |
+
|
| 201 |
+
# If both agents have reached their message quota, enter split phase
|
| 202 |
+
if all(
|
| 203 |
+
self.state.nb_messages_sent[agent_id]
|
| 204 |
+
>= self.quota_messages_per_agent_per_round
|
| 205 |
+
for agent_id in self.agent_ids
|
| 206 |
+
):
|
| 207 |
+
self.state.split_phase = True
|
| 208 |
+
is_last_timestep_in_round = False
|
| 209 |
+
done = False
|
| 210 |
+
rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
|
| 211 |
+
info = {"type": "message"}
|
| 212 |
+
|
| 213 |
+
info[
|
| 214 |
+
"is_last_timestep_in_round"
|
| 215 |
+
] = is_last_timestep_in_round # Used later to group round timesteps if needed
|
| 216 |
+
return done, SimulationStepLog(rewards=rewards, info=info)
|
| 217 |
+
|
| 218 |
+
def get_obs(self):
|
| 219 |
+
"""Returns all agent observations in dict"""
|
| 220 |
+
return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
|
| 221 |
+
|
| 222 |
+
@abstractmethod
|
| 223 |
+
def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
|
| 224 |
+
pass
|
| 225 |
+
|
| 226 |
+
@abstractmethod
|
| 227 |
+
def get_obs_agent(self, agent_id):
|
| 228 |
+
pass
|
| 229 |
+
|
| 230 |
+
def get_state(self):
|
| 231 |
+
return self.state
|
| 232 |
+
|
| 233 |
+
def get_safe_copy(self):
|
| 234 |
+
"""Return a safe copy of the simulation."""
|
| 235 |
+
simulation_copy = copy.copy(self)
|
| 236 |
+
simulation_copy.state = copy.deepcopy(self.state)
|
| 237 |
+
return simulation_copy
|
| 238 |
+
|
| 239 |
+
@abstractmethod
|
| 240 |
+
def reset(self) -> dict[AgentId, NegotiationObs]:
|
| 241 |
+
pass
|
src_code_for_reproducibility/markov_games/negotiation/negotiation_statistics.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Callable, Dict, List, Tuple
|
| 4 |
+
|
| 5 |
+
from mllm.markov_games.negotiation.nego_simulation import Split
|
| 6 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def avg_reward(sl: SimulationStepLog) -> List[Tuple[str, float]]:
|
| 10 |
+
"""Average (per-step) reward for each agent and overall.
|
| 11 |
+
|
| 12 |
+
What it computes:
|
| 13 |
+
- Returns the raw reward for every (non-buffer) agent at the current
|
| 14 |
+
simulation step.
|
| 15 |
+
- Adds an aggregate key ``all_agents`` which is the simple arithmetic
|
| 16 |
+
mean across the agents present in ``sl.rewards``.
|
| 17 |
+
|
| 18 |
+
Rationale / motivation:
|
| 19 |
+
Monitoring the reward stream at each step helps:
|
| 20 |
+
* Diagnose reward shaping issues (e.g., unintended negative drift).
|
| 21 |
+
* Provide a fairness snapshot (are rewards systematically skewed?).
|
| 22 |
+
* Supply a ubiquitous baseline metric used by other higher‑level
|
| 23 |
+
summaries (efficiency, surplus allocation, etc.).
|
| 24 |
+
|
| 25 |
+
Return shape:
|
| 26 |
+
{ agent_id: float, ..., "all_agents": float }
|
| 27 |
+
If any agent id contains the substring "buffer" we treat this step as
|
| 28 |
+
an implementation artifact (e.g., rollout buffer) and return ``None``
|
| 29 |
+
to avoid polluting aggregates.
|
| 30 |
+
"""
|
| 31 |
+
for aid in sl.rewards.keys():
|
| 32 |
+
if "buffer" in str(aid) and "live" not in str(aid):
|
| 33 |
+
return None
|
| 34 |
+
# One value per agent at each step
|
| 35 |
+
rewards_dict = {f"reward-{aid}": float(v) for aid, v in (sl.rewards or {}).items()}
|
| 36 |
+
return [(key, value) for key, value in rewards_dict.items() if value is not None]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def split_efficiency(sl: SimulationStepLog) -> List[Tuple[str, float]] | None:
|
| 40 |
+
"""Final‑round allocation efficiency relative to an upper bound.
|
| 41 |
+
|
| 42 |
+
What it computes (only on the last timestep of a negotiation round):
|
| 43 |
+
- Uses ``info['values']`` (per‑agent per‑item valuations) and
|
| 44 |
+
``info['quantities']`` (available item counts) to form a greedy
|
| 45 |
+
*upper bound* on achievable total reward: allocate each unit of an
|
| 46 |
+
item to the single agent who values that item most.
|
| 47 |
+
- Compares the actually realized sum of rewards at that final
|
| 48 |
+
timestep to this constructed maximum.
|
| 49 |
+
- Emits a single scalar under key ``"all_agents"`` equal to
|
| 50 |
+
achieved / theoretical_max.
|
| 51 |
+
|
| 52 |
+
Motivation:
|
| 53 |
+
Efficiency (a core welfare notion) distinguishes between coordination
|
| 54 |
+
failures (low efficiency) versus strategic distributional disputes
|
| 55 |
+
(high efficiency but uneven splits). Tracking this per round helps
|
| 56 |
+
evaluate whether models learn to identify and realize joint surplus.
|
| 57 |
+
|
| 58 |
+
Notes / caveats:
|
| 59 |
+
- Only defined for 2+ non‑buffer agents; if a buffer agent is present
|
| 60 |
+
returns ``None`` to exclude spurious steps.
|
| 61 |
+
- Requires the environment to have populated ``values`` and
|
| 62 |
+
``quantities``; otherwise returns ``None``.
|
| 63 |
+
- This is an optimistic bound (not necessarily reachable under
|
| 64 |
+
protocol constraints) but is simple, fast, and comparable across
|
| 65 |
+
runs.
|
| 66 |
+
"""
|
| 67 |
+
info = sl.info or {}
|
| 68 |
+
if not info or not info.get("is_last_timestep_in_round"):
|
| 69 |
+
return None
|
| 70 |
+
quantities = info.get("quantities") or {}
|
| 71 |
+
values = info.get("values") or {}
|
| 72 |
+
if not values or not quantities:
|
| 73 |
+
return None
|
| 74 |
+
agent_ids = list(sl.rewards.keys())
|
| 75 |
+
if type(values[agent_ids[0]]) is dict:
|
| 76 |
+
item_keys = list(values.values())[0].keys()
|
| 77 |
+
max_vals, max_quantities = [], []
|
| 78 |
+
for item in item_keys:
|
| 79 |
+
max_val = max(float(agent_vals[item]) for agent_vals in values.values())
|
| 80 |
+
max_vals.append(max_val)
|
| 81 |
+
max_quantities.append(quantities[item])
|
| 82 |
+
else:
|
| 83 |
+
max_vals = [max(float(v) for v in values.values())]
|
| 84 |
+
max_quantities = [quantities[item] for item in quantities.keys()]
|
| 85 |
+
for aid in sl.rewards.keys():
|
| 86 |
+
if "buffer" in str(aid) and "live" not in str(aid):
|
| 87 |
+
return None
|
| 88 |
+
achieved = sum(float(v) for v in sl.rewards.values())
|
| 89 |
+
max_reward = sum(d * v for d, v in zip(max_quantities, max_vals))
|
| 90 |
+
# Efficiency is a global metric; emit same value for a special key "all"
|
| 91 |
+
return [("split_efficiency", achieved / max_reward)]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _extract_items_from_split(raw_split: Dict) -> Dict[str, float] | None:
|
| 95 |
+
"""Return a mapping item->proposal amount from a split structure.
|
| 96 |
+
|
| 97 |
+
Supports both generic negotiation splits with nested structure
|
| 98 |
+
{ 'items_given_to_self': {item: qty, ...}}
|
| 99 |
+
and TAS coin-only variants which may already be a flat mapping {'coins': qty}.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
if raw_split is None:
|
| 103 |
+
return {}
|
| 104 |
+
elif isinstance(raw_split, Split):
|
| 105 |
+
return {k: float(v) for k, v in raw_split.items_given_to_self.items()}
|
| 106 |
+
elif isinstance(raw_split, dict):
|
| 107 |
+
if "items_given_to_self" in raw_split and isinstance(
|
| 108 |
+
raw_split["items_given_to_self"], dict
|
| 109 |
+
):
|
| 110 |
+
return {k: float(v) for k, v in raw_split["items_given_to_self"].items()}
|
| 111 |
+
# Fallback: assume already flat mapping of items
|
| 112 |
+
elif hasattr(raw_split, "items_given_to_self"):
|
| 113 |
+
return {k: float(v) for k, v in raw_split["items_given_to_self"].items()}
|
| 114 |
+
return {
|
| 115 |
+
k: float(v) for k, v in raw_split.items() if isinstance(v, (int, float))
|
| 116 |
+
}
|
| 117 |
+
return {}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _average_proposal_relative_value(
|
| 121 |
+
sl: SimulationStepLog,
|
| 122 |
+
metric_name: str,
|
| 123 |
+
comparator: Callable[[float, float], bool],
|
| 124 |
+
opposite_comparator: Callable[[float, float], bool],
|
| 125 |
+
) -> Dict[str, float | None] | None:
|
| 126 |
+
"""Shared implementation for proposal size conditioned on relative value.
|
| 127 |
+
|
| 128 |
+
Parameters:
|
| 129 |
+
comparator: returns True when agent_0's value relation (e.g. < or >)
|
| 130 |
+
to agent_1 holds for an item and we should collect agent_0's
|
| 131 |
+
proposed quantity for that item.
|
| 132 |
+
opposite_comparator: inverse relation used to collect agent_1's items.
|
| 133 |
+
|
| 134 |
+
Behavior:
|
| 135 |
+
- Executes only on final timestep of a round (where the definitive
|
| 136 |
+
proposal / allocation is known via ``info['splits']``).
|
| 137 |
+
- For each item, classifies which agent's value satisfies the chosen
|
| 138 |
+
relation and records that agent's proposed quantity from the split.
|
| 139 |
+
- Averages (mean) across all qualifying items per agent; if no items
|
| 140 |
+
qualify for an agent returns ``None`` for that agent id.
|
| 141 |
+
- Adds ``all_agents`` mean across the numeric (non-None) agent values.
|
| 142 |
+
|
| 143 |
+
Why this matters:
|
| 144 |
+
Distinguishing how much an agent *asks for* when it subjectively
|
| 145 |
+
values items more (or less) than its counterpart reveals patterns of
|
| 146 |
+
opportunism vs. concession. This is especially useful when raw reward
|
| 147 |
+
differences are subtle but allocation *intent* differs.
|
| 148 |
+
"""
|
| 149 |
+
info = sl.info or {}
|
| 150 |
+
if not info or not info.get("is_last_timestep_in_round"):
|
| 151 |
+
return None
|
| 152 |
+
quantities = info.get("quantities") or {}
|
| 153 |
+
splits = info.get("splits") or {}
|
| 154 |
+
values = info.get("values") or {}
|
| 155 |
+
agent_ids: List[str] = list(sl.rewards.keys())
|
| 156 |
+
if len(agent_ids) != 2:
|
| 157 |
+
return None # Only defined for 2-agent case.
|
| 158 |
+
for aid in agent_ids:
|
| 159 |
+
if "buffer" in str(aid) and "live" not in str(aid):
|
| 160 |
+
return None
|
| 161 |
+
# Extract per-agent item proposals robustly
|
| 162 |
+
split_items = {aid: _extract_items_from_split(splits.get(aid)) for aid in agent_ids}
|
| 163 |
+
agent_0_vals: List[float] = []
|
| 164 |
+
agent_1_vals: List[float] = []
|
| 165 |
+
for item in quantities.keys():
|
| 166 |
+
# Values may be either a float (same for all items) or dict per item
|
| 167 |
+
v0_raw = values[agent_ids[0]]
|
| 168 |
+
v1_raw = values[agent_ids[1]]
|
| 169 |
+
v0 = float(v0_raw[item]) if isinstance(v0_raw, dict) else float(v0_raw)
|
| 170 |
+
v1 = float(v1_raw[item]) if isinstance(v1_raw, dict) else float(v1_raw)
|
| 171 |
+
if comparator(v0, v1):
|
| 172 |
+
agent_0_vals.append(split_items[agent_ids[0]].get(item, 0.0))
|
| 173 |
+
elif opposite_comparator(v0, v1):
|
| 174 |
+
agent_1_vals.append(split_items[agent_ids[1]].get(item, 0.0))
|
| 175 |
+
out: Dict[str, float | None] = {}
|
| 176 |
+
out[f"{metric_name}-{agent_ids[0]}"] = (
|
| 177 |
+
sum(agent_0_vals) / len(agent_0_vals) if agent_0_vals else None
|
| 178 |
+
)
|
| 179 |
+
out[f"{metric_name}-{agent_ids[1]}"] = (
|
| 180 |
+
sum(agent_1_vals) / len(agent_1_vals) if agent_1_vals else None
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
return [(key, value) for key, value in out.items() if value is not None]
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def average_proposal_when_agent_values_item_lower(
|
| 187 |
+
sl: SimulationStepLog,
|
| 188 |
+
) -> List[Tuple[str, float | None]] | None:
|
| 189 |
+
"""Mean quantity an agent proposes for items it values *less* than opponent.
|
| 190 |
+
|
| 191 |
+
Interpretation:
|
| 192 |
+
A higher value implies the agent still claims (or is allocated) a
|
| 193 |
+
notable share of items where it has a comparative *disadvantage* in
|
| 194 |
+
valuation, signaling either strategic over-claiming or protocol-driven
|
| 195 |
+
egalitarian splits. Conversely, very low numbers can indicate
|
| 196 |
+
efficient specialization or excessive concession.
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
Mapping { agent_id: float | None, "all_agents": float | None } where
|
| 200 |
+
None indicates no qualifying items for that agent in the round.
|
| 201 |
+
"""
|
| 202 |
+
return _average_proposal_relative_value(
|
| 203 |
+
sl,
|
| 204 |
+
"average_proposal_when_agent_values_item_lower",
|
| 205 |
+
lambda a, b: a < b,
|
| 206 |
+
lambda a, b: a > b,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def average_proposal_when_agent_values_item_higher(
|
| 211 |
+
sl: SimulationStepLog,
|
| 212 |
+
) -> List[Tuple[str, float | None]] | None:
|
| 213 |
+
"""Mean quantity an agent proposes for items it values *more* than opponent.
|
| 214 |
+
|
| 215 |
+
Interpretation:
|
| 216 |
+
Captures how aggressively an agent claims items where it holds a
|
| 217 |
+
comparative *advantage*. Elevated values can reflect rational
|
| 218 |
+
specialization (efficient exploitation of comparative advantage) or
|
| 219 |
+
potentially unfair grabs if paired with low concession in the lower
|
| 220 |
+
valuation metric. Comparing this with the 'lower' counterpart helps
|
| 221 |
+
profile negotiation style (cooperative vs. exploitative).
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
Mapping { agent_id: float | None, "all_agents": float | None } where
|
| 225 |
+
None indicates no qualifying items.
|
| 226 |
+
"""
|
| 227 |
+
return _average_proposal_relative_value(
|
| 228 |
+
sl,
|
| 229 |
+
"average_proposal_when_agent_values_item_higher",
|
| 230 |
+
lambda a, b: a > b,
|
| 231 |
+
lambda a, b: a < b,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# Explicit list of metric functions exported for rendering. Helper functions
|
| 236 |
+
# starting with '_' are intentionally excluded. Update this list when adding
|
| 237 |
+
# new public statistics so render.py can rely on it instead of introspecting
|
| 238 |
+
# every callable in the module.
|
| 239 |
+
stat_functs: list[Callable[[SimulationStepLog], List[Tuple[str, float]]]] = [
|
| 240 |
+
avg_reward,
|
| 241 |
+
average_proposal_when_agent_values_item_lower,
|
| 242 |
+
average_proposal_when_agent_values_item_higher,
|
| 243 |
+
split_efficiency,
|
| 244 |
+
]
|
src_code_for_reproducibility/markov_games/negotiation/tas_rps_simulation.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Trust-and-Split simulation.
|
| 3 |
+
|
| 4 |
+
This environment models a simple bargaining game over 10 coins with messaging.
|
| 5 |
+
Agents are assigned rock/paper/scissors hands, with the winner getting value 10 per coin
|
| 6 |
+
and the loser getting value 1 per coin. Agents alternate sending messages for a fixed
|
| 7 |
+
number of turns per round and then each submits a split proposal indicating how many
|
| 8 |
+
coins they keep for themselves. Rewards are proportional if the proposed totals exceed 10.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import copy
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from typing import Any, Dict, List, Literal, Tuple
|
| 14 |
+
|
| 15 |
+
from numpy.random import default_rng
|
| 16 |
+
|
| 17 |
+
from mllm.markov_games.negotiation.nego_simulation import (
|
| 18 |
+
Message,
|
| 19 |
+
NegotiationObs,
|
| 20 |
+
NegotiationSimulation,
|
| 21 |
+
NegotiationState,
|
| 22 |
+
Split,
|
| 23 |
+
compute_tas_style_rewards,
|
| 24 |
+
)
|
| 25 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 26 |
+
|
| 27 |
+
AgentId = str
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _get_rps_winner(
|
| 31 |
+
hand1: Literal["rock", "paper", "scissors"],
|
| 32 |
+
hand2: Literal["rock", "paper", "scissors"],
|
| 33 |
+
) -> Literal["rock", "paper", "scissors"]:
|
| 34 |
+
"""Determine winner of rock-paper-scissors between two hands."""
|
| 35 |
+
if hand1 == hand2:
|
| 36 |
+
raise ValueError("Hands should be different")
|
| 37 |
+
if (
|
| 38 |
+
(hand1 == "rock" and hand2 == "scissors")
|
| 39 |
+
or (hand1 == "paper" and hand2 == "rock")
|
| 40 |
+
or (hand1 == "scissors" and hand2 == "paper")
|
| 41 |
+
):
|
| 42 |
+
return hand1
|
| 43 |
+
else:
|
| 44 |
+
return hand2
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class TrustAndSplitRPSState(NegotiationState):
|
| 49 |
+
hands: Dict[
|
| 50 |
+
AgentId, Literal["rock", "paper", "scissors"]
|
| 51 |
+
] # rock, paper, or scissors
|
| 52 |
+
previous_hands: Dict[AgentId, Literal["rock", "paper", "scissors"]] | None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class TrustAndSplitRPSObs(NegotiationObs):
|
| 57 |
+
hand: Literal["rock", "paper", "scissors"]
|
| 58 |
+
last_hand_agent: Literal["rock", "paper", "scissors"] | None
|
| 59 |
+
last_hand_coagent: Literal["rock", "paper", "scissors"] | None
|
| 60 |
+
last_hand_value_coagent: Literal["upper", "lower"] | None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TrustAndSplitRPSSimulation(NegotiationSimulation):
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
alternating_hands: bool = False,
|
| 67 |
+
alternating_mix_ratio: float = None,
|
| 68 |
+
*args,
|
| 69 |
+
**kwargs,
|
| 70 |
+
):
|
| 71 |
+
self.alternating_hands = alternating_hands
|
| 72 |
+
self.alternating_mix_ratio = alternating_mix_ratio
|
| 73 |
+
super().__init__(*args, **kwargs)
|
| 74 |
+
if self.alternating_mix_ratio is not None:
|
| 75 |
+
if self.rng.random() < self.alternating_mix_ratio:
|
| 76 |
+
self.alternating_hands = True
|
| 77 |
+
else:
|
| 78 |
+
self.alternating_hands = False
|
| 79 |
+
|
| 80 |
+
def _sample_hands_and_values(
|
| 81 |
+
self,
|
| 82 |
+
alternate_hands: bool = False,
|
| 83 |
+
) -> Tuple[Dict[AgentId, str], Dict[AgentId, float]]:
|
| 84 |
+
hands = ["rock", "paper", "scissors"]
|
| 85 |
+
if alternate_hands:
|
| 86 |
+
previous_hands = list(self.state.previous_hands.values())
|
| 87 |
+
hand1, hand2 = self.rng.choice(hands, size=2, replace=False)
|
| 88 |
+
winner = _get_rps_winner(hand1, hand2)
|
| 89 |
+
loser = hand1 if winner == hand2 else hand2
|
| 90 |
+
previous_winner = _get_rps_winner(previous_hands[0], previous_hands[1])
|
| 91 |
+
agent_hands, values = {}, {}
|
| 92 |
+
for agent_id in self.agent_ids:
|
| 93 |
+
if self.state.previous_hands[agent_id] == previous_winner:
|
| 94 |
+
agent_hands[agent_id] = loser
|
| 95 |
+
values[agent_id] = 1.0
|
| 96 |
+
else:
|
| 97 |
+
agent_hands[agent_id] = winner
|
| 98 |
+
values[agent_id] = 10.0
|
| 99 |
+
return agent_hands, values
|
| 100 |
+
else:
|
| 101 |
+
# Assign different hands to each agent
|
| 102 |
+
hand1, hand2 = self.rng.choice(hands, size=2, replace=False)
|
| 103 |
+
|
| 104 |
+
agent_hands = {self.agent_ids[0]: hand1, self.agent_ids[1]: hand2}
|
| 105 |
+
|
| 106 |
+
# Determine winner and assign values
|
| 107 |
+
winner = _get_rps_winner(hand1, hand2)
|
| 108 |
+
values = {}
|
| 109 |
+
for agent_id in self.agent_ids:
|
| 110 |
+
if agent_hands[agent_id] == winner:
|
| 111 |
+
values[agent_id] = 10.0 # Winner gets value 10
|
| 112 |
+
else:
|
| 113 |
+
values[agent_id] = 1.0 # Loser gets value 1
|
| 114 |
+
|
| 115 |
+
return agent_hands, values
|
| 116 |
+
|
| 117 |
+
def set_new_round_of_variant(self):
|
| 118 |
+
self.state.previous_hands = copy.deepcopy(self.state.hands)
|
| 119 |
+
new_hands, new_values = self._sample_hands_and_values(
|
| 120 |
+
alternate_hands=self.alternating_hands
|
| 121 |
+
)
|
| 122 |
+
self.state.hands = new_hands
|
| 123 |
+
self.state.values = new_values
|
| 124 |
+
# Quantities are constant in TAS
|
| 125 |
+
self.state.quantities = {"coins": 10}
|
| 126 |
+
self.state.split_phase = False
|
| 127 |
+
|
| 128 |
+
def get_info_of_variant(
|
| 129 |
+
self, state: NegotiationState, actions: Dict[AgentId, Any]
|
| 130 |
+
) -> Dict[str, Any]:
|
| 131 |
+
return {
|
| 132 |
+
"quantities": copy.deepcopy(state.quantities),
|
| 133 |
+
"hands": copy.deepcopy(state.hands),
|
| 134 |
+
"values": copy.deepcopy(state.values),
|
| 135 |
+
"previous_hands": copy.deepcopy(state.previous_hands),
|
| 136 |
+
"previous_values": copy.deepcopy(state.previous_values),
|
| 137 |
+
"splits": copy.deepcopy(state.splits),
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
|
| 141 |
+
return compute_tas_style_rewards(
|
| 142 |
+
self.agent_ids, self.state.values, splits, self.state.quantities
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def get_obs_agent(self, agent_id):
|
| 146 |
+
"""Returns observation for agent_id"""
|
| 147 |
+
other_id = self._other(agent_id)
|
| 148 |
+
last_value_coagent = (
|
| 149 |
+
None
|
| 150 |
+
if self.state.previous_values is None
|
| 151 |
+
else self.state.previous_values.get(other_id)
|
| 152 |
+
)
|
| 153 |
+
last_hand_coagent = (
|
| 154 |
+
None
|
| 155 |
+
if self.state.previous_hands is None
|
| 156 |
+
else self.state.previous_hands.get(other_id)
|
| 157 |
+
)
|
| 158 |
+
last_points_coagent = (
|
| 159 |
+
None
|
| 160 |
+
if self.state.previous_points is None
|
| 161 |
+
else round(self.state.previous_points.get(other_id), 1)
|
| 162 |
+
)
|
| 163 |
+
last_value_agent = (
|
| 164 |
+
None
|
| 165 |
+
if self.state.previous_values is None
|
| 166 |
+
else self.state.previous_values.get(agent_id)
|
| 167 |
+
)
|
| 168 |
+
last_hand_agent = (
|
| 169 |
+
None
|
| 170 |
+
if self.state.previous_hands is None
|
| 171 |
+
else self.state.previous_hands.get(agent_id)
|
| 172 |
+
)
|
| 173 |
+
last_points_agent = (
|
| 174 |
+
None
|
| 175 |
+
if self.state.previous_points is None
|
| 176 |
+
else round(self.state.previous_points.get(agent_id), 1)
|
| 177 |
+
)
|
| 178 |
+
last_split_coagent = None
|
| 179 |
+
last_split_agent = None
|
| 180 |
+
if self.state.previous_splits is not None:
|
| 181 |
+
last_split_coagent = self.state.previous_splits[
|
| 182 |
+
other_id
|
| 183 |
+
].items_given_to_self["coins"]
|
| 184 |
+
last_split_agent = self.state.previous_splits[agent_id].items_given_to_self[
|
| 185 |
+
"coins"
|
| 186 |
+
]
|
| 187 |
+
if last_hand_agent is None or last_hand_coagent is None:
|
| 188 |
+
last_hand_value_coagent = None
|
| 189 |
+
else:
|
| 190 |
+
winner = _get_rps_winner(last_hand_agent, last_hand_coagent)
|
| 191 |
+
last_hand_value_coagent = (
|
| 192 |
+
"upper" if winner == last_hand_coagent else "lower"
|
| 193 |
+
)
|
| 194 |
+
obs = TrustAndSplitRPSObs(
|
| 195 |
+
round_nb=self.state.round_nb,
|
| 196 |
+
last_message=self.state.last_message,
|
| 197 |
+
quota_messages_per_agent_per_round=self.quota_messages_per_agent_per_round,
|
| 198 |
+
current_agent=self.state.current_agent,
|
| 199 |
+
other_agent=self.agent_id_to_name[other_id],
|
| 200 |
+
quantities={"coins": 10},
|
| 201 |
+
item_types=self.item_types,
|
| 202 |
+
value=self.state.values[agent_id],
|
| 203 |
+
split_phase=self.state.split_phase,
|
| 204 |
+
last_split_agent=last_split_agent,
|
| 205 |
+
last_value_agent=last_value_agent,
|
| 206 |
+
last_points_agent=last_points_agent,
|
| 207 |
+
last_split_coagent=last_split_coagent,
|
| 208 |
+
last_value_coagent=last_value_coagent,
|
| 209 |
+
last_points_coagent=last_points_coagent,
|
| 210 |
+
hand=self.state.hands[agent_id],
|
| 211 |
+
last_hand_coagent=last_hand_coagent,
|
| 212 |
+
last_hand_agent=last_hand_agent,
|
| 213 |
+
last_quantities=self.state.previous_quantities,
|
| 214 |
+
last_hand_value_coagent=last_hand_value_coagent,
|
| 215 |
+
)
|
| 216 |
+
return obs
|
| 217 |
+
|
| 218 |
+
def get_state(self):
|
| 219 |
+
return self.state
|
| 220 |
+
|
| 221 |
+
def get_safe_copy(self):
|
| 222 |
+
"""Return a safe copy of the simulation."""
|
| 223 |
+
simulation_copy = copy.copy(self)
|
| 224 |
+
simulation_copy.state = copy.deepcopy(self.state)
|
| 225 |
+
return simulation_copy
|
| 226 |
+
|
| 227 |
+
def reset(self):
|
| 228 |
+
"""Initialize and return initial observations"""
|
| 229 |
+
# Decide starting agent alternating across resets for determinism
|
| 230 |
+
start_agent = self.agent_ids[self._starting_agent_index]
|
| 231 |
+
hands, values = self._sample_hands_and_values()
|
| 232 |
+
self.state = TrustAndSplitRPSState(
|
| 233 |
+
round_nb=0,
|
| 234 |
+
last_message="",
|
| 235 |
+
current_agent=start_agent,
|
| 236 |
+
quantities={"coins": 10},
|
| 237 |
+
values=values,
|
| 238 |
+
splits={aid: None for aid in self.agent_ids},
|
| 239 |
+
nb_messages_sent={aid: 0 for aid in self.agent_ids},
|
| 240 |
+
previous_values=None,
|
| 241 |
+
previous_splits=None,
|
| 242 |
+
previous_points=None,
|
| 243 |
+
split_phase=False,
|
| 244 |
+
hands=hands,
|
| 245 |
+
previous_hands=None,
|
| 246 |
+
previous_quantities=None,
|
| 247 |
+
)
|
| 248 |
+
return self.get_obs()
|
src_code_for_reproducibility/markov_games/negotiation/tas_simple_agent.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mllm.markov_games.negotiation.nego_agent import NegotiationAgent
|
| 2 |
+
from mllm.markov_games.negotiation.nego_simulation import Split
|
| 3 |
+
from mllm.markov_games.negotiation.tas_simple_simulation import TrustAndSplitSimpleObs
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TrustAndSplitSimpleAgent(NegotiationAgent):
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
num_message_chars,
|
| 10 |
+
message_start_end_format: bool = False,
|
| 11 |
+
proposal_start_end_format: bool = False,
|
| 12 |
+
*args,
|
| 13 |
+
**kwargs,
|
| 14 |
+
):
|
| 15 |
+
self.num_message_chars = num_message_chars
|
| 16 |
+
self.message_start_end_format = message_start_end_format
|
| 17 |
+
self.proposal_start_end_format = proposal_start_end_format
|
| 18 |
+
super().__init__(*args, **kwargs)
|
| 19 |
+
self.intro_prompt = (
|
| 20 |
+
"Welcome to an iterated game. You are {agent}. The other agent is {other_agent}.\n"
|
| 21 |
+
"Setup:\n"
|
| 22 |
+
"1. The game has multiple independent rounds.\n"
|
| 23 |
+
"2. In each round, there are 10 coins to split between the two agents.\n"
|
| 24 |
+
"3. Both agents are assigned a per-coin value between 1 and 10 (inclusive) in each round.\n"
|
| 25 |
+
"4. You can only observe your own per-coin value.\n"
|
| 26 |
+
"5. Because assignments are random, both agents are equally likely to have same expected per-coin value.\n"
|
| 27 |
+
"\n"
|
| 28 |
+
"Protocol:\n"
|
| 29 |
+
"1. At the start of the round, one agent begins the conversation. The starting role alternates each round.\n"
|
| 30 |
+
"2. Agents exchange a short chat ({quota_messages_per_agent_per_round} messages per round per agent) to negotiate how to split the coins.\n"
|
| 31 |
+
" - Use this chat to communicate your private per-coin value to make informed proposals.\n"
|
| 32 |
+
"3. After the chat, both agents simultaneously propose how many coins they keep.\n"
|
| 33 |
+
"4. If the total sum of proposals is less than or equal to 10, both agents receive their proposals.\n"
|
| 34 |
+
"5. If the total sum of proposals exceeds 10, the coins are allocated proportionally.\n"
|
| 35 |
+
"6. Your points for the round = (coins you receive) x (your per-coin value for that round). \n"
|
| 36 |
+
"7. Points are accumulated across rounds.\n"
|
| 37 |
+
"Your goal: {goal}\n"
|
| 38 |
+
)
|
| 39 |
+
self.new_round_prompt = (
|
| 40 |
+
"A New Round Begins\n"
|
| 41 |
+
"Your per-coin value is {value}. You don't know {other_agent}'s value yet.\n"
|
| 42 |
+
)
|
| 43 |
+
self.last_round_prompt = "In the previous round, {other_agent} had a {last_value_str_coagent} value and proposed {last_split_coagent} coins.\n"
|
| 44 |
+
if self.proposal_start_end_format:
|
| 45 |
+
self.send_split_prompt = (
|
| 46 |
+
"Submit your proposal\n"
|
| 47 |
+
"Respond with <<proposal_start>> x <<proposal_end>> where x is an integer in [0, 10]."
|
| 48 |
+
)
|
| 49 |
+
else:
|
| 50 |
+
self.send_split_prompt = (
|
| 51 |
+
"Submit your proposal\n"
|
| 52 |
+
"Respond with <coins_to_self> x </coins_to_self> where x is an integer in [0, 10]."
|
| 53 |
+
)
|
| 54 |
+
self.wait_for_message_prompt = "Wait for {other_agent} to send a message..."
|
| 55 |
+
# self.wait_for_message_prompt = ""
|
| 56 |
+
self.last_message_prompt = "{other_agent} said: {last_message}"
|
| 57 |
+
if self.message_start_end_format:
|
| 58 |
+
self.send_message_prompt = f"Send your message now in <<message_start>>...<<message_end>> (<={self.num_message_chars} chars)."
|
| 59 |
+
else:
|
| 60 |
+
self.send_message_prompt = f"Send your message now in <message>...</message> (<={self.num_message_chars} chars)."
|
| 61 |
+
|
| 62 |
+
def get_message_regex(self, observation: TrustAndSplitSimpleObs) -> str:
|
| 63 |
+
if self.message_start_end_format:
|
| 64 |
+
return (
|
| 65 |
+
rf"<<message_start>>[\s\S]{{0,{self.num_message_chars}}}<<message_end>>"
|
| 66 |
+
)
|
| 67 |
+
else:
|
| 68 |
+
return rf"<message>[\s\S]{{0,{self.num_message_chars}}}</message>"
|
| 69 |
+
|
| 70 |
+
def get_split_regex(self, observation: TrustAndSplitSimpleObs) -> str:
|
| 71 |
+
if self.proposal_start_end_format:
|
| 72 |
+
return r"<<proposal_start>> ?(10|[0-9]) ?<<proposal_end>>"
|
| 73 |
+
else:
|
| 74 |
+
return r"<coins_to_self> ?(10|[0-9]) ?</coins_to_self>"
|
| 75 |
+
|
| 76 |
+
def get_split_action(
|
| 77 |
+
self, policy_output: str, observation: TrustAndSplitSimpleObs
|
| 78 |
+
) -> Split:
|
| 79 |
+
import re as _re
|
| 80 |
+
|
| 81 |
+
if self.proposal_start_end_format:
|
| 82 |
+
m = _re.search(
|
| 83 |
+
r"<<proposal_start>> ?(10|[0-9]) ?<<proposal_end>>", policy_output
|
| 84 |
+
)
|
| 85 |
+
else:
|
| 86 |
+
m = _re.search(
|
| 87 |
+
r"<coins_to_self> ?(10|[0-9]) ?</coins_to_self>", policy_output
|
| 88 |
+
)
|
| 89 |
+
coins_int = int(m.group(1)) if m else int(policy_output)
|
| 90 |
+
return Split(items_given_to_self={"coins": coins_int})
|
src_code_for_reproducibility/training/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (155 Bytes). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/annealing_methods.cpython-312.pyc
ADDED
|
Binary file (500 Bytes). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/credit_methods.cpython-312.pyc
ADDED
|
Binary file (12.3 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/produce_training_stats.cpython-312.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/tally_basic.cpython-312.pyc
ADDED
|
Binary file (6.01 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/tokenize_chats.cpython-312.pyc
ADDED
|
Binary file (5.85 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/trainer_ad_align.cpython-312.pyc
ADDED
|
Binary file (19.5 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/trainer_common.cpython-312.pyc
ADDED
|
Binary file (39.7 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/trainer_independent.cpython-312.pyc
ADDED
|
Binary file (6.47 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/trainer_sum_rewards.cpython-312.pyc
ADDED
|
Binary file (5.9 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/training_data_utils.cpython-312.pyc
ADDED
|
Binary file (20 kB). View file
|
|
|