Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- run.log +0 -0
- src_code_for_reproducibility/__pycache__/__init__.cpython-312.pyc +0 -0
- src_code_for_reproducibility/chat_utils/apply_template.py +89 -0
- src_code_for_reproducibility/chat_utils/chat_turn.py +32 -0
- src_code_for_reproducibility/chat_utils/template_specific.py +114 -0
- src_code_for_reproducibility/markov_games/__init__.py +4 -0
- src_code_for_reproducibility/markov_games/__pycache__/alternative_actions_runner.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/__pycache__/mg_utils.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc +0 -0
- src_code_for_reproducibility/markov_games/agent.py +72 -0
- src_code_for_reproducibility/markov_games/alternative_actions_runner.py +146 -0
- src_code_for_reproducibility/markov_games/group_timesteps.py +133 -0
- src_code_for_reproducibility/markov_games/linear_runner.py +42 -0
- src_code_for_reproducibility/markov_games/markov_game.py +217 -0
- src_code_for_reproducibility/markov_games/mg_utils.py +97 -0
- src_code_for_reproducibility/markov_games/negotiation/README.md +27 -0
- src_code_for_reproducibility/markov_games/negotiation/dond_agent.py +75 -0
- src_code_for_reproducibility/markov_games/negotiation/dond_simulation.py +176 -0
- src_code_for_reproducibility/markov_games/negotiation/nego_agent.py +261 -0
- src_code_for_reproducibility/markov_games/negotiation/nego_hard_coded_policies.py +70 -0
- src_code_for_reproducibility/markov_games/negotiation/nego_simulation.py +252 -0
- src_code_for_reproducibility/markov_games/negotiation/negotiation_statistics.py +249 -0
- src_code_for_reproducibility/markov_games/negotiation/no_press_nego_simulation.py +182 -0
- src_code_for_reproducibility/markov_games/negotiation/tas_agent.py +118 -0
- src_code_for_reproducibility/markov_games/negotiation/tas_rps_agent.py +128 -0
- src_code_for_reproducibility/markov_games/negotiation/tas_rps_simulation.py +257 -0
- src_code_for_reproducibility/markov_games/rollout_tree.py +95 -0
- src_code_for_reproducibility/markov_games/run_markov_games.py +35 -0
- src_code_for_reproducibility/markov_games/simulation.py +94 -0
- src_code_for_reproducibility/markov_games/statistics_runner.py +415 -0
- src_code_for_reproducibility/models/__init__.py +4 -0
- src_code_for_reproducibility/models/__pycache__/__init__.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/adapter_training_wrapper.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/human_policy.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/inference_backend.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/inference_backend_dummy.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/inference_backend_vllm.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/large_language_model_api.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/large_language_model_local.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/__pycache__/scalar_critic.cpython-312.pyc +0 -0
- src_code_for_reproducibility/models/human_policy.py +260 -0
- src_code_for_reproducibility/models/inference_backend_vllm.py +111 -0
- src_code_for_reproducibility/training/__init__.py +4 -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__/tally_metrics.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/tally_rollout.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/tally_tokenwise.cpython-312.pyc +0 -0
- src_code_for_reproducibility/training/__pycache__/tokenize_chats.cpython-312.pyc +0 -0
run.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
src_code_for_reproducibility/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (272 Bytes). View file
|
|
|
src_code_for_reproducibility/chat_utils/apply_template.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/chat_utils/apply_template.py
|
| 3 |
+
Summary: Applies tokenizer-specific chat templates and stitches chat token IDs.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from mllm.chat_utils.chat_turn import ChatTurn
|
| 9 |
+
from mllm.chat_utils.template_specific import (
|
| 10 |
+
custom_gemma3_template,
|
| 11 |
+
custom_llama3_template,
|
| 12 |
+
custom_qwen2_template,
|
| 13 |
+
custom_qwen3_template,
|
| 14 |
+
gemma3_assistant_postfix,
|
| 15 |
+
qwen2_assistant_postfix,
|
| 16 |
+
qwen3_assistant_postfix,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_custom_chat_template(tokenizer) -> str:
|
| 21 |
+
"""
|
| 22 |
+
Get the chat template for the tokenizer.
|
| 23 |
+
"""
|
| 24 |
+
if "qwen2" in tokenizer.name_or_path.lower():
|
| 25 |
+
return custom_qwen2_template
|
| 26 |
+
elif "llama" in tokenizer.name_or_path.lower():
|
| 27 |
+
return custom_llama3_template
|
| 28 |
+
elif "qwen3" in tokenizer.name_or_path.lower():
|
| 29 |
+
return custom_qwen3_template
|
| 30 |
+
elif "gemma" in tokenizer.name_or_path.lower():
|
| 31 |
+
return custom_gemma3_template
|
| 32 |
+
else:
|
| 33 |
+
raise ValueError(f"Tokenizer {tokenizer.name_or_path} not supported")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_custom_assistant_postfix(tokenizer) -> torch.Tensor:
|
| 37 |
+
"""
|
| 38 |
+
Get the custom assistant postfix for the tokenizer.
|
| 39 |
+
"""
|
| 40 |
+
if "qwen2" in tokenizer.name_or_path.lower():
|
| 41 |
+
return qwen2_assistant_postfix
|
| 42 |
+
elif "qwen3" in tokenizer.name_or_path.lower():
|
| 43 |
+
return qwen3_assistant_postfix
|
| 44 |
+
elif "gemma" in tokenizer.name_or_path.lower():
|
| 45 |
+
return gemma3_assistant_postfix
|
| 46 |
+
return torch.tensor([], dtype=torch.long)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def tokenize_chats(chats: list[ChatTurn], tokenizer, enable_thinking) -> None:
|
| 50 |
+
"""
|
| 51 |
+
Set the chat_template_token_ids for each chat turn.
|
| 52 |
+
We rely on tokenizer-side templates because engine-provided cached tokens are not exposed yet.
|
| 53 |
+
"""
|
| 54 |
+
custom_template = get_custom_chat_template(tokenizer)
|
| 55 |
+
custom_assistant_postfix: torch.Tensor = get_custom_assistant_postfix(tokenizer)
|
| 56 |
+
for i, chat in enumerate(chats):
|
| 57 |
+
if chat.chat_template_token_ids is None:
|
| 58 |
+
if chat.role == "user":
|
| 59 |
+
next_chat = chats[i + 1] if i + 1 < len(chats) else None
|
| 60 |
+
add_generation_prompt = True
|
| 61 |
+
if next_chat and next_chat.role == "user":
|
| 62 |
+
add_generation_prompt = False
|
| 63 |
+
encoded_chat = tokenizer.apply_chat_template(
|
| 64 |
+
[chat],
|
| 65 |
+
return_tensors="pt",
|
| 66 |
+
chat_template=custom_template,
|
| 67 |
+
add_generation_prompt=add_generation_prompt,
|
| 68 |
+
add_system_prompt=True if i == 0 else False,
|
| 69 |
+
enable_thinking=enable_thinking,
|
| 70 |
+
).flatten()
|
| 71 |
+
previous_chat = chats[i - 1] if i > 0 else None
|
| 72 |
+
if previous_chat and previous_chat.role == "assistant":
|
| 73 |
+
encoded_chat = torch.cat([custom_assistant_postfix, encoded_chat])
|
| 74 |
+
elif chat.role == "assistant":
|
| 75 |
+
encoded_chat = chat.out_token_ids
|
| 76 |
+
chat.chat_template_token_ids = encoded_chat
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def chat_turns_to_token_ids(
|
| 80 |
+
chats: list[ChatTurn], tokenizer, enable_thinking
|
| 81 |
+
) -> list[int]:
|
| 82 |
+
"""
|
| 83 |
+
Tokenize the chat turns and set the chat_template_token_ids for each chat turn.
|
| 84 |
+
"""
|
| 85 |
+
tokenize_chats(chats=chats, tokenizer=tokenizer, enable_thinking=enable_thinking)
|
| 86 |
+
token_ids = []
|
| 87 |
+
for chat in chats:
|
| 88 |
+
token_ids.append(chat.chat_template_token_ids)
|
| 89 |
+
return torch.cat(token_ids)
|
src_code_for_reproducibility/chat_utils/chat_turn.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/chat_utils/chat_turn.py
|
| 3 |
+
Summary: Defines the ChatTurn schema plus helpers for serialization and validation.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any, List, Literal, Optional, Tuple
|
| 12 |
+
|
| 13 |
+
import jsonschema
|
| 14 |
+
import torch
|
| 15 |
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
| 16 |
+
|
| 17 |
+
AgentId = str
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ChatTurn(BaseModel):
|
| 21 |
+
model_config = ConfigDict(arbitrary_types_allowed=True) # needed for torch tensors
|
| 22 |
+
|
| 23 |
+
role: str = Field(pattern="^(user|assistant)$")
|
| 24 |
+
agent_id: AgentId # ID of the agent with which the chat occured
|
| 25 |
+
content: str
|
| 26 |
+
reasoning_content: str | None = None
|
| 27 |
+
chat_template_token_ids: torch.LongTensor | None = None # Token ids of chat template format. For example, token ids of "<assistant>{content}</assistant>""
|
| 28 |
+
out_token_ids: torch.LongTensor | None = (
|
| 29 |
+
None # tokens generated from inference engine
|
| 30 |
+
)
|
| 31 |
+
log_probs: torch.FloatTensor | None = None
|
| 32 |
+
is_state_end: bool = False # indicates whether this chat turn marks the end of a state in the trajectory
|
src_code_for_reproducibility/chat_utils/template_specific.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/chat_utils/template_specific.py
|
| 3 |
+
Summary: Stores chat template variants and assistant postfix tensors per tokenizer.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import huggingface_hub
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import AutoTokenizer
|
| 9 |
+
|
| 10 |
+
custom_llama3_template = """
|
| 11 |
+
{%- if add_system_prompt %}
|
| 12 |
+
{{- '<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nCutting Knowledge Date: December 2023\nToday Date: 26 Jul 2024\n\n<|eot_id|>' }}
|
| 13 |
+
{%- endif %}
|
| 14 |
+
{%- for message in messages %}
|
| 15 |
+
{{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' }}
|
| 16 |
+
{%- endfor %}
|
| 17 |
+
|
| 18 |
+
{%- if add_generation_prompt %}
|
| 19 |
+
{{- '<|start_header_id|>' + 'assistant' + '<|end_header_id|>\n\n' }}
|
| 20 |
+
{%- endif %}
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
qwen2_assistant_postfix = (
|
| 24 |
+
AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
|
| 25 |
+
.encode("\n", return_tensors="pt")
|
| 26 |
+
.flatten()
|
| 27 |
+
)
|
| 28 |
+
qwen3_assistant_postfix = (
|
| 29 |
+
AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
|
| 30 |
+
.encode("\n", return_tensors="pt")
|
| 31 |
+
.flatten()
|
| 32 |
+
)
|
| 33 |
+
gemma3_assistant_postfix = (
|
| 34 |
+
AutoTokenizer.from_pretrained("google/gemma-3-4b-it")
|
| 35 |
+
.encode("\n", return_tensors="pt")
|
| 36 |
+
.flatten()
|
| 37 |
+
)
|
| 38 |
+
custom_qwen2_template = """
|
| 39 |
+
{%- if add_system_prompt %}
|
| 40 |
+
{{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
|
| 41 |
+
{%- endif %}
|
| 42 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 43 |
+
{%- for message in messages %}
|
| 44 |
+
{%- if message.content is string %}
|
| 45 |
+
{%- set content = message.content %}
|
| 46 |
+
{%- else %}
|
| 47 |
+
{%- set content = '' %}
|
| 48 |
+
{%- endif %}
|
| 49 |
+
{%- if (message.role == "user") %}
|
| 50 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 51 |
+
{%- elif message.role == "assistant" %}
|
| 52 |
+
{%- set reasoning_content = '' %}
|
| 53 |
+
{%- if message.reasoning_content is string %}
|
| 54 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 55 |
+
{%- else %}
|
| 56 |
+
{%- if '</think>' in content %}
|
| 57 |
+
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
|
| 58 |
+
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
|
| 59 |
+
{%- endif %}
|
| 60 |
+
{%- endif %}
|
| 61 |
+
{%- if loop.index0 > ns.last_query_index %}
|
| 62 |
+
{%- if reasoning_content %}
|
| 63 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
|
| 64 |
+
{%- else %}
|
| 65 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 66 |
+
{%- endif %}
|
| 67 |
+
{%- else %}
|
| 68 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 69 |
+
{%- endif %}
|
| 70 |
+
{{- '<|im_end|>\n' }}
|
| 71 |
+
{%- endif %}
|
| 72 |
+
{%- endfor %}
|
| 73 |
+
{%- if add_generation_prompt %}
|
| 74 |
+
{{- '<|im_start|>assistant\n' }}
|
| 75 |
+
{%- endif %}
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
custom_qwen3_template = """
|
| 79 |
+
{%- for message in messages %}
|
| 80 |
+
{%- if message.content is string %}
|
| 81 |
+
{%- set content = message.content %}
|
| 82 |
+
{%- else %}
|
| 83 |
+
{%- set content = '' %}
|
| 84 |
+
{%- endif %}
|
| 85 |
+
{%- if (message.role == "user") %}
|
| 86 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 87 |
+
{%- elif message.role == "assistant" %}
|
| 88 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 89 |
+
{%- endif %}
|
| 90 |
+
{%- endfor %}
|
| 91 |
+
{%- if add_generation_prompt %}
|
| 92 |
+
{{- '<|im_start|>assistant\n' }}
|
| 93 |
+
{%- if enable_thinking is defined and enable_thinking is false %}
|
| 94 |
+
{{- '<think>\n\n</think>\n\n' }}
|
| 95 |
+
{%- endif %}
|
| 96 |
+
{%- endif %}
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
custom_gemma3_template = """
|
| 100 |
+
{%- if add_system_prompt %}
|
| 101 |
+
{{- bos_token -}}
|
| 102 |
+
{%- endif %}
|
| 103 |
+
{%- for message in messages -%}
|
| 104 |
+
{%- if message['role'] == 'assistant' -%}
|
| 105 |
+
{%- set role = 'model' -%}
|
| 106 |
+
{%- else -%}
|
| 107 |
+
{%- set role = message['role'] -%}
|
| 108 |
+
{%- endif -%}
|
| 109 |
+
{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}
|
| 110 |
+
{%- endfor -%}
|
| 111 |
+
{%- if add_generation_prompt -%}
|
| 112 |
+
{{ '<start_of_turn>model\n' }}
|
| 113 |
+
{%- endif -%}
|
| 114 |
+
"""
|
src_code_for_reproducibility/markov_games/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/__init__.py
|
| 3 |
+
Summary: Makes Markov-game subpackages importable from the top-level namespace.
|
| 4 |
+
"""
|
src_code_for_reproducibility/markov_games/__pycache__/alternative_actions_runner.cpython-312.pyc
ADDED
|
Binary file (5.43 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/__pycache__/mg_utils.cpython-312.pyc
ADDED
|
Binary file (4.07 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc
ADDED
|
Binary file (3.97 kB). View file
|
|
|
src_code_for_reproducibility/markov_games/agent.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/agent.py
|
| 3 |
+
Summary: Declares the base Agent interface connecting simulations to policy calls.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from typing import Any, Tuple
|
| 9 |
+
|
| 10 |
+
from numpy.random import default_rng
|
| 11 |
+
|
| 12 |
+
from mllm.markov_games.rollout_tree import AgentActLog
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Agent(ABC):
|
| 16 |
+
"""Abstract policy wrapper that bridges simulations with arbitrary backends."""
|
| 17 |
+
|
| 18 |
+
@abstractmethod
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
seed: int,
|
| 22 |
+
agent_id: str,
|
| 23 |
+
agent_name: str,
|
| 24 |
+
agent_policy: Callable[[list[dict]], str],
|
| 25 |
+
*args,
|
| 26 |
+
**kwargs,
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
Initialize the agent state and seed its RNG.
|
| 30 |
+
|
| 31 |
+
Subclasses typically store extra handles (tokenizers, inference clients, etc.)
|
| 32 |
+
but they should always call ``super().__init__`` so sampling remains reproducible.
|
| 33 |
+
"""
|
| 34 |
+
self.seed = seed
|
| 35 |
+
self.agent_id = agent_id
|
| 36 |
+
self.agent_name = agent_name
|
| 37 |
+
self.policy = policy
|
| 38 |
+
self.rng = default_rng(self.seed)
|
| 39 |
+
raise NotImplementedError
|
| 40 |
+
|
| 41 |
+
async def act(self, observation) -> Tuple[Any, AgentActLog]:
|
| 42 |
+
"""
|
| 43 |
+
Produce the next action (and associated chat log) given an environment observation.
|
| 44 |
+
|
| 45 |
+
Implementations can iterate with rejection sampling, multi-call deliberation, etc.
|
| 46 |
+
Returns both the chosen action and an `AgentActLog` describing how it was produced.
|
| 47 |
+
"""
|
| 48 |
+
raise NotImplementedError
|
| 49 |
+
|
| 50 |
+
def get_safe_copy(self):
|
| 51 |
+
"""
|
| 52 |
+
Return a deep copy whose future calls do not mutate the original agent.
|
| 53 |
+
|
| 54 |
+
Needed for branch exploration/reruns with alternative actions.
|
| 55 |
+
"""
|
| 56 |
+
raise NotImplementedError
|
| 57 |
+
|
| 58 |
+
def reset(self):
|
| 59 |
+
"""Reset any internal state between rollouts."""
|
| 60 |
+
raise NotImplementedError
|
| 61 |
+
|
| 62 |
+
def render(self):
|
| 63 |
+
"""Optional human-readable visualization of the agent (CLI/UI)."""
|
| 64 |
+
raise NotImplementedError
|
| 65 |
+
|
| 66 |
+
def close(self):
|
| 67 |
+
"""Release any external resources (network sockets, subprocesses, etc.)."""
|
| 68 |
+
raise NotImplementedError
|
| 69 |
+
|
| 70 |
+
def get_agent_info(self):
|
| 71 |
+
"""Return diagnostic metadata to embed inside rollout logs."""
|
| 72 |
+
raise NotImplementedError
|
src_code_for_reproducibility/markov_games/alternative_actions_runner.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/alternative_actions_runner.py
|
| 3 |
+
Summary: Generates rollout branches by replaying trajectories with unilateral action changes.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import copy
|
| 8 |
+
import json
|
| 9 |
+
import os.path
|
| 10 |
+
from typing import Any, Tuple
|
| 11 |
+
|
| 12 |
+
from mllm.markov_games.markov_game import AgentAndActionSafeCopy, MarkovGame
|
| 13 |
+
from mllm.markov_games.rollout_tree import (
|
| 14 |
+
AgentActLog,
|
| 15 |
+
RolloutTreeBranchNode,
|
| 16 |
+
RolloutTreeNode,
|
| 17 |
+
RolloutTreeRootNode,
|
| 18 |
+
StepLog,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
AgentId = str
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
async def run_with_unilateral_alt_action(
|
| 25 |
+
markov_game: MarkovGame,
|
| 26 |
+
agent_id: AgentId,
|
| 27 |
+
time_step: int,
|
| 28 |
+
branch_node: RolloutTreeBranchNode,
|
| 29 |
+
max_depth: int,
|
| 30 |
+
):
|
| 31 |
+
"""
|
| 32 |
+
Roll out a counterfactual branch where ``agent_id`` deviates unilaterally.
|
| 33 |
+
|
| 34 |
+
Starting from ``branch_node`` (which already contains the main trajectory),
|
| 35 |
+
we replay the simulation with the deviating agent's action while freezing
|
| 36 |
+
all other agents/actions, then continue for ``max_depth`` steps.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
# Generate alternative action and take a step
|
| 40 |
+
await markov_game.set_action_of_agent(agent_id)
|
| 41 |
+
terminated: bool = markov_game.take_simulation_step()
|
| 42 |
+
step_log = markov_game.get_step_log()
|
| 43 |
+
first_alternative_node = RolloutTreeNode(
|
| 44 |
+
step_log=step_log,
|
| 45 |
+
time_step=time_step,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Generate rest of trajectory up to max depth
|
| 49 |
+
time_step += 1
|
| 50 |
+
counter = 1
|
| 51 |
+
previous_node = first_alternative_node
|
| 52 |
+
while not terminated and counter <= max_depth:
|
| 53 |
+
terminated, step_log = await markov_game.step()
|
| 54 |
+
current_node = RolloutTreeNode(step_log=step_log, time_step=time_step)
|
| 55 |
+
previous_node.child = current_node
|
| 56 |
+
previous_node = current_node
|
| 57 |
+
counter += 1
|
| 58 |
+
time_step += 1
|
| 59 |
+
|
| 60 |
+
if branch_node.branches == None:
|
| 61 |
+
branch_node.branches = {agent_id: [first_alternative_node]}
|
| 62 |
+
else:
|
| 63 |
+
agent_branches = branch_node.branches.get(agent_id, [])
|
| 64 |
+
agent_branches.append(first_alternative_node)
|
| 65 |
+
branch_node.branches[agent_id] = agent_branches
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
async def AlternativeActionsRunner(
|
| 69 |
+
markov_game: MarkovGame,
|
| 70 |
+
output_folder: str,
|
| 71 |
+
nb_alternative_actions: int,
|
| 72 |
+
max_depth: int,
|
| 73 |
+
branch_only_on_new_round: bool = False,
|
| 74 |
+
):
|
| 75 |
+
"""
|
| 76 |
+
Generate a rollout tree containing the main path plus unilateral deviation branches.
|
| 77 |
+
|
| 78 |
+
For each timestep we:
|
| 79 |
+
1. Cache agent actions without side effects.
|
| 80 |
+
2. Advance the main trajectory.
|
| 81 |
+
3. Spawn ``nb_alternative_actions`` asynchronous deviations per agent,
|
| 82 |
+
each replaying up to ``max_depth`` steps from the cached pre-action state.
|
| 83 |
+
The resulting branches feed advantage-alignment estimators.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
tasks = []
|
| 87 |
+
time_step = 0
|
| 88 |
+
terminated = False
|
| 89 |
+
root = RolloutTreeRootNode(id=markov_game.get_id(), crn_id=markov_game.get_crn_id())
|
| 90 |
+
previous_node = root
|
| 91 |
+
|
| 92 |
+
while not terminated:
|
| 93 |
+
mg_before_action = markov_game.get_safe_copy()
|
| 94 |
+
|
| 95 |
+
# Get safe copies for main branch
|
| 96 |
+
agent_action_safe_copies: dict[
|
| 97 |
+
AgentId, AgentAndActionSafeCopy
|
| 98 |
+
] = await markov_game.get_actions_of_agents_without_side_effects()
|
| 99 |
+
|
| 100 |
+
markov_game.set_actions_of_agents_manually(agent_action_safe_copies)
|
| 101 |
+
terminated = markov_game.take_simulation_step()
|
| 102 |
+
main_node = RolloutTreeNode(
|
| 103 |
+
step_log=markov_game.get_step_log(), time_step=time_step
|
| 104 |
+
)
|
| 105 |
+
branch_node = RolloutTreeBranchNode(main_child=main_node)
|
| 106 |
+
previous_node.child = branch_node
|
| 107 |
+
previous_node = main_node
|
| 108 |
+
|
| 109 |
+
# Get alternative branches by generating new unilateral actions
|
| 110 |
+
for agent_id in markov_game.agent_ids:
|
| 111 |
+
for _ in range(nb_alternative_actions):
|
| 112 |
+
# Get safe copies for branches
|
| 113 |
+
branch_agent_action_safe_copies: dict[
|
| 114 |
+
AgentId, AgentAndActionSafeCopy
|
| 115 |
+
] = {
|
| 116 |
+
agent_id: AgentAndActionSafeCopy(
|
| 117 |
+
action=copy.deepcopy(agent_action_safe_copy.action),
|
| 118 |
+
action_info=copy.deepcopy(agent_action_safe_copy.action_info),
|
| 119 |
+
agent_after_action=agent_action_safe_copy.agent_after_action.get_safe_copy(),
|
| 120 |
+
)
|
| 121 |
+
for agent_id, agent_action_safe_copy in agent_action_safe_copies.items()
|
| 122 |
+
}
|
| 123 |
+
mg_branch: MarkovGame = mg_before_action.get_safe_copy()
|
| 124 |
+
other_agent_id = [id for id in mg_branch.agent_ids if id != agent_id][0]
|
| 125 |
+
mg_branch.set_action_and_agent_after_action_manually(
|
| 126 |
+
agent_id=other_agent_id,
|
| 127 |
+
agent_action_safe_copy=branch_agent_action_safe_copies[
|
| 128 |
+
other_agent_id
|
| 129 |
+
],
|
| 130 |
+
)
|
| 131 |
+
task = asyncio.create_task(
|
| 132 |
+
run_with_unilateral_alt_action(
|
| 133 |
+
markov_game=mg_branch,
|
| 134 |
+
time_step=time_step,
|
| 135 |
+
agent_id=agent_id,
|
| 136 |
+
branch_node=branch_node,
|
| 137 |
+
max_depth=max_depth,
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
tasks.append(task)
|
| 141 |
+
time_step += 1
|
| 142 |
+
|
| 143 |
+
# wait for all branches to complete
|
| 144 |
+
await asyncio.gather(*tasks)
|
| 145 |
+
|
| 146 |
+
return root
|
src_code_for_reproducibility/markov_games/group_timesteps.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/group_timesteps.py
|
| 3 |
+
Summary: Provides timestep-grouping utilities for rollout trees and training.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 7 |
+
from typing import Callable
|
| 8 |
+
|
| 9 |
+
from mllm.markov_games.markov_game import MarkovGame
|
| 10 |
+
from mllm.markov_games.rollout_tree import (
|
| 11 |
+
AgentActLog,
|
| 12 |
+
RolloutTreeBranchNode,
|
| 13 |
+
RolloutTreeNode,
|
| 14 |
+
RolloutTreeRootNode,
|
| 15 |
+
StepLog,
|
| 16 |
+
)
|
| 17 |
+
from mllm.markov_games.simulation import SimulationStepLog
|
| 18 |
+
|
| 19 |
+
AgentId = str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def group_time_steps(
|
| 23 |
+
rollout_tree: RolloutTreeRootNode,
|
| 24 |
+
accumulation_stop_condition: Callable[[StepLog], bool],
|
| 25 |
+
) -> RolloutTreeRootNode:
|
| 26 |
+
"""
|
| 27 |
+
During generation, we create rollout trees according to the real time steps.
|
| 28 |
+
However, during training, we might want to treat groups of time steps as a single time step.
|
| 29 |
+
As a concrete example, take Trust-and-Split. At each round, say we have X time steps of communication and then one time step for the split.
|
| 30 |
+
Then the communication actions will not get any reward, and the split action will get the reward. During REINFORCE training, with discounting, this
|
| 31 |
+
can cause training instability. We could instead treat every action in the round as being part of a single action, and give it the reward of the split action.
|
| 32 |
+
This method helps to do this sort of grouping.
|
| 33 |
+
It accumulates actions until the accumulation_stop_condition is met, and then creates a new node with the accumulated actions.
|
| 34 |
+
It then recursively calls itself on the child node.
|
| 35 |
+
Details:
|
| 36 |
+
- The reward for the group is the reward of the last time step in the group.
|
| 37 |
+
- The simulation log for the group is the simulation log of the last time step in the group.
|
| 38 |
+
- The state end for the group becomes the first state end in the group.
|
| 39 |
+
- The agent info for the group is the agent info of the last time step in the group.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def group_step_logs(step_logs: list[StepLog]) -> StepLog:
|
| 43 |
+
"""
|
| 44 |
+
Concatenate per-agent chat turns across steps; keep only the first is_state_end.
|
| 45 |
+
"""
|
| 46 |
+
last_sim_log = step_logs[-1].simulation_step_log
|
| 47 |
+
agent_ids = {aid for s in step_logs for aid in s.action_logs.keys()}
|
| 48 |
+
grouped_logs: dict[AgentId, AgentActLog] = {}
|
| 49 |
+
for aid in agent_ids:
|
| 50 |
+
turns = []
|
| 51 |
+
for s in step_logs:
|
| 52 |
+
act = s.action_logs.get(aid)
|
| 53 |
+
if act and act.chat_turns:
|
| 54 |
+
turns.extend(copy.deepcopy(act.chat_turns))
|
| 55 |
+
disable_is_state_end = False
|
| 56 |
+
# Only the first state_end should be True, the rest should be False
|
| 57 |
+
for t in turns:
|
| 58 |
+
if t.is_state_end:
|
| 59 |
+
if disable_is_state_end:
|
| 60 |
+
t.is_state_end = False
|
| 61 |
+
else:
|
| 62 |
+
disable_is_state_end = True
|
| 63 |
+
continue
|
| 64 |
+
grouped_logs[aid] = AgentActLog(
|
| 65 |
+
chat_turns=turns, info=step_logs[-1].action_logs[aid].info
|
| 66 |
+
)
|
| 67 |
+
return StepLog(action_logs=grouped_logs, simulation_step_log=last_sim_log)
|
| 68 |
+
|
| 69 |
+
def group_time_steps_rec(
|
| 70 |
+
current_node: RolloutTreeNode | RolloutTreeBranchNode,
|
| 71 |
+
group_time_step: int,
|
| 72 |
+
accumulation_step_logs: list[StepLog],
|
| 73 |
+
) -> RolloutTreeNode | RolloutTreeBranchNode:
|
| 74 |
+
"""
|
| 75 |
+
Groups time steps. Recursion is used to handle branches.
|
| 76 |
+
"""
|
| 77 |
+
assert isinstance(current_node, RolloutTreeNode) or isinstance(
|
| 78 |
+
current_node, RolloutTreeBranchNode
|
| 79 |
+
), "Current node must be a tree node or a branch node. Is of type: " + str(
|
| 80 |
+
type(current_node)
|
| 81 |
+
)
|
| 82 |
+
first_group_node = None
|
| 83 |
+
current_group_node = None
|
| 84 |
+
while current_node is not None:
|
| 85 |
+
if isinstance(current_node, RolloutTreeBranchNode):
|
| 86 |
+
raise Exception(
|
| 87 |
+
"Grouping timesteps by round is not supported for branching trajectories yet."
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# Accumulate
|
| 91 |
+
accumulation_step_logs.append(current_node.step_log)
|
| 92 |
+
if accumulation_stop_condition(current_node.step_log):
|
| 93 |
+
grouped_step_logs = group_step_logs(accumulation_step_logs)
|
| 94 |
+
accumulation_step_logs = []
|
| 95 |
+
new_group_node = RolloutTreeNode(
|
| 96 |
+
step_log=grouped_step_logs, time_step=group_time_step, child=None
|
| 97 |
+
)
|
| 98 |
+
if first_group_node == None:
|
| 99 |
+
first_group_node = new_group_node
|
| 100 |
+
group_time_step += 1
|
| 101 |
+
if current_group_node is not None:
|
| 102 |
+
current_group_node.child = new_group_node
|
| 103 |
+
current_group_node = new_group_node
|
| 104 |
+
current_node = current_node.child
|
| 105 |
+
return first_group_node
|
| 106 |
+
|
| 107 |
+
node = group_time_steps_rec(
|
| 108 |
+
current_node=rollout_tree.child, group_time_step=0, accumulation_step_logs=[]
|
| 109 |
+
)
|
| 110 |
+
return RolloutTreeRootNode(
|
| 111 |
+
id=rollout_tree.id,
|
| 112 |
+
crn_id=rollout_tree.crn_id,
|
| 113 |
+
child=node,
|
| 114 |
+
agent_ids=rollout_tree.agent_ids,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def stop_when_round_ends(step_log: StepLog) -> bool:
|
| 119 |
+
"""
|
| 120 |
+
Simplest stop condition. Will return True if step log is the last time step of a round.
|
| 121 |
+
This will throw an error if this information is not available in the simulation info.
|
| 122 |
+
"""
|
| 123 |
+
assert (
|
| 124 |
+
"is_last_timestep_in_round" in step_log.simulation_step_log.info.keys()
|
| 125 |
+
), "To group by round, is_last_timestep_in_round must be set in the info of your simulation step log at each time step."
|
| 126 |
+
return step_log.simulation_step_log.info["is_last_timestep_in_round"]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def group_by_round(rollout_tree: RolloutTreeRootNode) -> RolloutTreeRootNode:
|
| 130 |
+
"""
|
| 131 |
+
Groups time steps by round.
|
| 132 |
+
"""
|
| 133 |
+
return group_time_steps(rollout_tree, stop_when_round_ends)
|
src_code_for_reproducibility/markov_games/linear_runner.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/linear_runner.py
|
| 3 |
+
Summary: Simulates a single unbranched Markov-game rollout and records it.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import json
|
| 8 |
+
import os.path
|
| 9 |
+
|
| 10 |
+
from mllm.markov_games.markov_game import MarkovGame
|
| 11 |
+
from mllm.markov_games.rollout_tree import RolloutTreeNode, RolloutTreeRootNode
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
async def LinearRunner(
|
| 15 |
+
markov_game: MarkovGame, output_folder: str
|
| 16 |
+
) -> RolloutTreeRootNode:
|
| 17 |
+
"""
|
| 18 |
+
Generate a single main-path rollout (no branching) for the provided Markov game.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
markov_game:
|
| 23 |
+
Initialized ``MarkovGame`` with agents + simulation ready to step.
|
| 24 |
+
output_folder:
|
| 25 |
+
Unused placeholder in the legacy API (kept for compatibility).
|
| 26 |
+
"""
|
| 27 |
+
time_step = 0
|
| 28 |
+
terminated = False
|
| 29 |
+
root = RolloutTreeRootNode(
|
| 30 |
+
id=markov_game.get_id(),
|
| 31 |
+
crn_id=markov_game.get_crn_id(),
|
| 32 |
+
agent_ids=markov_game.get_agent_ids(),
|
| 33 |
+
)
|
| 34 |
+
previous_node = root
|
| 35 |
+
while not terminated:
|
| 36 |
+
terminated, step_log = await markov_game.step()
|
| 37 |
+
current_node = RolloutTreeNode(step_log=step_log, time_step=time_step)
|
| 38 |
+
previous_node.child = current_node
|
| 39 |
+
previous_node = current_node
|
| 40 |
+
time_step += 1
|
| 41 |
+
|
| 42 |
+
return root
|
src_code_for_reproducibility/markov_games/markov_game.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/markov_game.py
|
| 3 |
+
Summary: Defines the MarkovGame base class plus shared simulation interfaces.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import copy
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from typing import Any, List, Literal, Optional, Tuple
|
| 12 |
+
|
| 13 |
+
from transformers.models.idefics2 import Idefics2Config
|
| 14 |
+
|
| 15 |
+
from mllm.markov_games.agent import Agent
|
| 16 |
+
from mllm.markov_games.rollout_tree import AgentActLog, StepLog
|
| 17 |
+
from mllm.markov_games.simulation import Simulation
|
| 18 |
+
|
| 19 |
+
AgentId = str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class AgentAndActionSafeCopy:
|
| 24 |
+
"""Snapshot of an agent, its action, and metadata used for branch replay."""
|
| 25 |
+
|
| 26 |
+
action: Any
|
| 27 |
+
action_info: AgentActLog
|
| 28 |
+
agent_after_action: type[Agent]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class MarkovGame(object):
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
id: int,
|
| 35 |
+
agents: dict[AgentId, type[Agent]],
|
| 36 |
+
simulation: type[Simulation],
|
| 37 |
+
crn_id: int,
|
| 38 |
+
):
|
| 39 |
+
"""
|
| 40 |
+
Initialize the Markov game wrapper.
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
id:
|
| 45 |
+
Unique rollout identifier (logged into rollout trees).
|
| 46 |
+
agents:
|
| 47 |
+
Mapping of agent_id -> Agent instance.
|
| 48 |
+
simulation:
|
| 49 |
+
Environment implementing the ``Simulation`` interface (IPD, TAS, etc.).
|
| 50 |
+
crn_id:
|
| 51 |
+
Identifier for the common random number stream used by this rollout.
|
| 52 |
+
"""
|
| 53 |
+
self.agents = agents
|
| 54 |
+
self.agent_ids = self.agents.keys()
|
| 55 |
+
self.simulation = simulation
|
| 56 |
+
self.simulation_step_log = None
|
| 57 |
+
self.agent_step_logs = {agent_id: None for agent_id in self.agent_ids}
|
| 58 |
+
self.actions = {}
|
| 59 |
+
self.id = id
|
| 60 |
+
self.crn_id = crn_id
|
| 61 |
+
|
| 62 |
+
def get_id(self) -> str:
|
| 63 |
+
return self.id
|
| 64 |
+
|
| 65 |
+
def get_crn_id(self) -> int:
|
| 66 |
+
return self.crn_id
|
| 67 |
+
|
| 68 |
+
def get_agent_ids(self) -> List[AgentId]:
|
| 69 |
+
return list(self.agent_ids)
|
| 70 |
+
|
| 71 |
+
async def get_action_of_agent_without_side_effects(
|
| 72 |
+
self, agent_id: AgentId
|
| 73 |
+
) -> Tuple[Any, AgentActLog]:
|
| 74 |
+
"""
|
| 75 |
+
Safe function to get an action of an agent without modifying the agent or the simulation.
|
| 76 |
+
"""
|
| 77 |
+
agent = self.agents[agent_id]
|
| 78 |
+
agent_before_action = agent.get_safe_copy()
|
| 79 |
+
obs = self.simulation.get_obs_agent(agent_id)
|
| 80 |
+
action, action_info = await agent.act(observation=obs)
|
| 81 |
+
self.agents[agent_id] = agent_before_action
|
| 82 |
+
agent_after_action = agent.get_safe_copy()
|
| 83 |
+
return AgentAndActionSafeCopy(action, action_info, agent_after_action)
|
| 84 |
+
|
| 85 |
+
async def get_actions_of_agents_without_side_effects(
|
| 86 |
+
self,
|
| 87 |
+
) -> dict[AgentId, AgentAndActionSafeCopy]:
|
| 88 |
+
"""
|
| 89 |
+
Safe function to get an action of an agent without modifying the agent or the simulation.
|
| 90 |
+
"""
|
| 91 |
+
tasks = []
|
| 92 |
+
for agent_id in self.agent_ids:
|
| 93 |
+
task = asyncio.create_task(
|
| 94 |
+
self.get_action_of_agent_without_side_effects(agent_id)
|
| 95 |
+
)
|
| 96 |
+
tasks.append(task)
|
| 97 |
+
agent_and_action_safe_copies: list[
|
| 98 |
+
AgentAndActionSafeCopy
|
| 99 |
+
] = await asyncio.gather(*tasks)
|
| 100 |
+
return {
|
| 101 |
+
agent_id: agent_and_action_safe_copy
|
| 102 |
+
for agent_id, agent_and_action_safe_copy in zip(
|
| 103 |
+
self.agent_ids, agent_and_action_safe_copies
|
| 104 |
+
)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
def set_action_and_agent_after_action_manually(
|
| 108 |
+
self,
|
| 109 |
+
agent_id: AgentId,
|
| 110 |
+
agent_action_safe_copy: AgentAndActionSafeCopy,
|
| 111 |
+
):
|
| 112 |
+
"""
|
| 113 |
+
Set the action and the agent after action manually.
|
| 114 |
+
"""
|
| 115 |
+
self.actions[agent_id] = agent_action_safe_copy.action
|
| 116 |
+
self.agent_step_logs[agent_id] = agent_action_safe_copy.action_info
|
| 117 |
+
self.agents[agent_id] = agent_action_safe_copy.agent_after_action
|
| 118 |
+
|
| 119 |
+
def set_actions_of_agents_manually(
|
| 120 |
+
self, actions: dict[AgentId, AgentAndActionSafeCopy]
|
| 121 |
+
):
|
| 122 |
+
"""
|
| 123 |
+
Set the actions of agents manually.
|
| 124 |
+
"""
|
| 125 |
+
for agent_id, agent_action_safe_copy in actions.items():
|
| 126 |
+
self.set_action_and_agent_after_action_manually(
|
| 127 |
+
agent_id, agent_action_safe_copy
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
async def set_action_of_agent(self, agent_id: AgentId):
|
| 131 |
+
"""
|
| 132 |
+
Query a single agent for its next action and store the result locally.
|
| 133 |
+
"""
|
| 134 |
+
agent = self.agents[agent_id]
|
| 135 |
+
obs = self.simulation.get_obs_agent(agent_id)
|
| 136 |
+
action, action_info = await agent.act(observation=obs)
|
| 137 |
+
self.actions[agent_id] = action
|
| 138 |
+
self.agent_step_logs[agent_id] = action_info
|
| 139 |
+
|
| 140 |
+
async def set_actions(self):
|
| 141 |
+
"""
|
| 142 |
+
Query every agent concurrently and populate the cached actions/logs.
|
| 143 |
+
"""
|
| 144 |
+
# background_tasks = set()
|
| 145 |
+
tasks = []
|
| 146 |
+
for agent_id in self.agent_ids:
|
| 147 |
+
task = asyncio.create_task(self.set_action_of_agent(agent_id))
|
| 148 |
+
tasks.append(task)
|
| 149 |
+
await asyncio.gather(*tasks)
|
| 150 |
+
|
| 151 |
+
def take_simulation_step(self):
|
| 152 |
+
"""
|
| 153 |
+
Advance the simulation by one step using the cached actions.
|
| 154 |
+
"""
|
| 155 |
+
terminated, self.simulation_step_log = self.simulation.step(self.actions)
|
| 156 |
+
return terminated
|
| 157 |
+
|
| 158 |
+
def get_step_log(self) -> StepLog:
|
| 159 |
+
"""
|
| 160 |
+
Package the most recent simulation step and agent logs into a StepLog.
|
| 161 |
+
"""
|
| 162 |
+
if self.simulation_step_log is None:
|
| 163 |
+
raise RuntimeError(
|
| 164 |
+
"Simulation step log is empty; call take_simulation_step() first."
|
| 165 |
+
)
|
| 166 |
+
missing_logs = [
|
| 167 |
+
agent_id for agent_id, log in self.agent_step_logs.items() if log is None
|
| 168 |
+
]
|
| 169 |
+
if missing_logs:
|
| 170 |
+
raise RuntimeError(
|
| 171 |
+
f"Agent action logs missing for: {', '.join(missing_logs)}. "
|
| 172 |
+
"Ensure set_actions() ran before requesting the step log."
|
| 173 |
+
)
|
| 174 |
+
step_log = StepLog(
|
| 175 |
+
simulation_step_log=self.simulation_step_log,
|
| 176 |
+
action_logs=self.agent_step_logs,
|
| 177 |
+
)
|
| 178 |
+
return step_log
|
| 179 |
+
|
| 180 |
+
async def step(self) -> Tuple[bool, StepLog]:
|
| 181 |
+
"""
|
| 182 |
+
Convenience step that collects actions, advances the simulation, and returns the log.
|
| 183 |
+
"""
|
| 184 |
+
await self.set_actions()
|
| 185 |
+
terminated = self.take_simulation_step()
|
| 186 |
+
step_log = self.get_step_log()
|
| 187 |
+
return terminated, step_log
|
| 188 |
+
|
| 189 |
+
def get_safe_copy(self):
|
| 190 |
+
"""
|
| 191 |
+
Create a shallow copy of the game with deep-copied agents/simulation for branching.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
new_markov_game = copy.copy(self)
|
| 195 |
+
new_simulation = self.simulation.get_safe_copy()
|
| 196 |
+
new_agents = {
|
| 197 |
+
agent_id: agent.get_safe_copy() for agent_id, agent in self.agents.items()
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
# Reassign copied components
|
| 201 |
+
new_markov_game.simulation = new_simulation
|
| 202 |
+
new_markov_game.agents = new_agents
|
| 203 |
+
|
| 204 |
+
# IMPORTANT: ensure agent_ids references the new agents dict, not the original
|
| 205 |
+
new_markov_game.agent_ids = new_markov_game.agents.keys()
|
| 206 |
+
|
| 207 |
+
# Deep-copy step data to avoid correlation
|
| 208 |
+
new_markov_game.simulation_step_log = copy.deepcopy(self.simulation_step_log)
|
| 209 |
+
new_markov_game.actions = copy.deepcopy(self.actions)
|
| 210 |
+
# Rebuild logs to align exactly with new agent ids
|
| 211 |
+
old_agent_step_logs = copy.deepcopy(self.agent_step_logs)
|
| 212 |
+
new_markov_game.agent_step_logs = {
|
| 213 |
+
agent_id: old_agent_step_logs.get(agent_id)
|
| 214 |
+
for agent_id in new_markov_game.agent_ids
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
return new_markov_game
|
src_code_for_reproducibility/markov_games/mg_utils.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/mg_utils.py
|
| 3 |
+
Summary: Holds miscellaneous helpers shared across Markov-game modules.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import copy
|
| 8 |
+
from collections.abc import Callable
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
|
| 11 |
+
from mllm.markov_games.ipd.ipd_agent import IPDAgent
|
| 12 |
+
from mllm.markov_games.ipd.Ipd_hard_coded_agents import (
|
| 13 |
+
AlwaysCooperateIPDAgent,
|
| 14 |
+
AlwaysDefectIPDAgent,
|
| 15 |
+
)
|
| 16 |
+
from mllm.markov_games.ipd.ipd_simulation import IPD
|
| 17 |
+
from mllm.markov_games.markov_game import MarkovGame
|
| 18 |
+
from mllm.markov_games.negotiation.dond_agent import DealNoDealAgent
|
| 19 |
+
from mllm.markov_games.negotiation.dond_simulation import DealNoDealSimulation
|
| 20 |
+
from mllm.markov_games.negotiation.nego_hard_coded_policies import (
|
| 21 |
+
HardCodedNegoGreedyPolicy,
|
| 22 |
+
HardCodedNegoWelfareMaximizingPolicy,
|
| 23 |
+
)
|
| 24 |
+
from mllm.markov_games.negotiation.no_press_nego_agent import NoPressAgent
|
| 25 |
+
from mllm.markov_games.negotiation.no_press_nego_simulation import NoPressSimulation
|
| 26 |
+
from mllm.markov_games.negotiation.tas_rps_agent import TrustAndSplitRPSAgent
|
| 27 |
+
from mllm.markov_games.negotiation.tas_rps_simulation import TrustAndSplitRPSSimulation
|
| 28 |
+
from mllm.markov_games.rollout_tree import (
|
| 29 |
+
AgentActLog,
|
| 30 |
+
RolloutTreeBranchNode,
|
| 31 |
+
RolloutTreeNode,
|
| 32 |
+
RolloutTreeRootNode,
|
| 33 |
+
StepLog,
|
| 34 |
+
)
|
| 35 |
+
from mllm.markov_games.simulation import SimulationStepLog
|
| 36 |
+
|
| 37 |
+
AgentId = str
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class AgentConfig:
|
| 42 |
+
"""Configuration blob describing one agent in a Markov game spec."""
|
| 43 |
+
|
| 44 |
+
agent_id: str
|
| 45 |
+
agent_name: str
|
| 46 |
+
agent_class_name: str
|
| 47 |
+
policy_id: str
|
| 48 |
+
init_kwargs: dict
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass
|
| 52 |
+
class MarkovGameConfig:
|
| 53 |
+
"""Top-level config that ties together simulation settings and agent configs."""
|
| 54 |
+
|
| 55 |
+
id: int
|
| 56 |
+
seed: int
|
| 57 |
+
simulation_class_name: str
|
| 58 |
+
simulation_init_args: dict
|
| 59 |
+
agent_configs: list[AgentConfig]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def init_markov_game_components(
|
| 63 |
+
config: MarkovGameConfig, policies: dict[str, Callable[[list[dict]], str]]
|
| 64 |
+
):
|
| 65 |
+
"""
|
| 66 |
+
Materialize Agents and the Simulation described by ``config`` and return a MarkovGame.
|
| 67 |
+
|
| 68 |
+
`policies` is a mapping of policy_id -> callable retrieved from the hosting trainer.
|
| 69 |
+
"""
|
| 70 |
+
agents = {}
|
| 71 |
+
agent_names = []
|
| 72 |
+
for agent_config in config.agent_configs:
|
| 73 |
+
agent_id = agent_config.agent_id
|
| 74 |
+
agent_name = agent_config.agent_name
|
| 75 |
+
agent_class = eval(agent_config.agent_class_name)
|
| 76 |
+
agent = agent_class(
|
| 77 |
+
seed=config.seed,
|
| 78 |
+
agent_id=agent_id,
|
| 79 |
+
agent_name=agent_name,
|
| 80 |
+
policy=policies[agent_config.policy_id],
|
| 81 |
+
**agent_config.init_kwargs,
|
| 82 |
+
)
|
| 83 |
+
agents[agent_id] = agent
|
| 84 |
+
agent_names.append(agent_name)
|
| 85 |
+
simulation = eval(config.simulation_class_name)(
|
| 86 |
+
seed=config.seed,
|
| 87 |
+
agent_ids=list(agents.keys()),
|
| 88 |
+
agent_names=agent_names,
|
| 89 |
+
**config.simulation_init_args,
|
| 90 |
+
)
|
| 91 |
+
markov_game = MarkovGame(
|
| 92 |
+
id=config.id,
|
| 93 |
+
crn_id=config.seed,
|
| 94 |
+
agents=agents,
|
| 95 |
+
simulation=simulation,
|
| 96 |
+
)
|
| 97 |
+
return markov_game
|
src_code_for_reproducibility/markov_games/negotiation/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
- Multiple item types (e.g., hats, balls, books)
|
| 13 |
+
- The item values for each agent are public.
|
| 14 |
+
- No communication; agents go straight to making split proposals.
|
| 15 |
+
- Motivation: mirrors no‑communication setups (e.g., Advantage Alignment) while keeping the split decision nontrivial.
|
| 16 |
+
|
| 17 |
+
- Trust-and-Split RPS (TAS-RPS)
|
| 18 |
+
- Single item type (coins)
|
| 19 |
+
- 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.
|
| 20 |
+
- Each agent initially sees only their own hand and must communicate to coordinate an optimal split.
|
| 21 |
+
- Motivation: enforce large value disparity so one’s own value reveals little about the other’s (avoiding ceiling effects) and incentivize meaningful communication.
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
src_code_for_reproducibility/markov_games/negotiation/dond_agent.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/dond_agent.py
|
| 3 |
+
Summary: Agent implementation for Deal-or-No-Deal style negotiations.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 7 |
+
import re
|
| 8 |
+
from collections.abc import Callable
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Any, Dict, List, Tuple
|
| 11 |
+
|
| 12 |
+
from mllm.markov_games.agent import Agent
|
| 13 |
+
from mllm.markov_games.negotiation.dond_simulation import DealNoDealObs
|
| 14 |
+
from mllm.markov_games.negotiation.nego_agent import (
|
| 15 |
+
NegotiationAgent,
|
| 16 |
+
NegotiationAgentState,
|
| 17 |
+
)
|
| 18 |
+
from mllm.markov_games.negotiation.nego_simulation import Split
|
| 19 |
+
from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class DealNoDealAgent(NegotiationAgent):
|
| 23 |
+
"""NegotiationAgent tailored to the Deal-or-No-Deal stock/value revelation rules."""
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
*args,
|
| 28 |
+
**kwargs,
|
| 29 |
+
):
|
| 30 |
+
super().__init__(*args, **kwargs)
|
| 31 |
+
self.intro_prompt = (
|
| 32 |
+
"You are {agent_id}. You are playing an iterated game. "
|
| 33 |
+
"At each round, you and other agent will try to distribute among yourselves items of types {item_types}. "
|
| 34 |
+
"You only know how much you value each item type, but not the other agent's values. "
|
| 35 |
+
"You can communicate with the other agent by sending up to {quota_messages_per_agent_per_round} short messages per round. "
|
| 36 |
+
"Each round, after exchanging messages, you and the other agent will submit a private proposal. "
|
| 37 |
+
"A deal is accepted only if both proposals match exactly and are within stock; otherwise no deal (0 points for both at that round). "
|
| 38 |
+
"The values of the items of the other agent at the previous round are revealed to you after each round. "
|
| 39 |
+
"Your goal is: {goal}."
|
| 40 |
+
)
|
| 41 |
+
self.new_round_prompt = (
|
| 42 |
+
"New round {round_nb}. Items: {stock}. Your values: {values}. "
|
| 43 |
+
)
|
| 44 |
+
self.last_round_prompt = (
|
| 45 |
+
"Last round, other agent's values: {previous_values_coagent}. "
|
| 46 |
+
)
|
| 47 |
+
self.send_split_prompt = "Respond with <split>...</split> where you propose how many items of each type you want to keep."
|
| 48 |
+
|
| 49 |
+
def get_message_regex(self, observation: DealNoDealObs) -> str:
|
| 50 |
+
"""Allow short XML messages (<400 chars) between proposal phases."""
|
| 51 |
+
return r"<message>[\s\S]{0,400}</message>"
|
| 52 |
+
|
| 53 |
+
def get_split_regex(self, observation: DealNoDealObs) -> str:
|
| 54 |
+
"""Constrain split proposals to per-item XML tags bounded by the current stock."""
|
| 55 |
+
parts = []
|
| 56 |
+
for t in observation.item_types:
|
| 57 |
+
s = int(observation.quantities.get(t, 0))
|
| 58 |
+
allowed = "|".join(str(k) for k in range(0, s + 1))
|
| 59 |
+
rng = f"({allowed})"
|
| 60 |
+
parts.append(rf"<{t}>{rng}</{t}>")
|
| 61 |
+
items_block = "".join(parts)
|
| 62 |
+
return rf"(<split>{items_block}</split>)"
|
| 63 |
+
|
| 64 |
+
def get_split_action(self, policy_output: str, observation: DealNoDealObs) -> Split:
|
| 65 |
+
"""Convert the XML proposal into a Split dataclass understood by the simulator."""
|
| 66 |
+
import re as _re
|
| 67 |
+
|
| 68 |
+
allocations: Dict[str, int] = {}
|
| 69 |
+
for t in observation.item_types:
|
| 70 |
+
m = _re.search(rf"<{t}>([0-9]+)</{t}>", policy_output)
|
| 71 |
+
if m:
|
| 72 |
+
allocations[t] = int(m.group(1))
|
| 73 |
+
else:
|
| 74 |
+
allocations[t] = 0
|
| 75 |
+
return Split(items_given_to_self=allocations)
|
src_code_for_reproducibility/markov_games/negotiation/dond_simulation.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/dond_simulation.py
|
| 3 |
+
Summary: Simulates Deal-or-No-Deal negotiation games and logs rollouts.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 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.negotiation.nego_simulation import (
|
| 13 |
+
NegotiationObs,
|
| 14 |
+
NegotiationSimulation,
|
| 15 |
+
NegotiationState,
|
| 16 |
+
Split,
|
| 17 |
+
)
|
| 18 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 19 |
+
from mllm.utils.get_coagent_id import get_coagent_id
|
| 20 |
+
|
| 21 |
+
AgentId = str
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class DealNoDealState(NegotiationState):
|
| 26 |
+
"""NegotiationState with per-agent value tables and item taxonomy."""
|
| 27 |
+
|
| 28 |
+
item_types: List[str]
|
| 29 |
+
values: Dict[AgentId, Dict[str, int]]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass
|
| 33 |
+
class DealNoDealObs(NegotiationObs):
|
| 34 |
+
"""Observation that reveals own values and (lagged) opponent values."""
|
| 35 |
+
|
| 36 |
+
my_values: Dict[str, int]
|
| 37 |
+
item_types: List[str]
|
| 38 |
+
previous_values_coagent: Dict[str, int] | None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def random_partition_integer(rng, total: int, parts: int) -> List[int]:
|
| 42 |
+
"""Sample non-negative integers summing to ``total`` across ``parts`` buckets."""
|
| 43 |
+
if parts <= 0:
|
| 44 |
+
return []
|
| 45 |
+
if total <= 0:
|
| 46 |
+
return [0 for _ in range(parts)]
|
| 47 |
+
cuts = sorted(rng.integers(0, total + 1, size=parts - 1).tolist())
|
| 48 |
+
vals = []
|
| 49 |
+
prev = 0
|
| 50 |
+
for c in cuts + [total]:
|
| 51 |
+
vals.append(c - prev)
|
| 52 |
+
prev = c
|
| 53 |
+
return vals
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class DealNoDealSimulation(NegotiationSimulation):
|
| 57 |
+
"""NegotiationSimulation variant implementing the Rubinstein-style Deal-or-No-Deal."""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
item_types: List[str] = ["books", "hats", "balls"],
|
| 62 |
+
*args,
|
| 63 |
+
**kwargs,
|
| 64 |
+
):
|
| 65 |
+
super().__init__(item_types=item_types, *args, **kwargs)
|
| 66 |
+
self.reset()
|
| 67 |
+
|
| 68 |
+
def _other(self, agent_id: AgentId) -> AgentId:
|
| 69 |
+
return get_coagent_id(self.agent_ids, agent_id)
|
| 70 |
+
|
| 71 |
+
def _sample_stock(self) -> Dict[str, int]:
|
| 72 |
+
# total items between 5 and 7
|
| 73 |
+
total_items = int(self.rng.integers(5, 8))
|
| 74 |
+
# nonnegative per-type counts summing to total_items
|
| 75 |
+
parts = random_partition_integer(self.rng, total_items, len(self.item_types))
|
| 76 |
+
# allow zeros per type
|
| 77 |
+
return {t: int(c) for t, c in zip(self.item_types, parts)}
|
| 78 |
+
|
| 79 |
+
def _sample_values_pair(self) -> Dict[AgentId, Dict[str, int]]:
|
| 80 |
+
# Each agent has integer non-negative values that sum to 10
|
| 81 |
+
# Each item type valued by at least one agent
|
| 82 |
+
# Some item type valued by both agents
|
| 83 |
+
while True:
|
| 84 |
+
vals_a = random_partition_integer(self.rng, 10, len(self.item_types))
|
| 85 |
+
vals_b = random_partition_integer(self.rng, 10, len(self.item_types))
|
| 86 |
+
a = {t: int(v) for t, v in zip(self.item_types, vals_a)}
|
| 87 |
+
b = {t: int(v) for t, v in zip(self.item_types, vals_b)}
|
| 88 |
+
# each item valued by at least one
|
| 89 |
+
ok1 = all((a[t] > 0) or (b[t] > 0) for t in self.item_types)
|
| 90 |
+
# some item valued by both
|
| 91 |
+
ok2 = any((a[t] > 0) and (b[t] > 0) for t in self.item_types)
|
| 92 |
+
if ok1 and ok2:
|
| 93 |
+
return {self.agent_ids[0]: a, self.agent_ids[1]: b}
|
| 94 |
+
|
| 95 |
+
def _is_valid_allocation(
|
| 96 |
+
self, allocation: Dict[str, int], stock: Dict[str, int]
|
| 97 |
+
) -> bool:
|
| 98 |
+
for t in self.item_types:
|
| 99 |
+
v = allocation.get(t)
|
| 100 |
+
if v is None:
|
| 101 |
+
return False
|
| 102 |
+
if not isinstance(v, int):
|
| 103 |
+
return False
|
| 104 |
+
if v < 0 or v > int(stock.get(t, 0)):
|
| 105 |
+
return False
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
def set_new_round_of_variant(self):
|
| 109 |
+
# Keep same values, resample stock
|
| 110 |
+
self.state.quantities = self._sample_stock()
|
| 111 |
+
|
| 112 |
+
def get_info_of_variant(
|
| 113 |
+
self, state: NegotiationState, actions: Dict[AgentId, Any]
|
| 114 |
+
) -> Dict[str, Any]:
|
| 115 |
+
return {
|
| 116 |
+
"quantities": copy.deepcopy(state.quantities),
|
| 117 |
+
"values": copy.deepcopy(state.values),
|
| 118 |
+
"splits": copy.deepcopy(state.splits),
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
|
| 122 |
+
"""
|
| 123 |
+
Returns the rewards for each agent.
|
| 124 |
+
"""
|
| 125 |
+
split_a = splits[self.agent_ids[0]].items_given_to_self
|
| 126 |
+
split_b = splits[self.agent_ids[1]].items_given_to_self
|
| 127 |
+
rewards = {self.agent_ids[0]: 0, self.agent_ids[1]: 0}
|
| 128 |
+
for t in self.item_types:
|
| 129 |
+
# If not complementary, return 0!
|
| 130 |
+
if not split_a[t] + split_b[t] == self.state.quantities[t]:
|
| 131 |
+
return {self.agent_ids[0]: 0, self.agent_ids[1]: 0}
|
| 132 |
+
rewards[self.agent_ids[0]] += (
|
| 133 |
+
split_a[t] * self.state.values[self.agent_ids[0]][t]
|
| 134 |
+
)
|
| 135 |
+
rewards[self.agent_ids[1]] += (
|
| 136 |
+
split_b[t] * self.state.values[self.agent_ids[1]][t]
|
| 137 |
+
)
|
| 138 |
+
return rewards
|
| 139 |
+
|
| 140 |
+
def get_obs(self):
|
| 141 |
+
return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
|
| 142 |
+
|
| 143 |
+
def get_obs_agent(self, agent_id):
|
| 144 |
+
other_id = self._other(agent_id)
|
| 145 |
+
obs = DealNoDealObs(
|
| 146 |
+
round_nb=self.state.round_nb,
|
| 147 |
+
last_message=self.state.last_message,
|
| 148 |
+
current_agent=self.state.current_agent,
|
| 149 |
+
quantities=copy.deepcopy(self.state.quantities),
|
| 150 |
+
value=0.0, # unused in DOND
|
| 151 |
+
other_agent_split=None, # not meaningful until split
|
| 152 |
+
split_phase=self.state.split_phase,
|
| 153 |
+
quota_messages_per_agent_per_round=self.quota_messages_per_agent_per_round,
|
| 154 |
+
my_values=copy.deepcopy(self.state.values[agent_id]),
|
| 155 |
+
item_types=list(self.item_types),
|
| 156 |
+
previous_values_coagent=copy.deepcopy(self.state.values.get(other_id, {})),
|
| 157 |
+
)
|
| 158 |
+
return obs
|
| 159 |
+
|
| 160 |
+
def reset(self):
|
| 161 |
+
start_agent = self.agent_ids[self._starting_agent_index]
|
| 162 |
+
stock = self._sample_stock()
|
| 163 |
+
values = self._sample_values_pair()
|
| 164 |
+
self.state = DealNoDealState(
|
| 165 |
+
round_nb=0,
|
| 166 |
+
last_message="",
|
| 167 |
+
current_agent=start_agent,
|
| 168 |
+
quantities=stock,
|
| 169 |
+
values=values,
|
| 170 |
+
previous_values=None,
|
| 171 |
+
splits={aid: None for aid in self.agent_ids},
|
| 172 |
+
nb_messages_sent={aid: 0 for aid in self.agent_ids},
|
| 173 |
+
split_phase=False,
|
| 174 |
+
item_types=list(self.item_types),
|
| 175 |
+
)
|
| 176 |
+
return self.get_obs()
|
src_code_for_reproducibility/markov_games/negotiation/nego_agent.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/nego_agent.py
|
| 3 |
+
Summary: General-purpose negotiation agent coordinating prompts and actions.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 7 |
+
from abc import abstractmethod
|
| 8 |
+
from collections.abc import Callable
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Any, Dict, List, Tuple
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
from mllm.markov_games.agent import Agent
|
| 15 |
+
from mllm.markov_games.negotiation.nego_simulation import Message, NegotiationObs, Split
|
| 16 |
+
from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class NegotiationAgentState:
|
| 21 |
+
"""Lightweight container tracking round progression and message history."""
|
| 22 |
+
|
| 23 |
+
round_nb: int
|
| 24 |
+
nb_messages_sent_this_round: int
|
| 25 |
+
chat_counter: int
|
| 26 |
+
chat_history: List[ChatTurn]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class NegotiationAgent(Agent):
|
| 30 |
+
"""Base agent that manages prompt scaffolding and regex validation for variants."""
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
seed: int,
|
| 35 |
+
agent_id: str,
|
| 36 |
+
agent_name: str,
|
| 37 |
+
policy: Callable[[List[Dict]], str],
|
| 38 |
+
goal: str,
|
| 39 |
+
exploration_prompts: List[str] = [],
|
| 40 |
+
exploration_prompt_probs: List[float] = [],
|
| 41 |
+
):
|
| 42 |
+
self.seed = seed
|
| 43 |
+
self.agent_id = agent_id
|
| 44 |
+
self.agent_name = agent_name
|
| 45 |
+
self.policy = policy
|
| 46 |
+
self.goal = goal
|
| 47 |
+
self.exploration_prompts_toggled = len(exploration_prompts) > 0
|
| 48 |
+
if self.exploration_prompts_toggled:
|
| 49 |
+
exploration_prompts = copy.deepcopy(exploration_prompts)
|
| 50 |
+
exploration_prompts.append(None)
|
| 51 |
+
self.exploration_prompts = exploration_prompts
|
| 52 |
+
self.exploration_prompt_probs = np.array(exploration_prompt_probs)
|
| 53 |
+
assert self.exploration_prompt_probs.sum() <= 1
|
| 54 |
+
assert np.all(self.exploration_prompt_probs >= 0)
|
| 55 |
+
self.exploration_prompt_probs = np.append(
|
| 56 |
+
self.exploration_prompt_probs, 1 - self.exploration_prompt_probs.sum()
|
| 57 |
+
)
|
| 58 |
+
self.state = NegotiationAgentState(
|
| 59 |
+
round_nb=0, nb_messages_sent_this_round=0, chat_counter=0, chat_history=[]
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Implemented in variants
|
| 63 |
+
self.intro_prompt = ""
|
| 64 |
+
self.new_round_prompt = ""
|
| 65 |
+
self.last_round_prompt = ""
|
| 66 |
+
self.send_split_prompt = ""
|
| 67 |
+
self.wait_for_message_prompt = ""
|
| 68 |
+
self.last_message_prompt = ""
|
| 69 |
+
self.send_message_prompt = ""
|
| 70 |
+
|
| 71 |
+
@abstractmethod
|
| 72 |
+
def get_message_regex(self, observation: NegotiationObs) -> str:
|
| 73 |
+
"""Return the regex that outgoing chat messages must satisfy."""
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
@abstractmethod
|
| 77 |
+
def get_split_regex(self, observation: NegotiationObs) -> str:
|
| 78 |
+
"""Return the regex that final split proposals must satisfy."""
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
@abstractmethod
|
| 82 |
+
def get_split_action(
|
| 83 |
+
self, policy_output: str, observation: NegotiationObs
|
| 84 |
+
) -> Split:
|
| 85 |
+
"""Convert raw LLM output into the ``Split`` structure required by simulations."""
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
async def act(self, observation: NegotiationObs) -> Tuple[Any, AgentActLog]:
|
| 89 |
+
"""
|
| 90 |
+
Assemble the appropriate prompt, query the policy, and return message or split.
|
| 91 |
+
|
| 92 |
+
This handles intro text, new-round reminders, quota tracking, and post-processing
|
| 93 |
+
(regex enforcement + ChatTurn logging) so subclasses only customize prompts/regexes.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def dict_to_str(d: dict) -> str:
|
| 97 |
+
return ", ".join(f"{v} {k}" for k, v in d.items())
|
| 98 |
+
|
| 99 |
+
def dict_to_eq_str(d: dict) -> str:
|
| 100 |
+
return ", ".join(f"{k}={v}" for k, v in d.items())
|
| 101 |
+
|
| 102 |
+
is_our_turn = observation.current_agent == self.agent_id
|
| 103 |
+
action: Any = None
|
| 104 |
+
round_nb = observation.round_nb
|
| 105 |
+
|
| 106 |
+
prompt_parts: List[str] = []
|
| 107 |
+
obs_ctx = vars(observation)
|
| 108 |
+
obs_ctx_formmated = obs_ctx.copy()
|
| 109 |
+
for key in obs_ctx_formmated:
|
| 110 |
+
if isinstance(obs_ctx_formmated[key], dict) and "value" not in key:
|
| 111 |
+
obs_ctx_formmated[key] = dict_to_str(obs_ctx_formmated[key])
|
| 112 |
+
elif isinstance(obs_ctx_formmated[key], dict) and "value" in key:
|
| 113 |
+
obs_ctx_formmated[key] = dict_to_eq_str(obs_ctx_formmated[key])
|
| 114 |
+
|
| 115 |
+
#######################################
|
| 116 |
+
# build user prompt
|
| 117 |
+
#######################################
|
| 118 |
+
|
| 119 |
+
# First-ever call
|
| 120 |
+
is_intro = round_nb == 0 and self.state.chat_counter == 0
|
| 121 |
+
if is_intro:
|
| 122 |
+
prompt_parts.append(
|
| 123 |
+
self.intro_prompt.format(
|
| 124 |
+
goal=self.goal, agent=self.agent_name, **obs_ctx_formmated
|
| 125 |
+
)
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
# New round
|
| 129 |
+
is_new_round = round_nb > self.state.round_nb
|
| 130 |
+
if is_new_round or is_intro:
|
| 131 |
+
self.state.nb_messages_sent_this_round = 0
|
| 132 |
+
if not is_intro:
|
| 133 |
+
prompt_parts.append(self.last_round_prompt.format(**obs_ctx_formmated))
|
| 134 |
+
prompt_parts.append(self.new_round_prompt.format(**obs_ctx_formmated))
|
| 135 |
+
if self.exploration_prompts_toggled:
|
| 136 |
+
exploration_prompt = self.exploration_prompts[
|
| 137 |
+
np.random.choice(
|
| 138 |
+
len(self.exploration_prompts), p=self.exploration_prompt_probs
|
| 139 |
+
)
|
| 140 |
+
]
|
| 141 |
+
if exploration_prompt is not None:
|
| 142 |
+
prompt_parts.append(exploration_prompt)
|
| 143 |
+
self.state.round_nb = round_nb
|
| 144 |
+
|
| 145 |
+
# Wait for message
|
| 146 |
+
if not is_our_turn and not observation.split_phase:
|
| 147 |
+
prompt_parts.append(
|
| 148 |
+
self.wait_for_message_prompt.format(**obs_ctx_formmated)
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
# Get last message
|
| 152 |
+
if is_our_turn and not is_new_round and not is_intro:
|
| 153 |
+
prompt_parts.append(self.last_message_prompt.format(**obs_ctx_formmated))
|
| 154 |
+
|
| 155 |
+
# Prompt to send message
|
| 156 |
+
must_send_message = not observation.split_phase and is_our_turn
|
| 157 |
+
if must_send_message:
|
| 158 |
+
prompt_parts.append(self.send_message_prompt.format(**obs_ctx_formmated))
|
| 159 |
+
|
| 160 |
+
# Prompt to give split
|
| 161 |
+
must_send_split = not must_send_message and observation.split_phase
|
| 162 |
+
if must_send_split:
|
| 163 |
+
var_names = ["x", "y", "z", "w"] # Extend as needed
|
| 164 |
+
items_str = ", ".join(
|
| 165 |
+
[
|
| 166 |
+
f"{var_names[i]} {item}"
|
| 167 |
+
for i, item in enumerate(obs_ctx["quantities"].keys())
|
| 168 |
+
]
|
| 169 |
+
)
|
| 170 |
+
ranges_str = ", ".join(
|
| 171 |
+
[
|
| 172 |
+
f"{var_names[i]}: 0-{obs_ctx['quantities'][item]} (integer)"
|
| 173 |
+
for i, item in enumerate(obs_ctx["quantities"].keys())
|
| 174 |
+
]
|
| 175 |
+
)
|
| 176 |
+
proposal_style = f"Proposal: {items_str} where {ranges_str}."
|
| 177 |
+
proposal_style2 = (
|
| 178 |
+
f"<items_to_self> {items_str} </items_to_self> where {ranges_str}."
|
| 179 |
+
)
|
| 180 |
+
prompt_parts.append(
|
| 181 |
+
self.send_split_prompt.format(
|
| 182 |
+
proposal_style=proposal_style,
|
| 183 |
+
proposal_style2=proposal_style2,
|
| 184 |
+
**obs_ctx_formmated,
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# Append one ChatTurn with is_state_end=True
|
| 189 |
+
user_prompt = "\n".join(prompt_parts)
|
| 190 |
+
self.state.chat_history.append(
|
| 191 |
+
ChatTurn(
|
| 192 |
+
agent_id=self.agent_id,
|
| 193 |
+
role="user",
|
| 194 |
+
content=user_prompt,
|
| 195 |
+
is_state_end=True,
|
| 196 |
+
)
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
#######################################
|
| 200 |
+
# Get policy action
|
| 201 |
+
#######################################
|
| 202 |
+
|
| 203 |
+
# Query policy for the appropriate format
|
| 204 |
+
if must_send_message:
|
| 205 |
+
return_regex = self.get_message_regex(observation)
|
| 206 |
+
policy_output = await self.policy(
|
| 207 |
+
state=self.state.chat_history,
|
| 208 |
+
agent_id=self.agent_id,
|
| 209 |
+
regex=return_regex,
|
| 210 |
+
)
|
| 211 |
+
self.state.chat_history.append(
|
| 212 |
+
ChatTurn(
|
| 213 |
+
agent_id=self.agent_id,
|
| 214 |
+
role="assistant",
|
| 215 |
+
content=policy_output.content,
|
| 216 |
+
reasoning_content=policy_output.reasoning_content,
|
| 217 |
+
log_probs=policy_output.log_probs,
|
| 218 |
+
out_token_ids=policy_output.out_token_ids,
|
| 219 |
+
is_state_end=False,
|
| 220 |
+
)
|
| 221 |
+
)
|
| 222 |
+
action = Message(message=policy_output.content)
|
| 223 |
+
self.state.nb_messages_sent_this_round += 1
|
| 224 |
+
|
| 225 |
+
elif must_send_split:
|
| 226 |
+
return_regex = self.get_split_regex(observation)
|
| 227 |
+
policy_output = await self.policy(
|
| 228 |
+
state=self.state.chat_history,
|
| 229 |
+
agent_id=self.agent_id,
|
| 230 |
+
regex=return_regex,
|
| 231 |
+
)
|
| 232 |
+
self.state.chat_history.append(
|
| 233 |
+
ChatTurn(
|
| 234 |
+
agent_id=self.agent_id,
|
| 235 |
+
role="assistant",
|
| 236 |
+
content=policy_output.content,
|
| 237 |
+
reasoning_content=policy_output.reasoning_content,
|
| 238 |
+
log_probs=policy_output.log_probs,
|
| 239 |
+
out_token_ids=policy_output.out_token_ids,
|
| 240 |
+
is_state_end=False,
|
| 241 |
+
)
|
| 242 |
+
)
|
| 243 |
+
action = self.get_split_action(policy_output.content, observation)
|
| 244 |
+
else:
|
| 245 |
+
action = None
|
| 246 |
+
|
| 247 |
+
agent_step_log = AgentActLog(
|
| 248 |
+
chat_turns=self.state.chat_history[self.state.chat_counter :], info=None
|
| 249 |
+
)
|
| 250 |
+
self.state.chat_counter = len(self.state.chat_history)
|
| 251 |
+
return action, agent_step_log
|
| 252 |
+
|
| 253 |
+
def get_safe_copy(self):
|
| 254 |
+
agent_copy = copy.copy(self)
|
| 255 |
+
agent_copy.state = copy.deepcopy(self.state)
|
| 256 |
+
return agent_copy
|
| 257 |
+
|
| 258 |
+
def reset(self):
|
| 259 |
+
self.state = NegotiationAgentState(
|
| 260 |
+
round_nb=0, nb_messages_sent_this_round=0, chat_counter=0, chat_history=[]
|
| 261 |
+
)
|
src_code_for_reproducibility/markov_games/negotiation/nego_hard_coded_policies.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/nego_hard_coded_policies.py
|
| 3 |
+
Summary: Provides deterministic negotiation policies for testing and baselines.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
from typing import Any, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
from mllm.markov_games.negotiation.nego_agent import NegotiationAgent
|
| 10 |
+
from mllm.markov_games.negotiation.nego_simulation import Split
|
| 11 |
+
from mllm.markov_games.negotiation.no_press_nego_agent import NoPressAgent
|
| 12 |
+
from mllm.markov_games.negotiation.no_press_nego_simulation import NoPressObs
|
| 13 |
+
from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class HardCodedNegoWelfareMaximizingPolicy(NoPressAgent):
|
| 17 |
+
async def act(self, observation: NoPressObs) -> Tuple[Any, AgentActLog]:
|
| 18 |
+
"""
|
| 19 |
+
Policy that gives all of the items to the agent who values them more.
|
| 20 |
+
If the items are equally valued, give them to the agent who values them more.
|
| 21 |
+
"""
|
| 22 |
+
quantities = observation.quantities
|
| 23 |
+
my_values = observation.value
|
| 24 |
+
other_values = observation.other_value
|
| 25 |
+
|
| 26 |
+
items_given_to_self = {}
|
| 27 |
+
for item, qty in quantities.items():
|
| 28 |
+
my_v = float(my_values.get(item, 0))
|
| 29 |
+
other_v = float(other_values.get(item, 0))
|
| 30 |
+
if my_v == other_v:
|
| 31 |
+
items_given_to_self[item] = int(qty) / 2
|
| 32 |
+
else:
|
| 33 |
+
items_given_to_self[item] = int(qty if my_v > other_v else 0)
|
| 34 |
+
|
| 35 |
+
action = Split(items_given_to_self=items_given_to_self)
|
| 36 |
+
act_log = AgentActLog(
|
| 37 |
+
chat_turns=[
|
| 38 |
+
ChatTurn(
|
| 39 |
+
agent_id=self.agent_id,
|
| 40 |
+
role="assistant",
|
| 41 |
+
content="Using welfare-maximizing split (all to higher-value agent).",
|
| 42 |
+
is_state_end=True,
|
| 43 |
+
)
|
| 44 |
+
],
|
| 45 |
+
info=None,
|
| 46 |
+
)
|
| 47 |
+
return action, act_log
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class HardCodedNegoGreedyPolicy(NoPressAgent):
|
| 51 |
+
async def act(self, observation: NoPressObs) -> Tuple[Any, AgentActLog]:
|
| 52 |
+
"""
|
| 53 |
+
Always gives itself all of the items.
|
| 54 |
+
"""
|
| 55 |
+
quantities = observation.quantities
|
| 56 |
+
items_given_to_self = {item: int(qty) for item, qty in quantities.items()}
|
| 57 |
+
|
| 58 |
+
action = Split(items_given_to_self=items_given_to_self)
|
| 59 |
+
act_log = AgentActLog(
|
| 60 |
+
chat_turns=[
|
| 61 |
+
ChatTurn(
|
| 62 |
+
agent_id=self.agent_id,
|
| 63 |
+
role="assistant",
|
| 64 |
+
content="Using greedy split (keep all items).",
|
| 65 |
+
is_state_end=True,
|
| 66 |
+
)
|
| 67 |
+
],
|
| 68 |
+
info=None,
|
| 69 |
+
)
|
| 70 |
+
return action, act_log
|
src_code_for_reproducibility/markov_games/negotiation/nego_simulation.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/nego_simulation.py
|
| 3 |
+
Summary: Simulation harness for general negotiation environments.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 7 |
+
from abc import abstractmethod
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Any, Dict, List, Tuple
|
| 10 |
+
|
| 11 |
+
from numpy.random import default_rng
|
| 12 |
+
|
| 13 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 14 |
+
from mllm.markov_games.simulation import Simulation
|
| 15 |
+
from mllm.utils.get_coagent_id import get_coagent_id
|
| 16 |
+
|
| 17 |
+
AgentId = str
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class Split:
|
| 22 |
+
"""Structured proposal describing how many units of each item an agent keeps."""
|
| 23 |
+
|
| 24 |
+
items_given_to_self: Dict[str, int]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class Message:
|
| 29 |
+
"""Single chat utterance exchanged during the negotiation phase."""
|
| 30 |
+
|
| 31 |
+
message: str
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass # gets extended by variants
|
| 35 |
+
class NegotiationState:
|
| 36 |
+
"""Full simulator state snapshot shared by all negotiation variants."""
|
| 37 |
+
|
| 38 |
+
round_nb: int
|
| 39 |
+
last_message: str
|
| 40 |
+
current_agent: AgentId
|
| 41 |
+
quantities: Dict[str, int]
|
| 42 |
+
values: Dict[AgentId, Dict[str, float]]
|
| 43 |
+
splits: Dict[AgentId, Split | None]
|
| 44 |
+
nb_messages_sent: Dict[AgentId, int]
|
| 45 |
+
previous_values: Dict[AgentId, Dict[str, float]] | None
|
| 46 |
+
previous_splits: Dict[AgentId, Dict[str, int] | None] | None
|
| 47 |
+
previous_points: Dict[AgentId, float] | None
|
| 48 |
+
previous_quantities: Dict[str, int] | None
|
| 49 |
+
split_phase: bool
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass # gets extended by variants
|
| 53 |
+
class NegotiationObs:
|
| 54 |
+
"""Observation presented to agents each turn (base fields; variants extend)."""
|
| 55 |
+
|
| 56 |
+
round_nb: int
|
| 57 |
+
last_message: str
|
| 58 |
+
quota_messages_per_agent_per_round: int
|
| 59 |
+
current_agent: AgentId
|
| 60 |
+
other_agent: str
|
| 61 |
+
quantities: Dict[str, int]
|
| 62 |
+
item_types: List[str]
|
| 63 |
+
value: Dict[str, int]
|
| 64 |
+
split_phase: bool
|
| 65 |
+
last_split_agent: Dict[str, int] | None
|
| 66 |
+
last_value_agent: Dict[str, int] | None
|
| 67 |
+
last_points_agent: float | None
|
| 68 |
+
last_split_coagent: Dict[str, int] | None
|
| 69 |
+
last_value_coagent: Dict[str, int] | None
|
| 70 |
+
last_points_coagent: float | None
|
| 71 |
+
last_quantities: Dict[str, int] | None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def compute_tas_style_rewards(
|
| 75 |
+
agent_ids: List[AgentId],
|
| 76 |
+
values: Dict[AgentId, float],
|
| 77 |
+
splits: Dict[AgentId, Split],
|
| 78 |
+
quantities: Dict[str, int],
|
| 79 |
+
) -> Dict[AgentId, float]:
|
| 80 |
+
"""
|
| 81 |
+
TAS-like reward computation: if sum of proposed coins exceeds max_coins,
|
| 82 |
+
allocate proportionally. Otherwise, use proposed amounts directly.
|
| 83 |
+
Rewards are quantity_kept * per-coin value for each agent.
|
| 84 |
+
"""
|
| 85 |
+
a0, a1 = agent_ids[0], agent_ids[1]
|
| 86 |
+
r0, r1 = 0.0, 0.0
|
| 87 |
+
|
| 88 |
+
for item in quantities:
|
| 89 |
+
max_item = quantities[item]
|
| 90 |
+
item_to_self_0 = int(
|
| 91 |
+
(splits[a0].items_given_to_self.get(item, 0))
|
| 92 |
+
if splits[a0] is not None
|
| 93 |
+
else 0
|
| 94 |
+
)
|
| 95 |
+
item_to_self_1 = int(
|
| 96 |
+
(splits[a1].items_given_to_self.get(item, 0))
|
| 97 |
+
if splits[a1] is not None
|
| 98 |
+
else 0
|
| 99 |
+
)
|
| 100 |
+
denom = max(int(max_item), item_to_self_0 + item_to_self_1)
|
| 101 |
+
q0 = float(max_item) * float(item_to_self_0) / float(denom)
|
| 102 |
+
q1 = float(max_item) * float(item_to_self_1) / float(denom)
|
| 103 |
+
if type(values[a0]) is not dict:
|
| 104 |
+
r0 += q0 * float(values[a0])
|
| 105 |
+
r1 += q1 * float(values[a1])
|
| 106 |
+
else:
|
| 107 |
+
r0 += q0 * float(values[a0][item])
|
| 108 |
+
r1 += q1 * float(values[a1][item])
|
| 109 |
+
return {a0: r0, a1: r1}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class NegotiationSimulation(Simulation):
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
agent_ids: List[AgentId],
|
| 116 |
+
agent_names: List[str],
|
| 117 |
+
seed: int,
|
| 118 |
+
nb_of_rounds: int,
|
| 119 |
+
quota_messages_per_agent_per_round: int,
|
| 120 |
+
item_types: List[str] | None = None,
|
| 121 |
+
):
|
| 122 |
+
self.seed = seed
|
| 123 |
+
self.rng = default_rng(self.seed)
|
| 124 |
+
self.agent_ids = list(agent_ids)
|
| 125 |
+
self.agent_names = agent_names
|
| 126 |
+
self.agent_id_to_name = {
|
| 127 |
+
agent_id: agent_name for agent_id, agent_name in zip(agent_ids, agent_names)
|
| 128 |
+
}
|
| 129 |
+
self.nb_of_rounds = int(nb_of_rounds)
|
| 130 |
+
self.quota_messages_per_agent_per_round = int(
|
| 131 |
+
quota_messages_per_agent_per_round
|
| 132 |
+
)
|
| 133 |
+
if item_types is not None:
|
| 134 |
+
self.item_types = [item.lower() for item in item_types]
|
| 135 |
+
else:
|
| 136 |
+
self.item_types = ["coins"]
|
| 137 |
+
self.state: NegotiationState | None = None
|
| 138 |
+
self._starting_agent_index = self.rng.choice([0, 1])
|
| 139 |
+
self.reset()
|
| 140 |
+
|
| 141 |
+
def _other(self, agent_id: AgentId) -> AgentId:
|
| 142 |
+
return get_coagent_id(self.agent_ids, agent_id)
|
| 143 |
+
|
| 144 |
+
@abstractmethod
|
| 145 |
+
def set_new_round_of_variant(self):
|
| 146 |
+
"""Variant hook: sample new private values / stock before each round."""
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
@abstractmethod
|
| 150 |
+
def get_info_of_variant(
|
| 151 |
+
self, state: NegotiationState, actions: Dict[AgentId, Any]
|
| 152 |
+
) -> Dict[str, Any]:
|
| 153 |
+
"""Variant hook: populate SimulationStepLog.info with custom diagnostics."""
|
| 154 |
+
pass
|
| 155 |
+
|
| 156 |
+
def step(self, actions: Any) -> Tuple[bool, SimulationStepLog]:
|
| 157 |
+
"""
|
| 158 |
+
Returns terminated, step_log
|
| 159 |
+
"""
|
| 160 |
+
assert self.state is not None
|
| 161 |
+
current_agent = self.state.current_agent
|
| 162 |
+
a0, a1 = self.agent_ids[0], self.agent_ids[1]
|
| 163 |
+
action = actions.get(current_agent)
|
| 164 |
+
|
| 165 |
+
# Split phase: require both splits in the same timestep
|
| 166 |
+
if self.state.split_phase:
|
| 167 |
+
action_a0 = actions.get(a0)
|
| 168 |
+
action_a1 = actions.get(a1)
|
| 169 |
+
have_both_splits = isinstance(action_a0, Split) and isinstance(
|
| 170 |
+
action_a1, Split
|
| 171 |
+
)
|
| 172 |
+
if not have_both_splits:
|
| 173 |
+
rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
|
| 174 |
+
return False, SimulationStepLog(
|
| 175 |
+
rewards=rewards, info={"type": "waiting_for_splits"}
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Record splits
|
| 179 |
+
self.state.splits[a0] = action_a0
|
| 180 |
+
self.state.splits[a1] = action_a1
|
| 181 |
+
|
| 182 |
+
# Compute rewards and end round
|
| 183 |
+
rewards = self.get_rewards(self.state.splits)
|
| 184 |
+
|
| 185 |
+
# Info
|
| 186 |
+
info = self.get_info_of_variant(self.state, actions)
|
| 187 |
+
|
| 188 |
+
# Prepare next round
|
| 189 |
+
# Alternate starting agent
|
| 190 |
+
self.state.round_nb += 1
|
| 191 |
+
self._starting_agent_index = 1 - self._starting_agent_index
|
| 192 |
+
self.state.current_agent = self.agent_ids[self._starting_agent_index]
|
| 193 |
+
self.state.previous_values = copy.deepcopy(self.state.values)
|
| 194 |
+
self.state.previous_splits = copy.deepcopy(self.state.splits)
|
| 195 |
+
self.state.previous_quantities = copy.deepcopy(self.state.quantities)
|
| 196 |
+
self.state.previous_points = copy.deepcopy(rewards)
|
| 197 |
+
self.state.last_message = ""
|
| 198 |
+
self.set_new_round_of_variant() # variant specific
|
| 199 |
+
self.state.splits = {agent_id: None for agent_id in self.agent_ids}
|
| 200 |
+
self.state.nb_messages_sent = {agent_id: 0 for agent_id in self.agent_ids}
|
| 201 |
+
is_last_timestep_in_round = True
|
| 202 |
+
done = self.state.round_nb >= self.nb_of_rounds
|
| 203 |
+
|
| 204 |
+
# Message phase: roll the conversation forward a single turn.
|
| 205 |
+
elif isinstance(action, Message):
|
| 206 |
+
self.state.last_message = action.message
|
| 207 |
+
self.state.nb_messages_sent[current_agent] += 1
|
| 208 |
+
|
| 209 |
+
# Move turn to other agent
|
| 210 |
+
self.state.current_agent = self._other(current_agent)
|
| 211 |
+
|
| 212 |
+
# If both agents have reached their message quota, enter split phase
|
| 213 |
+
if all(
|
| 214 |
+
self.state.nb_messages_sent[agent_id]
|
| 215 |
+
>= self.quota_messages_per_agent_per_round
|
| 216 |
+
for agent_id in self.agent_ids
|
| 217 |
+
):
|
| 218 |
+
self.state.split_phase = True
|
| 219 |
+
is_last_timestep_in_round = False
|
| 220 |
+
done = False
|
| 221 |
+
rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
|
| 222 |
+
info = {"type": "message"}
|
| 223 |
+
|
| 224 |
+
info[
|
| 225 |
+
"is_last_timestep_in_round"
|
| 226 |
+
] = is_last_timestep_in_round # Used later to group round timesteps if needed
|
| 227 |
+
return done, SimulationStepLog(rewards=rewards, info=info)
|
| 228 |
+
|
| 229 |
+
def get_obs(self):
|
| 230 |
+
"""Returns all agent observations in dict"""
|
| 231 |
+
return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
|
| 232 |
+
|
| 233 |
+
@abstractmethod
|
| 234 |
+
def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
|
| 235 |
+
pass
|
| 236 |
+
|
| 237 |
+
@abstractmethod
|
| 238 |
+
def get_obs_agent(self, agent_id):
|
| 239 |
+
pass
|
| 240 |
+
|
| 241 |
+
def get_state(self):
|
| 242 |
+
return self.state
|
| 243 |
+
|
| 244 |
+
def get_safe_copy(self):
|
| 245 |
+
"""Return a safe copy of the simulation."""
|
| 246 |
+
simulation_copy = copy.copy(self)
|
| 247 |
+
simulation_copy.state = copy.deepcopy(self.state)
|
| 248 |
+
return simulation_copy
|
| 249 |
+
|
| 250 |
+
@abstractmethod
|
| 251 |
+
def reset(self) -> dict[AgentId, NegotiationObs]:
|
| 252 |
+
pass
|
src_code_for_reproducibility/markov_games/negotiation/negotiation_statistics.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/negotiation_statistics.py
|
| 3 |
+
Summary: Aggregates and reports statistics for negotiation experiments.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import Callable, Dict, List, Tuple
|
| 9 |
+
|
| 10 |
+
from mllm.markov_games.negotiation.nego_simulation import Split
|
| 11 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def avg_reward(sl: SimulationStepLog) -> List[Tuple[str, float]]:
|
| 15 |
+
"""Average (per-step) reward for each agent and overall.
|
| 16 |
+
|
| 17 |
+
What it computes:
|
| 18 |
+
- Returns the raw reward for every (non-buffer) agent at the current
|
| 19 |
+
simulation step.
|
| 20 |
+
- Adds an aggregate key ``all_agents`` which is the simple arithmetic
|
| 21 |
+
mean across the agents present in ``sl.rewards``.
|
| 22 |
+
|
| 23 |
+
Rationale / motivation:
|
| 24 |
+
Monitoring the reward stream at each step helps:
|
| 25 |
+
* Diagnose reward shaping issues (e.g., unintended negative drift).
|
| 26 |
+
* Provide a fairness snapshot (are rewards systematically skewed?).
|
| 27 |
+
* Supply a ubiquitous baseline metric used by other higher‑level
|
| 28 |
+
summaries (efficiency, surplus allocation, etc.).
|
| 29 |
+
|
| 30 |
+
Return shape:
|
| 31 |
+
{ agent_id: float, ..., "all_agents": float }
|
| 32 |
+
If any agent id contains the substring "buffer" we treat this step as
|
| 33 |
+
an implementation artifact (e.g., rollout buffer) and return ``None``
|
| 34 |
+
to avoid polluting aggregates.
|
| 35 |
+
"""
|
| 36 |
+
for aid in sl.rewards.keys():
|
| 37 |
+
if "buffer" in str(aid) and "live" not in str(aid):
|
| 38 |
+
return None
|
| 39 |
+
# One value per agent at each step
|
| 40 |
+
rewards_dict = {f"reward-{aid}": float(v) for aid, v in (sl.rewards or {}).items()}
|
| 41 |
+
return [(key, value) for key, value in rewards_dict.items() if value is not None]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def split_efficiency(sl: SimulationStepLog) -> List[Tuple[str, float]] | None:
|
| 45 |
+
"""Final‑round allocation efficiency relative to an upper bound.
|
| 46 |
+
|
| 47 |
+
What it computes (only on the last timestep of a negotiation round):
|
| 48 |
+
- Uses ``info['values']`` (per‑agent per‑item valuations) and
|
| 49 |
+
``info['quantities']`` (available item counts) to form a greedy
|
| 50 |
+
*upper bound* on achievable total reward: allocate each unit of an
|
| 51 |
+
item to the single agent who values that item most.
|
| 52 |
+
- Compares the actually realized sum of rewards at that final
|
| 53 |
+
timestep to this constructed maximum.
|
| 54 |
+
- Emits a single scalar under key ``"all_agents"`` equal to
|
| 55 |
+
achieved / theoretical_max.
|
| 56 |
+
|
| 57 |
+
Motivation:
|
| 58 |
+
Efficiency (a core welfare notion) distinguishes between coordination
|
| 59 |
+
failures (low efficiency) versus strategic distributional disputes
|
| 60 |
+
(high efficiency but uneven splits). Tracking this per round helps
|
| 61 |
+
evaluate whether models learn to identify and realize joint surplus.
|
| 62 |
+
|
| 63 |
+
Notes / caveats:
|
| 64 |
+
- Only defined for 2+ non‑buffer agents; if a buffer agent is present
|
| 65 |
+
returns ``None`` to exclude spurious steps.
|
| 66 |
+
- Requires the environment to have populated ``values`` and
|
| 67 |
+
``quantities``; otherwise returns ``None``.
|
| 68 |
+
- This is an optimistic bound (not necessarily reachable under
|
| 69 |
+
protocol constraints) but is simple, fast, and comparable across
|
| 70 |
+
runs.
|
| 71 |
+
"""
|
| 72 |
+
info = sl.info or {}
|
| 73 |
+
if not info or not info.get("is_last_timestep_in_round"):
|
| 74 |
+
return None
|
| 75 |
+
quantities = info.get("quantities") or {}
|
| 76 |
+
values = info.get("values") or {}
|
| 77 |
+
if not values or not quantities:
|
| 78 |
+
return None
|
| 79 |
+
agent_ids = list(sl.rewards.keys())
|
| 80 |
+
if type(values[agent_ids[0]]) is dict:
|
| 81 |
+
item_keys = list(values.values())[0].keys()
|
| 82 |
+
max_vals, max_quantities = [], []
|
| 83 |
+
for item in item_keys:
|
| 84 |
+
max_val = max(float(agent_vals[item]) for agent_vals in values.values())
|
| 85 |
+
max_vals.append(max_val)
|
| 86 |
+
max_quantities.append(quantities[item])
|
| 87 |
+
else:
|
| 88 |
+
max_vals = [max(float(v) for v in values.values())]
|
| 89 |
+
max_quantities = [quantities[item] for item in quantities.keys()]
|
| 90 |
+
for aid in sl.rewards.keys():
|
| 91 |
+
if "buffer" in str(aid) and "live" not in str(aid):
|
| 92 |
+
return None
|
| 93 |
+
achieved = sum(float(v) for v in sl.rewards.values())
|
| 94 |
+
max_reward = sum(d * v for d, v in zip(max_quantities, max_vals))
|
| 95 |
+
# Efficiency is a global metric; emit same value for a special key "all"
|
| 96 |
+
return [("split_efficiency", achieved / max_reward)]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _extract_items_from_split(raw_split: Dict) -> Dict[str, float] | None:
|
| 100 |
+
"""Return a mapping item->proposal amount from a split structure.
|
| 101 |
+
|
| 102 |
+
Supports both generic negotiation splits with nested structure
|
| 103 |
+
{ 'items_given_to_self': {item: qty, ...}}
|
| 104 |
+
and TAS coin-only variants which may already be a flat mapping {'coins': qty}.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
if raw_split is None:
|
| 108 |
+
return {}
|
| 109 |
+
elif isinstance(raw_split, Split):
|
| 110 |
+
return {k: float(v) for k, v in raw_split.items_given_to_self.items()}
|
| 111 |
+
elif isinstance(raw_split, dict):
|
| 112 |
+
if "items_given_to_self" in raw_split and isinstance(
|
| 113 |
+
raw_split["items_given_to_self"], dict
|
| 114 |
+
):
|
| 115 |
+
return {k: float(v) for k, v in raw_split["items_given_to_self"].items()}
|
| 116 |
+
# Fallback: assume already flat mapping of items
|
| 117 |
+
elif hasattr(raw_split, "items_given_to_self"):
|
| 118 |
+
return {k: float(v) for k, v in raw_split["items_given_to_self"].items()}
|
| 119 |
+
return {
|
| 120 |
+
k: float(v) for k, v in raw_split.items() if isinstance(v, (int, float))
|
| 121 |
+
}
|
| 122 |
+
return {}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _average_proposal_relative_value(
|
| 126 |
+
sl: SimulationStepLog,
|
| 127 |
+
metric_name: str,
|
| 128 |
+
comparator: Callable[[float, float], bool],
|
| 129 |
+
opposite_comparator: Callable[[float, float], bool],
|
| 130 |
+
) -> Dict[str, float | None] | None:
|
| 131 |
+
"""Shared implementation for proposal size conditioned on relative value.
|
| 132 |
+
|
| 133 |
+
Parameters:
|
| 134 |
+
comparator: returns True when agent_0's value relation (e.g. < or >)
|
| 135 |
+
to agent_1 holds for an item and we should collect agent_0's
|
| 136 |
+
proposed quantity for that item.
|
| 137 |
+
opposite_comparator: inverse relation used to collect agent_1's items.
|
| 138 |
+
|
| 139 |
+
Behavior:
|
| 140 |
+
- Executes only on final timestep of a round (where the definitive
|
| 141 |
+
proposal / allocation is known via ``info['splits']``).
|
| 142 |
+
- For each item, classifies which agent's value satisfies the chosen
|
| 143 |
+
relation and records that agent's proposed quantity from the split.
|
| 144 |
+
- Averages (mean) across all qualifying items per agent; if no items
|
| 145 |
+
qualify for an agent returns ``None`` for that agent id.
|
| 146 |
+
- Adds ``all_agents`` mean across the numeric (non-None) agent values.
|
| 147 |
+
|
| 148 |
+
Why this matters:
|
| 149 |
+
Distinguishing how much an agent *asks for* when it subjectively
|
| 150 |
+
values items more (or less) than its counterpart reveals patterns of
|
| 151 |
+
opportunism vs. concession. This is especially useful when raw reward
|
| 152 |
+
differences are subtle but allocation *intent* differs.
|
| 153 |
+
"""
|
| 154 |
+
info = sl.info or {}
|
| 155 |
+
if not info or not info.get("is_last_timestep_in_round"):
|
| 156 |
+
return None
|
| 157 |
+
quantities = info.get("quantities") or {}
|
| 158 |
+
splits = info.get("splits") or {}
|
| 159 |
+
values = info.get("values") or {}
|
| 160 |
+
agent_ids: List[str] = list(sl.rewards.keys())
|
| 161 |
+
if len(agent_ids) != 2:
|
| 162 |
+
return None # Only defined for 2-agent case.
|
| 163 |
+
for aid in agent_ids:
|
| 164 |
+
if "buffer" in str(aid) and "live" not in str(aid):
|
| 165 |
+
return None
|
| 166 |
+
# Extract per-agent item proposals robustly
|
| 167 |
+
split_items = {aid: _extract_items_from_split(splits.get(aid)) for aid in agent_ids}
|
| 168 |
+
agent_0_vals: List[float] = []
|
| 169 |
+
agent_1_vals: List[float] = []
|
| 170 |
+
for item in quantities.keys():
|
| 171 |
+
# Values may be either a float (same for all items) or dict per item
|
| 172 |
+
v0_raw = values[agent_ids[0]]
|
| 173 |
+
v1_raw = values[agent_ids[1]]
|
| 174 |
+
v0 = float(v0_raw[item]) if isinstance(v0_raw, dict) else float(v0_raw)
|
| 175 |
+
v1 = float(v1_raw[item]) if isinstance(v1_raw, dict) else float(v1_raw)
|
| 176 |
+
if comparator(v0, v1):
|
| 177 |
+
agent_0_vals.append(split_items[agent_ids[0]].get(item, 0.0))
|
| 178 |
+
elif opposite_comparator(v0, v1):
|
| 179 |
+
agent_1_vals.append(split_items[agent_ids[1]].get(item, 0.0))
|
| 180 |
+
out: Dict[str, float | None] = {}
|
| 181 |
+
out[f"{metric_name}-{agent_ids[0]}"] = (
|
| 182 |
+
sum(agent_0_vals) / len(agent_0_vals) if agent_0_vals else None
|
| 183 |
+
)
|
| 184 |
+
out[f"{metric_name}-{agent_ids[1]}"] = (
|
| 185 |
+
sum(agent_1_vals) / len(agent_1_vals) if agent_1_vals else None
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
return [(key, value) for key, value in out.items() if value is not None]
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def average_proposal_when_agent_values_item_lower(
|
| 192 |
+
sl: SimulationStepLog,
|
| 193 |
+
) -> List[Tuple[str, float | None]] | None:
|
| 194 |
+
"""Mean quantity an agent proposes for items it values *less* than opponent.
|
| 195 |
+
|
| 196 |
+
Interpretation:
|
| 197 |
+
A higher value implies the agent still claims (or is allocated) a
|
| 198 |
+
notable share of items where it has a comparative *disadvantage* in
|
| 199 |
+
valuation, signaling either strategic over-claiming or protocol-driven
|
| 200 |
+
egalitarian splits. Conversely, very low numbers can indicate
|
| 201 |
+
efficient specialization or excessive concession.
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
Mapping { agent_id: float | None, "all_agents": float | None } where
|
| 205 |
+
None indicates no qualifying items for that agent in the round.
|
| 206 |
+
"""
|
| 207 |
+
return _average_proposal_relative_value(
|
| 208 |
+
sl,
|
| 209 |
+
"average_proposal_when_agent_values_item_lower",
|
| 210 |
+
lambda a, b: a < b,
|
| 211 |
+
lambda a, b: a > b,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def average_proposal_when_agent_values_item_higher(
|
| 216 |
+
sl: SimulationStepLog,
|
| 217 |
+
) -> List[Tuple[str, float | None]] | None:
|
| 218 |
+
"""Mean quantity an agent proposes for items it values *more* than opponent.
|
| 219 |
+
|
| 220 |
+
Interpretation:
|
| 221 |
+
Captures how aggressively an agent claims items where it holds a
|
| 222 |
+
comparative *advantage*. Elevated values can reflect rational
|
| 223 |
+
specialization (efficient exploitation of comparative advantage) or
|
| 224 |
+
potentially unfair grabs if paired with low concession in the lower
|
| 225 |
+
valuation metric. Comparing this with the 'lower' counterpart helps
|
| 226 |
+
profile negotiation style (cooperative vs. exploitative).
|
| 227 |
+
|
| 228 |
+
Returns:
|
| 229 |
+
Mapping { agent_id: float | None, "all_agents": float | None } where
|
| 230 |
+
None indicates no qualifying items.
|
| 231 |
+
"""
|
| 232 |
+
return _average_proposal_relative_value(
|
| 233 |
+
sl,
|
| 234 |
+
"average_proposal_when_agent_values_item_higher",
|
| 235 |
+
lambda a, b: a > b,
|
| 236 |
+
lambda a, b: a < b,
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# Explicit list of metric functions exported for rendering. Helper functions
|
| 241 |
+
# starting with '_' are intentionally excluded. Update this list when adding
|
| 242 |
+
# new public statistics so render.py can rely on it instead of introspecting
|
| 243 |
+
# every callable in the module.
|
| 244 |
+
stat_functs: list[Callable[[SimulationStepLog], List[Tuple[str, float]]]] = [
|
| 245 |
+
avg_reward,
|
| 246 |
+
average_proposal_when_agent_values_item_lower,
|
| 247 |
+
average_proposal_when_agent_values_item_higher,
|
| 248 |
+
split_efficiency,
|
| 249 |
+
]
|
src_code_for_reproducibility/markov_games/negotiation/no_press_nego_simulation.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/no_press_nego_simulation.py
|
| 3 |
+
Summary: Simulation driver for no-press negotiation scenarios.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Any, Dict, List, Literal, Tuple
|
| 10 |
+
|
| 11 |
+
from mllm.markov_games.negotiation.nego_simulation import (
|
| 12 |
+
NegotiationObs,
|
| 13 |
+
NegotiationSimulation,
|
| 14 |
+
NegotiationState,
|
| 15 |
+
Split,
|
| 16 |
+
compute_tas_style_rewards,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
AgentId = str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class NoPressState(NegotiationState):
|
| 24 |
+
"""NegotiationState alias used to clarify we run in always-split phase."""
|
| 25 |
+
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class NoPressObs(NegotiationObs):
|
| 31 |
+
"""Observation that includes both agents' values (since there is no messaging)."""
|
| 32 |
+
|
| 33 |
+
other_value: Dict[str, float]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class NoPressSimulation(NegotiationSimulation):
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
game_type: Literal["10-1-exclusive", "10-1-ties", "1-to-20"] = "1-to-20",
|
| 40 |
+
same_round_value: bool = True,
|
| 41 |
+
atleast_one_conflict: bool = False,
|
| 42 |
+
*args,
|
| 43 |
+
**kwargs,
|
| 44 |
+
):
|
| 45 |
+
self.game_type = game_type
|
| 46 |
+
self.same_round_value = same_round_value
|
| 47 |
+
self.atleast_one_conflict = atleast_one_conflict
|
| 48 |
+
super().__init__(*args, **kwargs)
|
| 49 |
+
|
| 50 |
+
def _sample_values(self) -> Dict[AgentId, dict]:
|
| 51 |
+
"""Sample per-item valuations according to the configured template."""
|
| 52 |
+
values = defaultdict(dict)
|
| 53 |
+
if self.state is None:
|
| 54 |
+
item_types = self.item_types
|
| 55 |
+
else:
|
| 56 |
+
item_types = list(self.state.quantities.keys())
|
| 57 |
+
while True:
|
| 58 |
+
for item in item_types:
|
| 59 |
+
if self.game_type == "10-1-exclusive":
|
| 60 |
+
v = int(self.rng.choice([1, 10]))
|
| 61 |
+
values[self.agent_ids[0]][item] = v
|
| 62 |
+
values[self.agent_ids[1]][item] = 10 if v == 1 else 1
|
| 63 |
+
elif self.game_type == "10-1-ties":
|
| 64 |
+
for aid in self.agent_ids:
|
| 65 |
+
values[aid][item] = int(self.rng.choice([1, 10]))
|
| 66 |
+
elif self.game_type == "1-to-20":
|
| 67 |
+
for aid in self.agent_ids:
|
| 68 |
+
values[aid][item] = int(self.rng.integers(1, 21))
|
| 69 |
+
if self.atleast_one_conflict:
|
| 70 |
+
has_conflict = False
|
| 71 |
+
for item in item_types:
|
| 72 |
+
agent_values_for_item = [
|
| 73 |
+
values[aid][item] for aid in self.agent_ids
|
| 74 |
+
]
|
| 75 |
+
if len(set(agent_values_for_item)) > 1:
|
| 76 |
+
has_conflict = True
|
| 77 |
+
break
|
| 78 |
+
if not has_conflict:
|
| 79 |
+
continue
|
| 80 |
+
agent_values = [sum(v.values()) for v in values.values()]
|
| 81 |
+
if len(set(agent_values)) == 1 or not self.same_round_value:
|
| 82 |
+
break
|
| 83 |
+
return values
|
| 84 |
+
|
| 85 |
+
def _sample_quantities(self) -> Dict[str, int]:
|
| 86 |
+
"""No-press setups use symmetric 10-unit stocks for every item."""
|
| 87 |
+
return {item.lower(): 10 for item in self.item_types}
|
| 88 |
+
|
| 89 |
+
def set_new_round_of_variant(self):
|
| 90 |
+
"""Refresh quantities/values and jump directly into the simultaneous split."""
|
| 91 |
+
self.state.quantities = self._sample_quantities()
|
| 92 |
+
self.state.values = self._sample_values()
|
| 93 |
+
self.state.split_phase = True
|
| 94 |
+
|
| 95 |
+
def get_info_of_variant(
|
| 96 |
+
self, state: NegotiationState, actions: Dict[AgentId, Any]
|
| 97 |
+
) -> Dict[str, Any]:
|
| 98 |
+
"""Surface quantities/values/splits so statistics modules can read them."""
|
| 99 |
+
return {
|
| 100 |
+
"quantities": copy.deepcopy(state.quantities),
|
| 101 |
+
"values": copy.deepcopy(state.values),
|
| 102 |
+
"splits": copy.deepcopy(state.splits),
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
|
| 106 |
+
"""Reuse TAS reward logic because the split arbitration is identical."""
|
| 107 |
+
return compute_tas_style_rewards(
|
| 108 |
+
self.agent_ids, self.state.values, splits, self.state.quantities
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def get_obs(self):
|
| 112 |
+
return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
|
| 113 |
+
|
| 114 |
+
def get_obs_agent(self, agent_id):
|
| 115 |
+
other_id = self._other(agent_id)
|
| 116 |
+
last_value_coagent = (
|
| 117 |
+
None
|
| 118 |
+
if self.state.previous_values is None
|
| 119 |
+
else self.state.previous_values.get(other_id)
|
| 120 |
+
)
|
| 121 |
+
last_points_coagent = (
|
| 122 |
+
None
|
| 123 |
+
if self.state.previous_points is None
|
| 124 |
+
else round(self.state.previous_points.get(other_id), 1)
|
| 125 |
+
)
|
| 126 |
+
last_value_agent = (
|
| 127 |
+
None
|
| 128 |
+
if self.state.previous_values is None
|
| 129 |
+
else self.state.previous_values.get(agent_id)
|
| 130 |
+
)
|
| 131 |
+
last_points_agent = (
|
| 132 |
+
None
|
| 133 |
+
if self.state.previous_points is None
|
| 134 |
+
else round(self.state.previous_points.get(agent_id), 1)
|
| 135 |
+
)
|
| 136 |
+
last_split_coagent = None
|
| 137 |
+
last_split_agent = None
|
| 138 |
+
if self.state.previous_splits is not None:
|
| 139 |
+
last_split_coagent = self.state.previous_splits[
|
| 140 |
+
other_id
|
| 141 |
+
].items_given_to_self
|
| 142 |
+
last_split_agent = self.state.previous_splits[agent_id].items_given_to_self
|
| 143 |
+
obs = NoPressObs(
|
| 144 |
+
round_nb=self.state.round_nb,
|
| 145 |
+
last_message="",
|
| 146 |
+
quota_messages_per_agent_per_round=self.quota_messages_per_agent_per_round,
|
| 147 |
+
current_agent=self.state.current_agent,
|
| 148 |
+
other_agent=self.agent_id_to_name[other_id],
|
| 149 |
+
quantities=self.state.quantities,
|
| 150 |
+
item_types=self.item_types,
|
| 151 |
+
value=self.state.values[agent_id],
|
| 152 |
+
split_phase=self.state.split_phase,
|
| 153 |
+
last_split_agent=last_split_agent,
|
| 154 |
+
last_value_agent=last_value_agent,
|
| 155 |
+
last_points_agent=last_points_agent,
|
| 156 |
+
last_split_coagent=last_split_coagent,
|
| 157 |
+
last_value_coagent=last_value_coagent,
|
| 158 |
+
last_points_coagent=last_points_coagent,
|
| 159 |
+
other_value=self.state.values[other_id],
|
| 160 |
+
last_quantities=self.state.previous_quantities,
|
| 161 |
+
)
|
| 162 |
+
return obs
|
| 163 |
+
|
| 164 |
+
def reset(self):
|
| 165 |
+
start_agent = self.agent_ids[self._starting_agent_index]
|
| 166 |
+
quantities = self._sample_quantities()
|
| 167 |
+
values = self._sample_values()
|
| 168 |
+
self.state = NoPressState(
|
| 169 |
+
round_nb=0,
|
| 170 |
+
last_message="",
|
| 171 |
+
current_agent=start_agent,
|
| 172 |
+
quantities=quantities,
|
| 173 |
+
values=values,
|
| 174 |
+
previous_values=None,
|
| 175 |
+
splits={aid: None for aid in self.agent_ids},
|
| 176 |
+
nb_messages_sent={aid: 0 for aid in self.agent_ids},
|
| 177 |
+
split_phase=True,
|
| 178 |
+
previous_splits=None,
|
| 179 |
+
previous_points=None,
|
| 180 |
+
previous_quantities=None,
|
| 181 |
+
)
|
| 182 |
+
return self.get_obs()
|
src_code_for_reproducibility/markov_games/negotiation/tas_agent.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/tas_agent.py
|
| 3 |
+
Summary: Agent implementation for Take-and-Split negotiations.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from mllm.markov_games.negotiation.nego_agent import NegotiationAgent
|
| 7 |
+
from mllm.markov_games.negotiation.nego_simulation import Split
|
| 8 |
+
from mllm.markov_games.negotiation.tas_simulation import TrustAndSplitObs
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TrustAndSplitAgent(NegotiationAgent):
|
| 12 |
+
"""Prompt/template wrapper for the classic multi-item Take-and-Split benchmark."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, num_message_chars, *args, **kwargs):
|
| 15 |
+
self.num_message_chars = num_message_chars
|
| 16 |
+
super().__init__(*args, **kwargs)
|
| 17 |
+
self.intro_prompt = (
|
| 18 |
+
"Welcome to an iterated game. You are {agent}. The other agent is {other_agent}.\n"
|
| 19 |
+
"Setup:\n"
|
| 20 |
+
"1. The game has multiple independent rounds.\n"
|
| 21 |
+
"2. In each round, there are multiple items to split between the two agents.\n"
|
| 22 |
+
"3. Both agents are assigned a per-item value between 1 and 20 (inclusive) in each round.\n"
|
| 23 |
+
"4. You can only observe your own per-item values.\n"
|
| 24 |
+
"5. Because assignments are random, both agents are equally likely to have same expected per-item value.\n"
|
| 25 |
+
"\n"
|
| 26 |
+
"Protocol:\n"
|
| 27 |
+
"1. At the start of the round, one agent begins the conversation. The starting role alternates each round.\n"
|
| 28 |
+
"2. Agents exchange a short chat ({quota_messages_per_agent_per_round} messages per round per agent) to negotiate how to split the item.\n"
|
| 29 |
+
" - Use this chat to communicate your private per-item value to make informed proposals.\n"
|
| 30 |
+
"3. After the chat, both agents simultaneously propose the amount of each item they will keep.\n"
|
| 31 |
+
"4. If the total sum of proposals is less than or equal to the item quantity, both agents receive their proposed amounts.\n"
|
| 32 |
+
"5. If the total sum of proposals exceeds the item quantity, they are allocated proportionally.\n"
|
| 33 |
+
"6. Your points for the round = (amount you receive per item) x (your per-item value for that round), added across all items.\n"
|
| 34 |
+
"7. Points are accumulated across rounds.\n"
|
| 35 |
+
"Your goal: {goal}\n"
|
| 36 |
+
)
|
| 37 |
+
self.new_round_prompt = (
|
| 38 |
+
"A New Round Begins\n"
|
| 39 |
+
"The items to split are {quantities}.\n"
|
| 40 |
+
"Your per-item values are {value}."
|
| 41 |
+
)
|
| 42 |
+
self.last_round_prompt = (
|
| 43 |
+
"Last Round Summary:\n"
|
| 44 |
+
" - Items to split: {last_quantities}\n"
|
| 45 |
+
" - Your per-item values: {last_value_agent}\n"
|
| 46 |
+
" - {other_agent}'s per-item values: {last_value_coagent}\n"
|
| 47 |
+
" - You proposed: {last_split_agent}\n"
|
| 48 |
+
" - You earned: {last_points_agent} points\n"
|
| 49 |
+
" - {other_agent} proposed: {last_split_coagent}\n"
|
| 50 |
+
" - {other_agent} earned: {last_points_coagent} points\n"
|
| 51 |
+
" - Round Complete.\n"
|
| 52 |
+
)
|
| 53 |
+
self.send_split_prompt = (
|
| 54 |
+
"Message quota is finished for this round.\n"
|
| 55 |
+
"{other_agent} has finalized their proposal.\n"
|
| 56 |
+
"Submit your finalization now\n"
|
| 57 |
+
"Respond with {proposal_style2}"
|
| 58 |
+
)
|
| 59 |
+
# self.wait_for_message_prompt = "Wait for {other_agent} to send a message..."
|
| 60 |
+
self.wait_for_message_prompt = ""
|
| 61 |
+
self.last_message_prompt = "{other_agent} said: {last_message}"
|
| 62 |
+
# self.send_message_prompt = (
|
| 63 |
+
# f"Send your message now (max {self.num_message_chars} chars)."
|
| 64 |
+
# )
|
| 65 |
+
self.send_message_prompt = f"Send your message now in <message>...</message> (<={self.num_message_chars} chars)."
|
| 66 |
+
|
| 67 |
+
def get_message_regex(self, observation: TrustAndSplitObs) -> str:
|
| 68 |
+
"""Constrain chat to bounded XML tags for stable parsing."""
|
| 69 |
+
return rf"<message>[\s\S]{{0,{self.num_message_chars}}}</message>"
|
| 70 |
+
|
| 71 |
+
# def get_message_regex(self, observation: TrustAndSplitObs) -> str:
|
| 72 |
+
# return rf"(?s).{{0,{self.num_message_chars}}}"
|
| 73 |
+
|
| 74 |
+
def get_split_regex(self, observation: TrustAndSplitObs) -> str:
|
| 75 |
+
"""Allow natural-language item names while still returning machine-parsable XML."""
|
| 76 |
+
items = list(observation.quantities.keys())
|
| 77 |
+
# Accept both singular and plural forms
|
| 78 |
+
item_pattern = "|".join(
|
| 79 |
+
[f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?" for item in items]
|
| 80 |
+
)
|
| 81 |
+
regex = rf"(?i)<items_to_self> ?((?:\s*(?P<num>(10|[0-9]))\s*(?P<item>{item_pattern})\s*,?)+) ?</items_to_self>"
|
| 82 |
+
return regex
|
| 83 |
+
|
| 84 |
+
def get_split_action(
|
| 85 |
+
self, policy_output: str, observation: TrustAndSplitObs
|
| 86 |
+
) -> Split:
|
| 87 |
+
"""Convert human-readable allocation text back into canonical item IDs."""
|
| 88 |
+
items = list(observation.quantities.keys())
|
| 89 |
+
import re as _re
|
| 90 |
+
|
| 91 |
+
split_regex = self.get_split_regex(observation)
|
| 92 |
+
items_given_to_self = {item: 0 for item in items}
|
| 93 |
+
m = _re.match(split_regex, policy_output.strip())
|
| 94 |
+
if m:
|
| 95 |
+
# Find all (number, item) pairs
|
| 96 |
+
item_pattern = "|".join(
|
| 97 |
+
[
|
| 98 |
+
f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?"
|
| 99 |
+
for item in items
|
| 100 |
+
]
|
| 101 |
+
)
|
| 102 |
+
inner_regex = rf"(?i)(10|[0-9])\s*({item_pattern})"
|
| 103 |
+
|
| 104 |
+
def normalize_item_name(item_str):
|
| 105 |
+
for orig in items:
|
| 106 |
+
if item_str.lower() == orig.lower():
|
| 107 |
+
return orig
|
| 108 |
+
if orig.endswith("s") and item_str.lower() == orig[:-1].lower():
|
| 109 |
+
return orig
|
| 110 |
+
if (
|
| 111 |
+
not orig.endswith("s")
|
| 112 |
+
and item_str.lower() == orig.lower() + "s"
|
| 113 |
+
):
|
| 114 |
+
return orig
|
| 115 |
+
|
| 116 |
+
for num, item in _re.findall(inner_regex, m.group(1)):
|
| 117 |
+
items_given_to_self[normalize_item_name(item)] = int(num)
|
| 118 |
+
return Split(items_given_to_self=items_given_to_self)
|
src_code_for_reproducibility/markov_games/negotiation/tas_rps_agent.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/tas_rps_agent.py
|
| 3 |
+
Summary: Agent logic for TAS Rock-Paper-Scissors blended game.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Any, Dict, List, Tuple
|
| 10 |
+
|
| 11 |
+
from mllm.markov_games.agent import Agent
|
| 12 |
+
from mllm.markov_games.negotiation.nego_agent import (
|
| 13 |
+
Message,
|
| 14 |
+
NegotiationAgent,
|
| 15 |
+
NegotiationAgentState,
|
| 16 |
+
Split,
|
| 17 |
+
)
|
| 18 |
+
from mllm.markov_games.negotiation.tas_rps_simulation import TrustAndSplitRPSObs
|
| 19 |
+
from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TrustAndSplitRPSAgent(NegotiationAgent):
|
| 23 |
+
"""NegotiationAgent that reasons about hidden hands before submitting TAS splits."""
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
num_message_chars: int,
|
| 28 |
+
message_start_end_format: bool = False,
|
| 29 |
+
proposal_start_end_format: bool = False,
|
| 30 |
+
*args,
|
| 31 |
+
**kwargs,
|
| 32 |
+
):
|
| 33 |
+
self.num_message_chars = num_message_chars
|
| 34 |
+
self.message_start_end_format = message_start_end_format
|
| 35 |
+
self.proposal_start_end_format = proposal_start_end_format
|
| 36 |
+
super().__init__(*args, **kwargs)
|
| 37 |
+
self.intro_prompt = (
|
| 38 |
+
"Welcome to an iterated game. You are {agent}. The other agent is {other_agent}.\n"
|
| 39 |
+
"\n"
|
| 40 |
+
"Setup:\n"
|
| 41 |
+
"1. The game has multiple independent rounds.\n"
|
| 42 |
+
"2. In each round, there are 10 coins to split between the two agents.\n"
|
| 43 |
+
"3. Each agent's per-coin value for that round is determined as follows:\n"
|
| 44 |
+
" - Both agents are randomly assigned a rock, paper or scissors hands\n"
|
| 45 |
+
" - Rock has the upper hand over scissors, scissors has the upper hand over paper and paper has the upper hand over rock.\n"
|
| 46 |
+
" - The agent with the upper hand has a per-coin value of 10.\n"
|
| 47 |
+
" - The agent with the lower hand has a per-coin value of 1.\n"
|
| 48 |
+
"4. You only see your own hand, but you may communicate it in messages and infer your value based on the other agent's hand.\n"
|
| 49 |
+
"5. Over many rounds both agents are equally likely to have the upper and lower hand.\n"
|
| 50 |
+
"\n"
|
| 51 |
+
"Protocol:\n"
|
| 52 |
+
"1. At the start of the round, one agent begins the conversation. The starting role alternates each round.\n"
|
| 53 |
+
"2. Agents exchange a short chat ({quota_messages_per_agent_per_round} messages per round per agent) to negotiate how to split the 10 coins.\n"
|
| 54 |
+
" - Use this chat to communicate your hand so that both agents can determine their per-coin values.\n"
|
| 55 |
+
"3. After the chat, both agents simultaneously propose how many coins they keep.\n"
|
| 56 |
+
"4. If the total sum of proposals is less than or equal to 10, both agents receive their proposals.\n"
|
| 57 |
+
"5. If the total sum of proposals exceeds 10, the coins are allocated proportionally.\n"
|
| 58 |
+
"6. Your points for the round = (coins you receive) x (your per-coin value for that round). \n"
|
| 59 |
+
"7. The points are accumulated across rounds.\n"
|
| 60 |
+
"Your goal: {goal}\n"
|
| 61 |
+
)
|
| 62 |
+
self.new_round_prompt = (
|
| 63 |
+
"A New Round Begins\n"
|
| 64 |
+
"Your hand is {hand}. You don't know {other_agent}'s hand yet.\n"
|
| 65 |
+
)
|
| 66 |
+
# self.last_round_prompt = (
|
| 67 |
+
# "Last Round Summary:\n"
|
| 68 |
+
# " - Your hand: {last_hand_agent}\n"
|
| 69 |
+
# " - {other_agent}'s hand: {last_hand_coagent}\n"
|
| 70 |
+
# " - Your value per coin: {last_value_agent}\n"
|
| 71 |
+
# " - {other_agent}'s value per coin: {last_value_coagent}\n"
|
| 72 |
+
# " - You proposed: {last_split_agent} coins\n"
|
| 73 |
+
# " - You earned: {last_points_agent} points\n"
|
| 74 |
+
# " - {other_agent} proposed: {last_split_coagent} coins\n"
|
| 75 |
+
# " - {other_agent} earned: {last_points_coagent} points\n"
|
| 76 |
+
# " - Round Complete.\n"
|
| 77 |
+
# )
|
| 78 |
+
self.last_round_prompt = "In the previous round, {other_agent} had a {last_hand_value_coagent} hand and proposed {last_split_coagent} coins.\n"
|
| 79 |
+
if self.proposal_start_end_format:
|
| 80 |
+
self.send_split_prompt = (
|
| 81 |
+
"Submit your proposal\n"
|
| 82 |
+
"Respond with <<proposal_start>> x <<proposal_end>> where x is an integer in [0, 10]."
|
| 83 |
+
)
|
| 84 |
+
else:
|
| 85 |
+
self.send_split_prompt = (
|
| 86 |
+
"Submit your proposal\n"
|
| 87 |
+
"Respond with <coins_to_self> x </coins_to_self> where x is an integer in [0, 10]."
|
| 88 |
+
)
|
| 89 |
+
self.wait_for_message_prompt = "Wait for {other_agent} to send a message..."
|
| 90 |
+
# self.wait_for_message_prompt = ""
|
| 91 |
+
self.last_message_prompt = "{other_agent} said: {last_message}"
|
| 92 |
+
if self.message_start_end_format:
|
| 93 |
+
self.send_message_prompt = f"Send your message now in <<message_start>>...<<message_end>> (<={self.num_message_chars} chars)."
|
| 94 |
+
else:
|
| 95 |
+
self.send_message_prompt = f"Send your message now in <message>...</message> (<={self.num_message_chars} chars)."
|
| 96 |
+
|
| 97 |
+
def get_message_regex(self, observation: TrustAndSplitRPSObs) -> str:
|
| 98 |
+
"""Switch between <message>...</message> and <<message_start>> formats on demand."""
|
| 99 |
+
if self.message_start_end_format:
|
| 100 |
+
return (
|
| 101 |
+
rf"<<message_start>>[\s\S]{{0,{self.num_message_chars}}}<<message_end>>"
|
| 102 |
+
)
|
| 103 |
+
else:
|
| 104 |
+
return rf"<message>[\s\S]{{0,{self.num_message_chars}}}</message>"
|
| 105 |
+
|
| 106 |
+
def get_split_regex(self, observation: TrustAndSplitRPSObs) -> str:
|
| 107 |
+
"""Force single-number proposals inside whichever tag style the config selected."""
|
| 108 |
+
if self.proposal_start_end_format:
|
| 109 |
+
return r"<<proposal_start>> ?(10|[0-9]) ?<<proposal_end>>"
|
| 110 |
+
else:
|
| 111 |
+
return r"<coins_to_self> ?(10|[0-9]) ?</coins_to_self>"
|
| 112 |
+
|
| 113 |
+
def get_split_action(
|
| 114 |
+
self, policy_output: str, observation: TrustAndSplitRPSObs
|
| 115 |
+
) -> Split:
|
| 116 |
+
"""Parse the proposal tag (or raw integer fallback) into a Split."""
|
| 117 |
+
import re as _re
|
| 118 |
+
|
| 119 |
+
if self.proposal_start_end_format:
|
| 120 |
+
m = _re.search(
|
| 121 |
+
r"<<proposal_start>> ?(10|[0-9]) ?<<proposal_end>>", policy_output
|
| 122 |
+
)
|
| 123 |
+
else:
|
| 124 |
+
m = _re.search(
|
| 125 |
+
r"<coins_to_self> ?(10|[0-9]) ?</coins_to_self>", policy_output
|
| 126 |
+
)
|
| 127 |
+
coins_int = int(m.group(1)) if m else int(policy_output)
|
| 128 |
+
return Split(items_given_to_self={"coins": coins_int})
|
src_code_for_reproducibility/markov_games/negotiation/tas_rps_simulation.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/negotiation/tas_rps_simulation.py
|
| 3 |
+
Summary: Simulation for TAS Rock-Paper-Scissors blended scenarios.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import copy
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Dict, List, Literal, Tuple
|
| 9 |
+
|
| 10 |
+
from mllm.markov_games.negotiation.nego_simulation import (
|
| 11 |
+
Message,
|
| 12 |
+
NegotiationObs,
|
| 13 |
+
NegotiationSimulation,
|
| 14 |
+
NegotiationState,
|
| 15 |
+
Split,
|
| 16 |
+
compute_tas_style_rewards,
|
| 17 |
+
)
|
| 18 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 19 |
+
|
| 20 |
+
AgentId = str
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _get_rps_winner(
|
| 24 |
+
hand1: Literal["rock", "paper", "scissors"],
|
| 25 |
+
hand2: Literal["rock", "paper", "scissors"],
|
| 26 |
+
) -> Literal["rock", "paper", "scissors"]:
|
| 27 |
+
"""Determine winner of rock-paper-scissors between two hands."""
|
| 28 |
+
if hand1 == hand2:
|
| 29 |
+
raise ValueError("Hands should be different")
|
| 30 |
+
if (
|
| 31 |
+
(hand1 == "rock" and hand2 == "scissors")
|
| 32 |
+
or (hand1 == "paper" and hand2 == "rock")
|
| 33 |
+
or (hand1 == "scissors" and hand2 == "paper")
|
| 34 |
+
):
|
| 35 |
+
return hand1
|
| 36 |
+
else:
|
| 37 |
+
return hand2
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class TrustAndSplitRPSState(NegotiationState):
|
| 42 |
+
"""Negotiation state augmented with the current and previous RPS hands."""
|
| 43 |
+
|
| 44 |
+
hands: Dict[
|
| 45 |
+
AgentId, Literal["rock", "paper", "scissors"]
|
| 46 |
+
] # rock, paper, or scissors
|
| 47 |
+
previous_hands: Dict[AgentId, Literal["rock", "paper", "scissors"]] | None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class TrustAndSplitRPSObs(NegotiationObs):
|
| 52 |
+
"""Agent-facing observation enriched with last-hand metadata."""
|
| 53 |
+
|
| 54 |
+
hand: Literal["rock", "paper", "scissors"]
|
| 55 |
+
last_hand_agent: Literal["rock", "paper", "scissors"] | None
|
| 56 |
+
last_hand_coagent: Literal["rock", "paper", "scissors"] | None
|
| 57 |
+
last_hand_value_coagent: Literal["upper", "lower"] | None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TrustAndSplitRPSSimulation(NegotiationSimulation):
|
| 61 |
+
"""Negotiation variant that splices TAS splitting with RPS-determined stakes."""
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
alternating_hands: bool = False,
|
| 66 |
+
alternating_mix_ratio: float = None,
|
| 67 |
+
*args,
|
| 68 |
+
**kwargs,
|
| 69 |
+
):
|
| 70 |
+
self.alternating_hands = alternating_hands
|
| 71 |
+
self.alternating_mix_ratio = alternating_mix_ratio
|
| 72 |
+
super().__init__(*args, **kwargs)
|
| 73 |
+
if self.alternating_mix_ratio is not None:
|
| 74 |
+
if self.rng.random() < self.alternating_mix_ratio:
|
| 75 |
+
self.alternating_hands = True
|
| 76 |
+
else:
|
| 77 |
+
self.alternating_hands = False
|
| 78 |
+
|
| 79 |
+
def _sample_hands_and_values(
|
| 80 |
+
self,
|
| 81 |
+
alternate_hands: bool = False,
|
| 82 |
+
) -> Tuple[Dict[AgentId, str], Dict[AgentId, float]]:
|
| 83 |
+
"""
|
| 84 |
+
Sample a rock-paper-scissors hand for each agent plus the per-hand value.
|
| 85 |
+
|
| 86 |
+
When ``alternate_hands`` is True we deliberately flip the previous round's
|
| 87 |
+
winner/loser roles to create nonstationary payoffs; otherwise we draw
|
| 88 |
+
uniformly without replacement.
|
| 89 |
+
"""
|
| 90 |
+
hands = ["rock", "paper", "scissors"]
|
| 91 |
+
if alternate_hands:
|
| 92 |
+
previous_hands = list(self.state.previous_hands.values())
|
| 93 |
+
hand1, hand2 = self.rng.choice(hands, size=2, replace=False)
|
| 94 |
+
winner = _get_rps_winner(hand1, hand2)
|
| 95 |
+
loser = hand1 if winner == hand2 else hand2
|
| 96 |
+
previous_winner = _get_rps_winner(previous_hands[0], previous_hands[1])
|
| 97 |
+
agent_hands, values = {}, {}
|
| 98 |
+
for agent_id in self.agent_ids:
|
| 99 |
+
if self.state.previous_hands[agent_id] == previous_winner:
|
| 100 |
+
agent_hands[agent_id] = loser
|
| 101 |
+
values[agent_id] = 1.0
|
| 102 |
+
else:
|
| 103 |
+
agent_hands[agent_id] = winner
|
| 104 |
+
values[agent_id] = 10.0
|
| 105 |
+
return agent_hands, values
|
| 106 |
+
else:
|
| 107 |
+
# Assign different hands to each agent
|
| 108 |
+
hand1, hand2 = self.rng.choice(hands, size=2, replace=False)
|
| 109 |
+
|
| 110 |
+
agent_hands = {self.agent_ids[0]: hand1, self.agent_ids[1]: hand2}
|
| 111 |
+
|
| 112 |
+
# Determine winner and assign values
|
| 113 |
+
winner = _get_rps_winner(hand1, hand2)
|
| 114 |
+
values = {}
|
| 115 |
+
for agent_id in self.agent_ids:
|
| 116 |
+
if agent_hands[agent_id] == winner:
|
| 117 |
+
values[agent_id] = 10.0 # Winner gets value 10
|
| 118 |
+
else:
|
| 119 |
+
values[agent_id] = 1.0 # Loser gets value 1
|
| 120 |
+
|
| 121 |
+
return agent_hands, values
|
| 122 |
+
|
| 123 |
+
def set_new_round_of_variant(self):
|
| 124 |
+
"""Refresh hands/values and reset round-specific state."""
|
| 125 |
+
self.state.previous_hands = copy.deepcopy(self.state.hands)
|
| 126 |
+
new_hands, new_values = self._sample_hands_and_values(
|
| 127 |
+
alternate_hands=self.alternating_hands
|
| 128 |
+
)
|
| 129 |
+
self.state.hands = new_hands
|
| 130 |
+
self.state.values = new_values
|
| 131 |
+
# Quantities are constant in TAS
|
| 132 |
+
self.state.quantities = {"coins": 10}
|
| 133 |
+
self.state.split_phase = False
|
| 134 |
+
|
| 135 |
+
def get_info_of_variant(
|
| 136 |
+
self, state: NegotiationState, actions: Dict[AgentId, Any]
|
| 137 |
+
) -> Dict[str, Any]:
|
| 138 |
+
"""Expose variant-specific tensors for downstream logging/analysis."""
|
| 139 |
+
return {
|
| 140 |
+
"quantities": copy.deepcopy(state.quantities),
|
| 141 |
+
"hands": copy.deepcopy(state.hands),
|
| 142 |
+
"values": copy.deepcopy(state.values),
|
| 143 |
+
"previous_hands": copy.deepcopy(state.previous_hands),
|
| 144 |
+
"previous_values": copy.deepcopy(state.previous_values),
|
| 145 |
+
"splits": copy.deepcopy(state.splits),
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
|
| 149 |
+
"""Delegates to TAS reward helper because the payout rule is identical."""
|
| 150 |
+
return compute_tas_style_rewards(
|
| 151 |
+
self.agent_ids, self.state.values, splits, self.state.quantities
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
def get_obs_agent(self, agent_id):
|
| 155 |
+
"""Return a full Trust-and-Split observation for ``agent_id``."""
|
| 156 |
+
other_id = self._other(agent_id)
|
| 157 |
+
last_value_coagent = (
|
| 158 |
+
None
|
| 159 |
+
if self.state.previous_values is None
|
| 160 |
+
else self.state.previous_values.get(other_id)
|
| 161 |
+
)
|
| 162 |
+
last_hand_coagent = (
|
| 163 |
+
None
|
| 164 |
+
if self.state.previous_hands is None
|
| 165 |
+
else self.state.previous_hands.get(other_id)
|
| 166 |
+
)
|
| 167 |
+
last_points_coagent = (
|
| 168 |
+
None
|
| 169 |
+
if self.state.previous_points is None
|
| 170 |
+
else round(self.state.previous_points.get(other_id), 1)
|
| 171 |
+
)
|
| 172 |
+
last_value_agent = (
|
| 173 |
+
None
|
| 174 |
+
if self.state.previous_values is None
|
| 175 |
+
else self.state.previous_values.get(agent_id)
|
| 176 |
+
)
|
| 177 |
+
last_hand_agent = (
|
| 178 |
+
None
|
| 179 |
+
if self.state.previous_hands is None
|
| 180 |
+
else self.state.previous_hands.get(agent_id)
|
| 181 |
+
)
|
| 182 |
+
last_points_agent = (
|
| 183 |
+
None
|
| 184 |
+
if self.state.previous_points is None
|
| 185 |
+
else round(self.state.previous_points.get(agent_id), 1)
|
| 186 |
+
)
|
| 187 |
+
last_split_coagent = None
|
| 188 |
+
last_split_agent = None
|
| 189 |
+
if self.state.previous_splits is not None:
|
| 190 |
+
last_split_coagent = self.state.previous_splits[
|
| 191 |
+
other_id
|
| 192 |
+
].items_given_to_self["coins"]
|
| 193 |
+
last_split_agent = self.state.previous_splits[agent_id].items_given_to_self[
|
| 194 |
+
"coins"
|
| 195 |
+
]
|
| 196 |
+
if last_hand_agent is None or last_hand_coagent is None:
|
| 197 |
+
last_hand_value_coagent = None
|
| 198 |
+
else:
|
| 199 |
+
winner = _get_rps_winner(last_hand_agent, last_hand_coagent)
|
| 200 |
+
last_hand_value_coagent = (
|
| 201 |
+
"upper" if winner == last_hand_coagent else "lower"
|
| 202 |
+
)
|
| 203 |
+
obs = TrustAndSplitRPSObs(
|
| 204 |
+
round_nb=self.state.round_nb,
|
| 205 |
+
last_message=self.state.last_message,
|
| 206 |
+
quota_messages_per_agent_per_round=self.quota_messages_per_agent_per_round,
|
| 207 |
+
current_agent=self.state.current_agent,
|
| 208 |
+
other_agent=self.agent_id_to_name[other_id],
|
| 209 |
+
quantities={"coins": 10},
|
| 210 |
+
item_types=self.item_types,
|
| 211 |
+
value=self.state.values[agent_id],
|
| 212 |
+
split_phase=self.state.split_phase,
|
| 213 |
+
last_split_agent=last_split_agent,
|
| 214 |
+
last_value_agent=last_value_agent,
|
| 215 |
+
last_points_agent=last_points_agent,
|
| 216 |
+
last_split_coagent=last_split_coagent,
|
| 217 |
+
last_value_coagent=last_value_coagent,
|
| 218 |
+
last_points_coagent=last_points_coagent,
|
| 219 |
+
hand=self.state.hands[agent_id],
|
| 220 |
+
last_hand_coagent=last_hand_coagent,
|
| 221 |
+
last_hand_agent=last_hand_agent,
|
| 222 |
+
last_quantities=self.state.previous_quantities,
|
| 223 |
+
last_hand_value_coagent=last_hand_value_coagent,
|
| 224 |
+
)
|
| 225 |
+
return obs
|
| 226 |
+
|
| 227 |
+
def get_state(self):
|
| 228 |
+
return self.state
|
| 229 |
+
|
| 230 |
+
def get_safe_copy(self):
|
| 231 |
+
"""Return a safe copy of the simulation."""
|
| 232 |
+
simulation_copy = copy.copy(self)
|
| 233 |
+
simulation_copy.state = copy.deepcopy(self.state)
|
| 234 |
+
return simulation_copy
|
| 235 |
+
|
| 236 |
+
def reset(self):
|
| 237 |
+
"""Initialize and return initial observations"""
|
| 238 |
+
# Decide starting agent alternating across resets for determinism
|
| 239 |
+
start_agent = self.agent_ids[self._starting_agent_index]
|
| 240 |
+
hands, values = self._sample_hands_and_values()
|
| 241 |
+
self.state = TrustAndSplitRPSState(
|
| 242 |
+
round_nb=0,
|
| 243 |
+
last_message="",
|
| 244 |
+
current_agent=start_agent,
|
| 245 |
+
quantities={"coins": 10},
|
| 246 |
+
values=values,
|
| 247 |
+
splits={aid: None for aid in self.agent_ids},
|
| 248 |
+
nb_messages_sent={aid: 0 for aid in self.agent_ids},
|
| 249 |
+
previous_values=None,
|
| 250 |
+
previous_splits=None,
|
| 251 |
+
previous_points=None,
|
| 252 |
+
split_phase=False,
|
| 253 |
+
hands=hands,
|
| 254 |
+
previous_hands=None,
|
| 255 |
+
previous_quantities=None,
|
| 256 |
+
)
|
| 257 |
+
return self.get_obs()
|
src_code_for_reproducibility/markov_games/rollout_tree.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/rollout_tree.py
|
| 3 |
+
Summary: Defines rollout tree data structures and serialization helpers.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any, List, Literal, Optional, Tuple
|
| 12 |
+
|
| 13 |
+
import jsonschema
|
| 14 |
+
from pydantic import BaseModel, Field, model_validator
|
| 15 |
+
|
| 16 |
+
from mllm.chat_utils.chat_turn import ChatTurn
|
| 17 |
+
|
| 18 |
+
AgentId = str
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SimulationStepLog(BaseModel):
|
| 22 |
+
"""Minimal snapshot of environment-side rewards and auxiliary info."""
|
| 23 |
+
|
| 24 |
+
rewards: dict[AgentId, float]
|
| 25 |
+
info: Any = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class AgentActLog(BaseModel):
|
| 29 |
+
"""LLM-side provenance for an action (chat turns + metadata)."""
|
| 30 |
+
|
| 31 |
+
chat_turns: list[ChatTurn] | None
|
| 32 |
+
info: Any = None
|
| 33 |
+
|
| 34 |
+
@model_validator(mode="after")
|
| 35 |
+
def _exactly_one_state_end(self):
|
| 36 |
+
"""
|
| 37 |
+
This method is used to enforce that for each AgentActLog, there is exactly one ChatTurn which is a state end.
|
| 38 |
+
"""
|
| 39 |
+
if self.chat_turns != []:
|
| 40 |
+
n = sum(1 for t in self.chat_turns if t.is_state_end)
|
| 41 |
+
if n != 1:
|
| 42 |
+
raise ValueError(
|
| 43 |
+
f"AgentActLog must have exactly one ChatTurn with is_state_end=True; got {self.chat_turns}."
|
| 44 |
+
)
|
| 45 |
+
return self
|
| 46 |
+
else:
|
| 47 |
+
return self
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class StepLog(BaseModel):
|
| 51 |
+
action_logs: dict[AgentId, AgentActLog]
|
| 52 |
+
simulation_step_log: SimulationStepLog
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# BranchType = Literal["unilateral_deviation", "common_deviation"] # might not be necessary
|
| 56 |
+
# class BranchNodeInfo(BaseModel):
|
| 57 |
+
# branch_id: str
|
| 58 |
+
# branch_for: AgentId
|
| 59 |
+
# branch_type: BranchType
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class RolloutTreeNode(BaseModel):
|
| 63 |
+
"""Single timestep of the main trajectory (or a branch) plus linkage."""
|
| 64 |
+
|
| 65 |
+
step_log: StepLog
|
| 66 |
+
time_step: int
|
| 67 |
+
child: RolloutTreeNode | RolloutTreeBranchNode | None = None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class RolloutTreeBranchNode(BaseModel):
|
| 71 |
+
"""
|
| 72 |
+
First item of the tuple indicates which agent "called" for an alternative branch.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
main_child: RolloutTreeNode
|
| 76 |
+
branches: dict[AgentId, list[RolloutTreeNode]] | None = None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class RolloutTreeRootNode(BaseModel):
|
| 80 |
+
"""Entry point for serialized rollouts (main path plus optional branches)."""
|
| 81 |
+
|
| 82 |
+
id: int
|
| 83 |
+
crn_id: int # ID of the rng used to generate this rollout tree
|
| 84 |
+
child: RolloutTreeNode | RolloutTreeBranchNode | None = None
|
| 85 |
+
agent_ids: List[AgentId] = Field(min_length=1)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# class RolloutTreeLeafNode(BaseModel):
|
| 89 |
+
# step_log: StepLog
|
| 90 |
+
# time_step: int
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# Necessary for self-referential stuff in pydantic
|
| 94 |
+
RolloutTreeBranchNode.model_rebuild()
|
| 95 |
+
RolloutTreeNode.model_rebuild()
|
src_code_for_reproducibility/markov_games/run_markov_games.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/run_markov_games.py
|
| 3 |
+
Summary: CLI entry point for running configured Markov-game experiments.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
|
| 10 |
+
from torch._C import ClassType
|
| 11 |
+
|
| 12 |
+
from mllm.markov_games.markov_game import MarkovGame
|
| 13 |
+
from mllm.markov_games.rollout_tree import RolloutTreeRootNode
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
async def run_markov_games(
|
| 17 |
+
runner: Callable[[MarkovGame], RolloutTreeRootNode],
|
| 18 |
+
runner_kwargs: dict,
|
| 19 |
+
output_folder: str,
|
| 20 |
+
markov_games: list[MarkovGame],
|
| 21 |
+
) -> list[RolloutTreeRootNode]:
|
| 22 |
+
"""
|
| 23 |
+
Kick off multiple Markov game rollouts concurrently and return their trees.
|
| 24 |
+
|
| 25 |
+
Parameters mirror the Hydra configs (runner callable + kwargs) so callers can
|
| 26 |
+
choose ``LinearRunner``, ``AlternativeActionsRunner`` or future variants.
|
| 27 |
+
"""
|
| 28 |
+
tasks = []
|
| 29 |
+
for mg in markov_games:
|
| 30 |
+
tasks.append(
|
| 31 |
+
asyncio.create_task(
|
| 32 |
+
runner(markov_game=mg, output_folder=output_folder, **runner_kwargs)
|
| 33 |
+
)
|
| 34 |
+
)
|
| 35 |
+
return await asyncio.gather(*tasks)
|
src_code_for_reproducibility/markov_games/simulation.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/simulation.py
|
| 3 |
+
Summary: Core simulation loop utilities and step logging for Markov games.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from typing import Any, Tuple
|
| 8 |
+
|
| 9 |
+
from numpy.random import default_rng
|
| 10 |
+
|
| 11 |
+
from mllm.markov_games.rollout_tree import SimulationStepLog
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Simulation(ABC):
|
| 15 |
+
@abstractmethod
|
| 16 |
+
def __init__(self, seed: int, *args, **kwargs):
|
| 17 |
+
self.seed = seed
|
| 18 |
+
self.rng = default_rng(self.seed)
|
| 19 |
+
|
| 20 |
+
@abstractmethod
|
| 21 |
+
def step(self, actions: Any) -> Tuple[bool, SimulationStepLog]:
|
| 22 |
+
"""
|
| 23 |
+
Advance the environment by one logical tick using ``actions``.
|
| 24 |
+
|
| 25 |
+
Returns
|
| 26 |
+
-------
|
| 27 |
+
terminated: bool
|
| 28 |
+
Whether the episode has finished.
|
| 29 |
+
SimulationStepLog
|
| 30 |
+
Reward/info bundle describing this transition.
|
| 31 |
+
"""
|
| 32 |
+
raise NotImplementedError
|
| 33 |
+
|
| 34 |
+
def get_obs(self):
|
| 35 |
+
"""Return a dict mapping agent_id -> observation for *all* agents."""
|
| 36 |
+
raise NotImplementedError
|
| 37 |
+
|
| 38 |
+
def get_obs_agent(self, agent_id):
|
| 39 |
+
"""Return the observation for a single agent."""
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def get_obs_size(self):
|
| 43 |
+
"""Describe the observation tensor shape (useful for critic heads)."""
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
def get_state(self):
|
| 47 |
+
"""Return the privileged simulator state if available."""
|
| 48 |
+
raise NotImplementedError
|
| 49 |
+
|
| 50 |
+
def get_state_size(self):
|
| 51 |
+
"""Describe the state tensor shape."""
|
| 52 |
+
raise NotImplementedError
|
| 53 |
+
|
| 54 |
+
def get_avail_actions(self):
|
| 55 |
+
"""Return the global action mask/tensor if the space is discrete."""
|
| 56 |
+
raise NotImplementedError
|
| 57 |
+
|
| 58 |
+
def get_avail_agent_actions(self, agent_id):
|
| 59 |
+
"""Return the available action mask for a given agent."""
|
| 60 |
+
raise NotImplementedError
|
| 61 |
+
|
| 62 |
+
def get_total_actions(self):
|
| 63 |
+
"""Returns the total number of actions an agent could ever take.
|
| 64 |
+
|
| 65 |
+
Implementations currently assume a discrete, one-dimensional action space per agent.
|
| 66 |
+
"""
|
| 67 |
+
raise NotImplementedError
|
| 68 |
+
|
| 69 |
+
def get_safe_copy(self):
|
| 70 |
+
"""
|
| 71 |
+
Return copy of the simulator that shares no mutable state with the original.
|
| 72 |
+
"""
|
| 73 |
+
raise NotImplementedError
|
| 74 |
+
|
| 75 |
+
def reset(self):
|
| 76 |
+
"""Reset to the initial state and return the starting observations."""
|
| 77 |
+
raise NotImplementedError
|
| 78 |
+
|
| 79 |
+
def render(self):
|
| 80 |
+
"""Optional human-facing visualization."""
|
| 81 |
+
raise NotImplementedError
|
| 82 |
+
|
| 83 |
+
def close(self):
|
| 84 |
+
"""Release any owned resources (files, processes, etc.)."""
|
| 85 |
+
raise NotImplementedError
|
| 86 |
+
|
| 87 |
+
# def seed(self):
|
| 88 |
+
# raise NotImplementedError
|
| 89 |
+
|
| 90 |
+
def save_replay(self):
|
| 91 |
+
raise NotImplementedError
|
| 92 |
+
|
| 93 |
+
def get_simulation_info(self):
|
| 94 |
+
raise NotImplementedError
|
src_code_for_reproducibility/markov_games/statistics_runner.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/markov_games/statistics_runner.py
|
| 3 |
+
Summary: Executes multiple rollouts to compute experiment statistics.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import gc
|
| 9 |
+
import json
|
| 10 |
+
import pickle
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional
|
| 14 |
+
|
| 15 |
+
from basic_render import find_iteration_folders
|
| 16 |
+
|
| 17 |
+
from mllm.markov_games.rollout_tree import (
|
| 18 |
+
RolloutTreeBranchNode,
|
| 19 |
+
RolloutTreeNode,
|
| 20 |
+
RolloutTreeRootNode,
|
| 21 |
+
SimulationStepLog,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _iterate_main_nodes(root: RolloutTreeRootNode) -> Iterator[RolloutTreeNode]:
|
| 26 |
+
"""
|
| 27 |
+
Iterate the main path nodes without materializing full path lists.
|
| 28 |
+
"""
|
| 29 |
+
current = root.child
|
| 30 |
+
while current is not None:
|
| 31 |
+
if isinstance(current, RolloutTreeNode):
|
| 32 |
+
yield current
|
| 33 |
+
current = current.child
|
| 34 |
+
elif isinstance(current, RolloutTreeBranchNode):
|
| 35 |
+
# Follow only the main child on the main trajectory
|
| 36 |
+
current = current.main_child
|
| 37 |
+
else:
|
| 38 |
+
break
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def iterate_main_simulation_logs(
|
| 42 |
+
root: RolloutTreeRootNode,
|
| 43 |
+
) -> Iterator[SimulationStepLog]:
|
| 44 |
+
"""Yield ``SimulationStepLog`` objects along the main (non-branch) path."""
|
| 45 |
+
for node in _iterate_main_nodes(root):
|
| 46 |
+
yield node.step_log.simulation_step_log
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def stream_rollout_files(iteration_folder: Path) -> Iterator[Path]:
|
| 50 |
+
"""Iterate over every ``*.rt.pkl`` file under an iteration directory."""
|
| 51 |
+
for p in iteration_folder.rglob("*.rt.pkl"):
|
| 52 |
+
if p.is_file():
|
| 53 |
+
yield p
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_root(path: Path) -> RolloutTreeRootNode:
|
| 57 |
+
"""Load and validate a rollout tree from disk."""
|
| 58 |
+
with open(path, "rb") as f:
|
| 59 |
+
data = pickle.load(f)
|
| 60 |
+
return RolloutTreeRootNode.model_validate(data)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass
|
| 64 |
+
class StatRecord:
|
| 65 |
+
"""Convenience container for serialized stat rows."""
|
| 66 |
+
|
| 67 |
+
mgid: int
|
| 68 |
+
crn_id: Optional[int]
|
| 69 |
+
iteration: str
|
| 70 |
+
values: Dict[str, Any]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class StatComputer:
|
| 74 |
+
"""
|
| 75 |
+
Stateful stat computer that consumes SimulationStepLog instances
|
| 76 |
+
and produces final aggregated values for one rollout (mgid).
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def update(self, sl: SimulationStepLog) -> None: # pragma: no cover - interface
|
| 80 |
+
raise NotImplementedError
|
| 81 |
+
|
| 82 |
+
def finalize(self) -> Dict[str, Any]: # pragma: no cover - interface
|
| 83 |
+
raise NotImplementedError
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def run_stats(
|
| 87 |
+
data_root: Path,
|
| 88 |
+
game_name: str,
|
| 89 |
+
make_computers: Callable[[], List[StatComputer]],
|
| 90 |
+
output_filename: Optional[str] = None,
|
| 91 |
+
output_format: str = "json", # "json" (dict of lists) or "jsonl"
|
| 92 |
+
) -> Path:
|
| 93 |
+
"""
|
| 94 |
+
Compute stats across all iteration_* folders under data_root.
|
| 95 |
+
Writes JSONL to data_root/statistics/<output_filename or f"{game_name}.stats.jsonl">.
|
| 96 |
+
"""
|
| 97 |
+
data_root = Path(data_root)
|
| 98 |
+
outdir = data_root / "statistics"
|
| 99 |
+
outdir.mkdir(parents=True, exist_ok=True)
|
| 100 |
+
# Choose extension by format
|
| 101 |
+
default_name = (
|
| 102 |
+
f"{game_name}.stats.json"
|
| 103 |
+
if output_format == "json"
|
| 104 |
+
else f"{game_name}.stats.jsonl"
|
| 105 |
+
)
|
| 106 |
+
outfile = outdir / (
|
| 107 |
+
output_filename if output_filename is not None else default_name
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Rewrite file each run to keep it clean and small
|
| 111 |
+
if outfile.exists():
|
| 112 |
+
outfile.unlink()
|
| 113 |
+
|
| 114 |
+
iteration_folders = find_iteration_folders(str(data_root))
|
| 115 |
+
|
| 116 |
+
# If writing JSONL, stream directly; otherwise accumulate minimal records
|
| 117 |
+
if output_format == "jsonl":
|
| 118 |
+
with open(outfile, "w", encoding="utf-8") as w:
|
| 119 |
+
for iteration_folder in iteration_folders:
|
| 120 |
+
iteration_name = Path(iteration_folder).name
|
| 121 |
+
for pkl_path in stream_rollout_files(Path(iteration_folder)):
|
| 122 |
+
root = load_root(pkl_path)
|
| 123 |
+
|
| 124 |
+
computers = make_computers()
|
| 125 |
+
for sl in iterate_main_simulation_logs(root):
|
| 126 |
+
for comp in computers:
|
| 127 |
+
try:
|
| 128 |
+
comp.update(sl)
|
| 129 |
+
except Exception:
|
| 130 |
+
continue
|
| 131 |
+
|
| 132 |
+
values: Dict[str, Any] = {}
|
| 133 |
+
for comp in computers:
|
| 134 |
+
try:
|
| 135 |
+
values.update(comp.finalize())
|
| 136 |
+
except Exception:
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
rec = {
|
| 140 |
+
"mgid": getattr(root, "id", None),
|
| 141 |
+
"crn_id": getattr(root, "crn_id", None),
|
| 142 |
+
"iteration": iteration_name,
|
| 143 |
+
"stats": values,
|
| 144 |
+
}
|
| 145 |
+
w.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
| 146 |
+
|
| 147 |
+
del root
|
| 148 |
+
del computers
|
| 149 |
+
gc.collect()
|
| 150 |
+
else:
|
| 151 |
+
# Aggregate to dict-of-lists for easier plotting
|
| 152 |
+
records: List[Dict[str, Any]] = []
|
| 153 |
+
# Process in deterministic order
|
| 154 |
+
for iteration_folder in iteration_folders:
|
| 155 |
+
iteration_name = Path(iteration_folder).name
|
| 156 |
+
for pkl_path in stream_rollout_files(Path(iteration_folder)):
|
| 157 |
+
root = load_root(pkl_path)
|
| 158 |
+
|
| 159 |
+
computers = make_computers()
|
| 160 |
+
for sl in iterate_main_simulation_logs(root):
|
| 161 |
+
for comp in computers:
|
| 162 |
+
try:
|
| 163 |
+
comp.update(sl)
|
| 164 |
+
except Exception:
|
| 165 |
+
continue
|
| 166 |
+
|
| 167 |
+
values: Dict[str, Any] = {}
|
| 168 |
+
for comp in computers:
|
| 169 |
+
try:
|
| 170 |
+
values.update(comp.finalize())
|
| 171 |
+
except Exception:
|
| 172 |
+
continue
|
| 173 |
+
|
| 174 |
+
records.append(
|
| 175 |
+
{
|
| 176 |
+
"mgid": getattr(root, "id", None),
|
| 177 |
+
"crn_id": getattr(root, "crn_id", None),
|
| 178 |
+
"iteration": iteration_name,
|
| 179 |
+
"stats": values,
|
| 180 |
+
}
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
del root
|
| 184 |
+
del computers
|
| 185 |
+
gc.collect()
|
| 186 |
+
|
| 187 |
+
# Build dict-of-lists with nested stats preserved
|
| 188 |
+
# Collect all stat keys and nested agent keys where needed
|
| 189 |
+
mgids: List[Any] = []
|
| 190 |
+
crn_ids: List[Any] = []
|
| 191 |
+
iterations_out: List[str] = []
|
| 192 |
+
# stats_out is a nested structure mirroring keys but with lists
|
| 193 |
+
stats_out: Dict[str, Any] = {}
|
| 194 |
+
|
| 195 |
+
# First pass to collect union of keys
|
| 196 |
+
stat_keys: set[str] = set()
|
| 197 |
+
nested_agent_keys: Dict[str, set[str]] = {}
|
| 198 |
+
for r in records:
|
| 199 |
+
stats = r.get("stats", {}) or {}
|
| 200 |
+
for k, v in stats.items():
|
| 201 |
+
stat_keys.add(k)
|
| 202 |
+
if isinstance(v, dict):
|
| 203 |
+
nested = nested_agent_keys.setdefault(k, set())
|
| 204 |
+
for ak in v.keys():
|
| 205 |
+
nested.add(str(ak))
|
| 206 |
+
|
| 207 |
+
# Initialize structure
|
| 208 |
+
for k in stat_keys:
|
| 209 |
+
if k in nested_agent_keys:
|
| 210 |
+
stats_out[k] = {ak: [] for ak in sorted(nested_agent_keys[k])}
|
| 211 |
+
else:
|
| 212 |
+
stats_out[k] = []
|
| 213 |
+
|
| 214 |
+
# Fill lists
|
| 215 |
+
for r in records:
|
| 216 |
+
mgids.append(r.get("mgid"))
|
| 217 |
+
crn_ids.append(r.get("crn_id"))
|
| 218 |
+
iterations_out.append(r.get("iteration"))
|
| 219 |
+
stats = r.get("stats", {}) or {}
|
| 220 |
+
for k in stat_keys:
|
| 221 |
+
val = stats.get(k)
|
| 222 |
+
if isinstance(stats_out[k], dict):
|
| 223 |
+
# per-agent dict
|
| 224 |
+
agent_dict = val if isinstance(val, dict) else {}
|
| 225 |
+
for ak in stats_out[k].keys():
|
| 226 |
+
stats_out[k][ak].append(agent_dict.get(ak))
|
| 227 |
+
else:
|
| 228 |
+
stats_out[k].append(val)
|
| 229 |
+
|
| 230 |
+
with open(outfile, "w", encoding="utf-8") as w:
|
| 231 |
+
json.dump(
|
| 232 |
+
{
|
| 233 |
+
"mgid": mgids,
|
| 234 |
+
"crn_id": crn_ids,
|
| 235 |
+
"iteration": iterations_out,
|
| 236 |
+
"stats": stats_out,
|
| 237 |
+
},
|
| 238 |
+
w,
|
| 239 |
+
ensure_ascii=False,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
return outfile
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def run_stats_functional(
|
| 246 |
+
data_root: Path,
|
| 247 |
+
game_name: str,
|
| 248 |
+
metrics: Dict[str, Callable[[SimulationStepLog], Optional[Dict[str, float]]]],
|
| 249 |
+
output_filename: Optional[str] = None,
|
| 250 |
+
output_format: str = "json",
|
| 251 |
+
) -> Path:
|
| 252 |
+
"""
|
| 253 |
+
Functional variant where metrics is a dict of name -> f(SimulationStepLog) -> {agent_id: value}.
|
| 254 |
+
Aggregates per rollout by averaging over steps where a metric produced a value.
|
| 255 |
+
Writes a single consolidated file in data_root/statistics/.
|
| 256 |
+
"""
|
| 257 |
+
data_root = Path(data_root)
|
| 258 |
+
outdir = data_root / "statistics"
|
| 259 |
+
outdir.mkdir(parents=True, exist_ok=True)
|
| 260 |
+
default_name = (
|
| 261 |
+
f"{game_name}.stats.json"
|
| 262 |
+
if output_format == "json"
|
| 263 |
+
else f"{game_name}.stats.jsonl"
|
| 264 |
+
)
|
| 265 |
+
outfile = outdir / (
|
| 266 |
+
output_filename if output_filename is not None else default_name
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
if outfile.exists():
|
| 270 |
+
outfile.unlink()
|
| 271 |
+
|
| 272 |
+
iteration_folders = find_iteration_folders(str(data_root))
|
| 273 |
+
|
| 274 |
+
def finalize_rollout(
|
| 275 |
+
agg: Dict[str, Dict[str, List[float]]]
|
| 276 |
+
) -> Dict[str, Dict[str, float]]:
|
| 277 |
+
# avg per metric per agent
|
| 278 |
+
result: Dict[str, Dict[str, float]] = {}
|
| 279 |
+
for mname, agent_values in agg.items():
|
| 280 |
+
result[mname] = {}
|
| 281 |
+
for aid, vals in agent_values.items():
|
| 282 |
+
if not vals:
|
| 283 |
+
result[mname][aid] = None # keep alignment; could be None
|
| 284 |
+
else:
|
| 285 |
+
result[mname][aid] = sum(vals) / len(vals)
|
| 286 |
+
return result
|
| 287 |
+
|
| 288 |
+
if output_format == "jsonl":
|
| 289 |
+
with open(outfile, "w", encoding="utf-8") as w:
|
| 290 |
+
for iteration_folder in iteration_folders:
|
| 291 |
+
iteration_name = Path(iteration_folder).name
|
| 292 |
+
for pkl_path in stream_rollout_files(Path(iteration_folder)):
|
| 293 |
+
root = load_root(pkl_path)
|
| 294 |
+
|
| 295 |
+
# aggregator structure: metric -> agent_id -> list of values
|
| 296 |
+
agg: Dict[str, Dict[str, List[float]]] = {
|
| 297 |
+
m: {} for m in metrics.keys()
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
for sl in iterate_main_simulation_logs(root):
|
| 301 |
+
for mname, fn in metrics.items():
|
| 302 |
+
try:
|
| 303 |
+
vals = fn(sl)
|
| 304 |
+
except Exception:
|
| 305 |
+
vals = None
|
| 306 |
+
if not vals:
|
| 307 |
+
continue
|
| 308 |
+
for aid, v in vals.items():
|
| 309 |
+
if v is None:
|
| 310 |
+
continue
|
| 311 |
+
lst = agg[mname].setdefault(str(aid), [])
|
| 312 |
+
try:
|
| 313 |
+
lst.append(float(v))
|
| 314 |
+
except Exception:
|
| 315 |
+
continue
|
| 316 |
+
|
| 317 |
+
values = finalize_rollout(agg)
|
| 318 |
+
rec = {
|
| 319 |
+
"mgid": getattr(root, "id", None),
|
| 320 |
+
"crn_id": getattr(root, "crn_id", None),
|
| 321 |
+
"iteration": iteration_name,
|
| 322 |
+
"stats": values,
|
| 323 |
+
}
|
| 324 |
+
w.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
| 325 |
+
|
| 326 |
+
del root
|
| 327 |
+
gc.collect()
|
| 328 |
+
else:
|
| 329 |
+
records: List[Dict[str, Any]] = []
|
| 330 |
+
for iteration_folder in iteration_folders:
|
| 331 |
+
iteration_name = Path(iteration_folder).name
|
| 332 |
+
for pkl_path in stream_rollout_files(Path(iteration_folder)):
|
| 333 |
+
root = load_root(pkl_path)
|
| 334 |
+
|
| 335 |
+
agg: Dict[str, Dict[str, List[float]]] = {m: {} for m in metrics.keys()}
|
| 336 |
+
for sl in iterate_main_simulation_logs(root):
|
| 337 |
+
for mname, fn in metrics.items():
|
| 338 |
+
try:
|
| 339 |
+
vals = fn(sl)
|
| 340 |
+
except Exception:
|
| 341 |
+
vals = None
|
| 342 |
+
if not vals:
|
| 343 |
+
continue
|
| 344 |
+
for aid, v in vals.items():
|
| 345 |
+
if v is None:
|
| 346 |
+
continue
|
| 347 |
+
lst = agg[mname].setdefault(str(aid), [])
|
| 348 |
+
try:
|
| 349 |
+
lst.append(float(v))
|
| 350 |
+
except Exception:
|
| 351 |
+
continue
|
| 352 |
+
|
| 353 |
+
values = finalize_rollout(agg)
|
| 354 |
+
records.append(
|
| 355 |
+
{
|
| 356 |
+
"mgid": getattr(root, "id", None),
|
| 357 |
+
"crn_id": getattr(root, "crn_id", None),
|
| 358 |
+
"iteration": iteration_name,
|
| 359 |
+
"stats": values,
|
| 360 |
+
}
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
del root
|
| 364 |
+
gc.collect()
|
| 365 |
+
|
| 366 |
+
# Build dict-of-lists output
|
| 367 |
+
mgids: List[Any] = []
|
| 368 |
+
crn_ids: List[Any] = []
|
| 369 |
+
iterations_out: List[str] = []
|
| 370 |
+
stats_out: Dict[str, Any] = {}
|
| 371 |
+
|
| 372 |
+
stat_keys: set[str] = set()
|
| 373 |
+
nested_agent_keys: Dict[str, set[str]] = {}
|
| 374 |
+
for r in records:
|
| 375 |
+
stats = r.get("stats", {}) or {}
|
| 376 |
+
for k, v in stats.items():
|
| 377 |
+
stat_keys.add(k)
|
| 378 |
+
if isinstance(v, dict):
|
| 379 |
+
nested = nested_agent_keys.setdefault(k, set())
|
| 380 |
+
for ak in v.keys():
|
| 381 |
+
nested.add(str(ak))
|
| 382 |
+
|
| 383 |
+
for k in stat_keys:
|
| 384 |
+
if k in nested_agent_keys:
|
| 385 |
+
stats_out[k] = {ak: [] for ak in sorted(nested_agent_keys[k])}
|
| 386 |
+
else:
|
| 387 |
+
stats_out[k] = []
|
| 388 |
+
|
| 389 |
+
for r in records:
|
| 390 |
+
mgids.append(r.get("mgid"))
|
| 391 |
+
crn_ids.append(r.get("crn_id"))
|
| 392 |
+
iterations_out.append(r.get("iteration"))
|
| 393 |
+
stats = r.get("stats", {}) or {}
|
| 394 |
+
for k in stat_keys:
|
| 395 |
+
val = stats.get(k)
|
| 396 |
+
if isinstance(stats_out[k], dict):
|
| 397 |
+
agent_dict = val if isinstance(val, dict) else {}
|
| 398 |
+
for ak in stats_out[k].keys():
|
| 399 |
+
stats_out[k][ak].append(agent_dict.get(ak))
|
| 400 |
+
else:
|
| 401 |
+
stats_out[k].append(val)
|
| 402 |
+
|
| 403 |
+
with open(outfile, "w", encoding="utf-8") as w:
|
| 404 |
+
json.dump(
|
| 405 |
+
{
|
| 406 |
+
"mgid": mgids,
|
| 407 |
+
"crn_id": crn_ids,
|
| 408 |
+
"iteration": iterations_out,
|
| 409 |
+
"stats": stats_out,
|
| 410 |
+
},
|
| 411 |
+
w,
|
| 412 |
+
ensure_ascii=False,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
return outfile
|
src_code_for_reproducibility/models/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/models/__init__.py
|
| 3 |
+
Summary: Exports model-layer utilities from the models package.
|
| 4 |
+
"""
|
src_code_for_reproducibility/models/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (273 Bytes). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/adapter_training_wrapper.cpython-312.pyc
ADDED
|
Binary file (5.07 kB). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/human_policy.cpython-312.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/inference_backend.cpython-312.pyc
ADDED
|
Binary file (2.39 kB). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/inference_backend_dummy.cpython-312.pyc
ADDED
|
Binary file (2.49 kB). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/inference_backend_vllm.cpython-312.pyc
ADDED
|
Binary file (5.12 kB). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/large_language_model_api.cpython-312.pyc
ADDED
|
Binary file (7.09 kB). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/large_language_model_local.cpython-312.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
src_code_for_reproducibility/models/__pycache__/scalar_critic.cpython-312.pyc
ADDED
|
Binary file (3.33 kB). View file
|
|
|
src_code_for_reproducibility/models/human_policy.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/models/human_policy.py
|
| 3 |
+
Summary: Implements an interactive human-in-the-loop policy for experiments.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import shutil
|
| 10 |
+
import sys
|
| 11 |
+
from typing import Callable, Dict, List, Optional
|
| 12 |
+
|
| 13 |
+
from mllm.markov_games.rollout_tree import ChatTurn
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import rstr # For generating example strings from regex
|
| 17 |
+
except Exception: # pragma: no cover
|
| 18 |
+
rstr = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _clear_terminal() -> None:
|
| 22 |
+
"""
|
| 23 |
+
Clear the terminal screen in a cross-platform manner.
|
| 24 |
+
"""
|
| 25 |
+
if sys.stdout.isatty():
|
| 26 |
+
os.system("cls" if os.name == "nt" else "clear")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _terminal_width(default: int = 100) -> int:
|
| 30 |
+
try:
|
| 31 |
+
return shutil.get_terminal_size().columns
|
| 32 |
+
except Exception:
|
| 33 |
+
return default
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _horizontal_rule(char: str = "─") -> str:
|
| 37 |
+
width = max(20, _terminal_width() - 2)
|
| 38 |
+
return char * width
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class _Style:
|
| 42 |
+
# ANSI colors (bright, readable)
|
| 43 |
+
RESET = "\033[0m"
|
| 44 |
+
BOLD = "\033[1m"
|
| 45 |
+
DIM = "\033[2m"
|
| 46 |
+
# Foreground colors
|
| 47 |
+
FG_BLUE = "\033[94m" # user/system headers
|
| 48 |
+
FG_GREEN = "\033[92m" # human response header
|
| 49 |
+
FG_YELLOW = "\033[93m" # notices
|
| 50 |
+
FG_RED = "\033[91m" # errors
|
| 51 |
+
FG_MAGENTA = "\033[95m" # regex
|
| 52 |
+
FG_CYAN = "\033[96m" # tips
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _render_chat(state) -> str:
|
| 56 |
+
"""
|
| 57 |
+
Render prior messages in a compact, readable terminal format.
|
| 58 |
+
|
| 59 |
+
Expected message dict keys: {"role": str, "content": str, ...}
|
| 60 |
+
"""
|
| 61 |
+
lines: List[str] = []
|
| 62 |
+
lines.append(_horizontal_rule())
|
| 63 |
+
lines.append(f"{_Style.FG_BLUE}{_Style.BOLD} Conversation so far {_Style.RESET}")
|
| 64 |
+
lines.append(_horizontal_rule())
|
| 65 |
+
for chat in state:
|
| 66 |
+
role = chat.role
|
| 67 |
+
content = str(chat.content).strip()
|
| 68 |
+
# Map roles to display names and colors/emojis
|
| 69 |
+
if role == "assistant":
|
| 70 |
+
header = f"{_Style.FG_GREEN}{_Style.BOLD}HUMAN--🧑💻{_Style.RESET}"
|
| 71 |
+
elif role == "user":
|
| 72 |
+
header = f"{_Style.FG_BLUE}{_Style.BOLD}USER--⚙️{_Style.RESET}"
|
| 73 |
+
else:
|
| 74 |
+
header = f"[{_Style.DIM}{role.upper()}{_Style.RESET}]"
|
| 75 |
+
lines.append(header)
|
| 76 |
+
# Indent content for readability
|
| 77 |
+
for line in content.splitlines() or [""]:
|
| 78 |
+
lines.append(f" {line}")
|
| 79 |
+
lines.append("")
|
| 80 |
+
lines.append(_horizontal_rule())
|
| 81 |
+
return "\n".join(lines)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
async def _async_input(prompt_text: str) -> str:
|
| 85 |
+
"""Non-blocking input using a background thread."""
|
| 86 |
+
return await asyncio.to_thread(input, prompt_text)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _short_regex_example(regex: str, max_len: int = 30) -> Optional[str]:
|
| 90 |
+
"""
|
| 91 |
+
Try to produce a short example string that matches the regex.
|
| 92 |
+
We attempt multiple times and pick the first <= max_len.
|
| 93 |
+
"""
|
| 94 |
+
if rstr is None:
|
| 95 |
+
return None
|
| 96 |
+
try:
|
| 97 |
+
for _ in range(20):
|
| 98 |
+
candidate = rstr.xeger(regex)
|
| 99 |
+
if len(candidate) <= max_len:
|
| 100 |
+
return candidate
|
| 101 |
+
# Fallback to truncation (may break match, so don't return)
|
| 102 |
+
return None
|
| 103 |
+
except Exception:
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _detect_input_type(regex: str | None) -> tuple[str, str, str]:
|
| 108 |
+
"""
|
| 109 |
+
Detect what type of input is expected based on the regex pattern.
|
| 110 |
+
Returns (input_type, start_tag, end_tag)
|
| 111 |
+
"""
|
| 112 |
+
if regex is None:
|
| 113 |
+
return "text", "", ""
|
| 114 |
+
|
| 115 |
+
if "message_start" in regex and "message_end" in regex:
|
| 116 |
+
return "message", "<<message_start>>", "<<message_end>>"
|
| 117 |
+
elif "proposal_start" in regex and "proposal_end" in regex:
|
| 118 |
+
return "proposal", "<<proposal_start>>", "<<proposal_end>>"
|
| 119 |
+
else:
|
| 120 |
+
return "text", "", ""
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
async def human_policy(state, agent_id, regex: str | None = None) -> str:
|
| 124 |
+
"""
|
| 125 |
+
Async human-in-the-loop policy.
|
| 126 |
+
|
| 127 |
+
- Displays prior conversation context in the terminal.
|
| 128 |
+
- Prompts the user for a response.
|
| 129 |
+
- If a regex is provided, validates and re-prompts until it matches.
|
| 130 |
+
- Automatically adds formatting tags based on expected input type.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
prompt: Chat history as a list of {role, content} dicts.
|
| 134 |
+
regex: Optional fullmatch validation pattern.
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
The user's validated response string.
|
| 138 |
+
"""
|
| 139 |
+
# Detect input type and formatting
|
| 140 |
+
input_type, start_tag, end_tag = _detect_input_type(regex)
|
| 141 |
+
|
| 142 |
+
while True:
|
| 143 |
+
_clear_terminal()
|
| 144 |
+
print(_render_chat(state))
|
| 145 |
+
|
| 146 |
+
if regex:
|
| 147 |
+
example = _short_regex_example(regex, max_len=30)
|
| 148 |
+
print(
|
| 149 |
+
f"{_Style.FG_MAGENTA}{_Style.BOLD}Expected format (regex fullmatch):{_Style.RESET}"
|
| 150 |
+
)
|
| 151 |
+
print(f" {_Style.FG_MAGENTA}{regex}{_Style.RESET}")
|
| 152 |
+
if example:
|
| 153 |
+
print(
|
| 154 |
+
f"{_Style.FG_CYAN}Example (random, <=30 chars):{_Style.RESET} {example}"
|
| 155 |
+
)
|
| 156 |
+
print(_horizontal_rule("."))
|
| 157 |
+
|
| 158 |
+
# Custom prompt based on input type
|
| 159 |
+
if input_type == "message":
|
| 160 |
+
print(
|
| 161 |
+
f"{_Style.FG_YELLOW}Type your message content (formatting will be added automatically):{_Style.RESET}"
|
| 162 |
+
)
|
| 163 |
+
elif input_type == "proposal":
|
| 164 |
+
print(
|
| 165 |
+
f"{_Style.FG_YELLOW}Type your proposal (number only, formatting will be added automatically):{_Style.RESET}"
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
print(
|
| 169 |
+
f"{_Style.FG_YELLOW}Type your response and press Enter.{_Style.RESET}"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
print(
|
| 173 |
+
f"{_Style.DIM}Commands: /help to view commands, /refresh to re-render, /quit to abort{_Style.RESET}"
|
| 174 |
+
)
|
| 175 |
+
else:
|
| 176 |
+
print(
|
| 177 |
+
f"{_Style.FG_YELLOW}Type your response and press Enter.{_Style.RESET} {_Style.DIM}(/help for commands){_Style.RESET}"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
user_in = (await _async_input("> ")).rstrip("\n")
|
| 181 |
+
|
| 182 |
+
# Commands
|
| 183 |
+
if user_in.strip().lower() in {"/help", "/h"}:
|
| 184 |
+
print(f"\n{_Style.FG_CYAN}{_Style.BOLD}Available commands:{_Style.RESET}")
|
| 185 |
+
print(
|
| 186 |
+
f" {_Style.FG_CYAN}/help{_Style.RESET} or {_Style.FG_CYAN}/h{_Style.RESET} Show this help"
|
| 187 |
+
)
|
| 188 |
+
print(
|
| 189 |
+
f" {_Style.FG_CYAN}/refresh{_Style.RESET} or {_Style.FG_CYAN}/r{_Style.RESET} Re-render the conversation and prompt"
|
| 190 |
+
)
|
| 191 |
+
print(
|
| 192 |
+
f" {_Style.FG_CYAN}/quit{_Style.RESET} or {_Style.FG_CYAN}/q{_Style.RESET} Abort the run (raises KeyboardInterrupt)"
|
| 193 |
+
)
|
| 194 |
+
await asyncio.sleep(1.0)
|
| 195 |
+
continue
|
| 196 |
+
if user_in.strip().lower() in {"/refresh", "/r"}:
|
| 197 |
+
continue
|
| 198 |
+
if user_in.strip().lower() in {"/quit", "/q"}:
|
| 199 |
+
raise KeyboardInterrupt("Human aborted run from human_policy")
|
| 200 |
+
|
| 201 |
+
# Add formatting tags if needed
|
| 202 |
+
if start_tag and end_tag:
|
| 203 |
+
formatted_input = f"{start_tag}{user_in}{end_tag}"
|
| 204 |
+
else:
|
| 205 |
+
formatted_input = user_in
|
| 206 |
+
|
| 207 |
+
if regex is None:
|
| 208 |
+
return ChatTurn(
|
| 209 |
+
role="assistant", agent_id=agent_id, content=formatted_input
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# Validate against regex (fullmatch)
|
| 213 |
+
try:
|
| 214 |
+
pattern = re.compile(regex)
|
| 215 |
+
except re.error as e:
|
| 216 |
+
# If regex is invalid, fall back to accepting any input
|
| 217 |
+
print(
|
| 218 |
+
f"{_Style.FG_RED}Warning:{_Style.RESET} Provided regex is invalid: {e}. Accepting input without validation."
|
| 219 |
+
)
|
| 220 |
+
await asyncio.sleep(0.5)
|
| 221 |
+
return ChatTurn(
|
| 222 |
+
role="assistant", agent_id=agent_id, content=formatted_input
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
if pattern.fullmatch(formatted_input):
|
| 226 |
+
return ChatTurn(
|
| 227 |
+
role="assistant", agent_id=agent_id, content=formatted_input
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
# Show validation error and re-prompt
|
| 231 |
+
print("")
|
| 232 |
+
print(
|
| 233 |
+
f"{_Style.FG_RED}{_Style.BOLD}Input did not match the required format.{_Style.RESET} Please try again."
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
if input_type == "message":
|
| 237 |
+
print(
|
| 238 |
+
f"You entered: {_Style.FG_CYAN}{start_tag}{user_in}{end_tag}{_Style.RESET}"
|
| 239 |
+
)
|
| 240 |
+
print(f"Just type the message content without tags.")
|
| 241 |
+
elif input_type == "proposal":
|
| 242 |
+
print(
|
| 243 |
+
f"You entered: {_Style.FG_CYAN}{start_tag}{user_in}{end_tag}{_Style.RESET}"
|
| 244 |
+
)
|
| 245 |
+
print(f"Just type the number without tags.")
|
| 246 |
+
else:
|
| 247 |
+
print(f"Expected (regex):")
|
| 248 |
+
print(f" {_Style.FG_MAGENTA}{regex}{_Style.RESET}")
|
| 249 |
+
|
| 250 |
+
print(_horizontal_rule("."))
|
| 251 |
+
print(f"{_Style.FG_YELLOW}Press Enter to retry...{_Style.RESET}")
|
| 252 |
+
await _async_input("")
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def get_human_policies() -> Dict[str, Callable[[List[Dict]], str]]:
|
| 256 |
+
"""
|
| 257 |
+
Expose the human policy in the same map shape used elsewhere.
|
| 258 |
+
"""
|
| 259 |
+
# Type hint says Callable[[List[Dict]], str] but we intentionally return the async callable.
|
| 260 |
+
return {"human_policy": human_policy} # type: ignore[return-value]
|
src_code_for_reproducibility/models/inference_backend_vllm.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/models/inference_backend_vllm.py
|
| 3 |
+
Summary: Connects to in-process vLLM instances for batched generation.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import re
|
| 8 |
+
from typing import Optional
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from transformers import AutoTokenizer
|
| 12 |
+
from vllm import AsyncEngineArgs, AsyncLLMEngine, SamplingParams
|
| 13 |
+
from vllm.inputs import TokensPrompt
|
| 14 |
+
from vllm.lora.request import LoRARequest
|
| 15 |
+
from vllm.sampling_params import GuidedDecodingParams, RequestOutputKind
|
| 16 |
+
|
| 17 |
+
from mllm.models.inference_backend import LLMInferenceBackend, LLMInferenceOutput
|
| 18 |
+
from mllm.utils.short_id_gen import generate_short_id
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class VLLMAsyncBackend(LLMInferenceBackend):
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
model_name: str,
|
| 25 |
+
tokenizer: AutoTokenizer,
|
| 26 |
+
# adapter_paths: dict[str, str],
|
| 27 |
+
engine_init_kwargs: dict = {},
|
| 28 |
+
sampling_params: dict = {},
|
| 29 |
+
):
|
| 30 |
+
self.model_name = model_name
|
| 31 |
+
self.vllm_adapter_ids = {}
|
| 32 |
+
ea = dict(model=model_name, **engine_init_kwargs)
|
| 33 |
+
self.engine = AsyncLLMEngine.from_engine_args(AsyncEngineArgs(**ea))
|
| 34 |
+
|
| 35 |
+
self.sampling_params = sampling_params
|
| 36 |
+
self.tokenizer = tokenizer
|
| 37 |
+
|
| 38 |
+
def prepare_adapter(
|
| 39 |
+
self,
|
| 40 |
+
adapter_id: Optional[str],
|
| 41 |
+
adapter_path: Optional[str],
|
| 42 |
+
weights_got_updated: bool,
|
| 43 |
+
) -> None:
|
| 44 |
+
if weights_got_updated:
|
| 45 |
+
self.vllm_adapter_ids[adapter_id] = generate_short_id()
|
| 46 |
+
self.current_lora_request = LoRARequest(
|
| 47 |
+
adapter_id,
|
| 48 |
+
self.vllm_adapter_ids[adapter_id],
|
| 49 |
+
adapter_path,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
async def toggle_training_mode(self) -> None:
|
| 53 |
+
await self.engine.sleep(level=1)
|
| 54 |
+
|
| 55 |
+
async def toggle_eval_mode(self) -> None:
|
| 56 |
+
await self.engine.wake_up()
|
| 57 |
+
|
| 58 |
+
def shutdown(self) -> None:
|
| 59 |
+
# No explicit close call; engine stops when process exits.
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
async def generate(
|
| 63 |
+
self,
|
| 64 |
+
input_token_ids: list[int],
|
| 65 |
+
regex: Optional[str] = None,
|
| 66 |
+
extract_thinking: bool = False,
|
| 67 |
+
) -> LLMInferenceOutput:
|
| 68 |
+
# Build SamplingParams correctly
|
| 69 |
+
guided = GuidedDecodingParams(regex=regex) if regex else None
|
| 70 |
+
sp = SamplingParams(
|
| 71 |
+
**self.sampling_params,
|
| 72 |
+
guided_decoding=guided,
|
| 73 |
+
output_kind=RequestOutputKind.FINAL_ONLY,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
prompt = TokensPrompt(prompt_token_ids=input_token_ids)
|
| 77 |
+
request_id = f"req-{asyncio.get_running_loop().time()}"
|
| 78 |
+
result_generator = self.engine.generate(
|
| 79 |
+
prompt,
|
| 80 |
+
sp, # SamplingParams(...)
|
| 81 |
+
request_id,
|
| 82 |
+
lora_request=self.current_lora_request,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
async for out in result_generator: # with FINAL_ONLY this runs once
|
| 86 |
+
res = out
|
| 87 |
+
|
| 88 |
+
raw_text = res.outputs[0].text
|
| 89 |
+
out_token_ids = res.outputs[0].token_ids
|
| 90 |
+
log_probs = [
|
| 91 |
+
logprob_dict[token_id].logprob
|
| 92 |
+
for token_id, logprob_dict in zip(out_token_ids, res.outputs[0].logprobs)
|
| 93 |
+
]
|
| 94 |
+
log_probs = torch.tensor(log_probs)
|
| 95 |
+
out_token_ids = torch.tensor(out_token_ids, dtype=torch.long)
|
| 96 |
+
content = raw_text
|
| 97 |
+
reasoning_content = None
|
| 98 |
+
|
| 99 |
+
if extract_thinking:
|
| 100 |
+
m = re.match(
|
| 101 |
+
r"^\n<think>\n([\s\S]*?)</think>\n\n(.*)$", raw_text, flags=re.DOTALL
|
| 102 |
+
)
|
| 103 |
+
if m:
|
| 104 |
+
reasoning_content = m.group(1)
|
| 105 |
+
content = m.group(2)
|
| 106 |
+
return LLMInferenceOutput(
|
| 107 |
+
content=content,
|
| 108 |
+
reasoning_content=reasoning_content,
|
| 109 |
+
log_probs=log_probs,
|
| 110 |
+
out_token_ids=out_token_ids,
|
| 111 |
+
)
|
src_code_for_reproducibility/training/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
File: mllm/training/__init__.py
|
| 3 |
+
Summary: Exposes training submodules through the package namespace.
|
| 4 |
+
"""
|
src_code_for_reproducibility/training/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (281 Bytes). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/annealing_methods.cpython-312.pyc
ADDED
|
Binary file (969 Bytes). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/credit_methods.cpython-312.pyc
ADDED
|
Binary file (12.8 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/tally_metrics.cpython-312.pyc
ADDED
|
Binary file (3.48 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/tally_rollout.cpython-312.pyc
ADDED
|
Binary file (6.01 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/tally_tokenwise.cpython-312.pyc
ADDED
|
Binary file (13.5 kB). View file
|
|
|
src_code_for_reproducibility/training/__pycache__/tokenize_chats.cpython-312.pyc
ADDED
|
Binary file (5.99 kB). View file
|
|
|