Muqeeth commited on
Commit
e80a42f
·
verified ·
1 Parent(s): 83779b2

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .hydra/config.yaml +178 -0
  2. .hydra/hydra.yaml +154 -0
  3. .hydra/overrides.yaml +1 -0
  4. seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/README.md +207 -0
  5. seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/agent_adapter/adapter_config.json +46 -0
  6. src_code_for_reproducibility/__init__.py +4 -0
  7. src_code_for_reproducibility/chat_utils/__pycache__/apply_template.cpython-312.pyc +0 -0
  8. src_code_for_reproducibility/chat_utils/__pycache__/chat_turn.cpython-312.pyc +0 -0
  9. src_code_for_reproducibility/chat_utils/__pycache__/template_specific.cpython-312.pyc +0 -0
  10. src_code_for_reproducibility/markov_games/__pycache__/__init__.cpython-312.pyc +0 -0
  11. src_code_for_reproducibility/markov_games/__pycache__/agent.cpython-312.pyc +0 -0
  12. src_code_for_reproducibility/markov_games/__pycache__/linear_runner.cpython-312.pyc +0 -0
  13. src_code_for_reproducibility/markov_games/__pycache__/mg_utils.cpython-312.pyc +0 -0
  14. src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc +0 -0
  15. src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc +0 -0
  16. src_code_for_reproducibility/markov_games/ipd/__init__.py +11 -0
  17. src_code_for_reproducibility/markov_games/ipd/__pycache__/Ipd_hard_coded_agents.cpython-312.pyc +0 -0
  18. src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc +0 -0
  19. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_agent.cpython-312.pyc +0 -0
  20. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_simulation.cpython-312.pyc +0 -0
  21. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_statistics.cpython-312.pyc +0 -0
  22. src_code_for_reproducibility/markov_games/negotiation/README.md +27 -0
  23. src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_agent.cpython-312.pyc +0 -0
  24. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_agent.cpython-312.pyc +0 -0
  25. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_hard_coded_policies.cpython-312.pyc +0 -0
  26. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_simulation.cpython-312.pyc +0 -0
  27. src_code_for_reproducibility/markov_games/negotiation/__pycache__/negotiation_statistics.cpython-312.pyc +0 -0
  28. src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_agent.cpython-312.pyc +0 -0
  29. src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_simulation.cpython-312.pyc +0 -0
  30. src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_agent.cpython-312.pyc +0 -0
  31. src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_simulation.cpython-312.pyc +0 -0
  32. src_code_for_reproducibility/markov_games/negotiation/dond_agent.py +75 -0
  33. src_code_for_reproducibility/markov_games/negotiation/dond_simulation.py +176 -0
  34. src_code_for_reproducibility/markov_games/negotiation/nego_agent.py +261 -0
  35. src_code_for_reproducibility/markov_games/negotiation/nego_hard_coded_policies.py +70 -0
  36. src_code_for_reproducibility/markov_games/negotiation/negotiation_statistics.py +249 -0
  37. src_code_for_reproducibility/markov_games/negotiation/no_press_nego_agent.py +108 -0
  38. src_code_for_reproducibility/markov_games/negotiation/no_press_nego_simulation.py +182 -0
  39. src_code_for_reproducibility/markov_games/negotiation/tas_agent.py +118 -0
  40. src_code_for_reproducibility/markov_games/negotiation/tas_rps_agent.py +128 -0
  41. src_code_for_reproducibility/markov_games/negotiation/tas_rps_simulation.py +257 -0
  42. src_code_for_reproducibility/utils/__init__.py +4 -0
  43. src_code_for_reproducibility/utils/gather_training_stats.py +262 -0
  44. src_code_for_reproducibility/utils/get_stochastic_game_lengths.py +33 -0
  45. src_code_for_reproducibility/utils/rollout_tree_chat_htmls.py +1597 -0
  46. src_code_for_reproducibility/utils/rollout_tree_gather_utils.py +314 -0
  47. src_code_for_reproducibility/utils/rollout_tree_stats.py +55 -0
  48. src_code_for_reproducibility/utils/short_id_gen.py +16 -0
  49. src_code_for_reproducibility/utils/stat_pack.py +117 -0
  50. src_code_for_reproducibility/utils/wandb_utils.py +170 -0
.hydra/config.yaml ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ experiment:
2
+ wandb_enabled: true
3
+ nb_epochs: 3000
4
+ nb_matches_per_iteration: 64
5
+ reinit_matches_each_it: true
6
+ checkpoint_every_n_iterations: 10
7
+ start_epoch: 0
8
+ resume_experiment: true
9
+ base_seed: 0
10
+ seed_group_size: 8
11
+ train: true
12
+ stat_methods_for_live_wandb: mllm.markov_games.negotiation.negotiation_statistics
13
+ name: split_no_comm_vanilla_ad_align_beta2
14
+ agent_buffer: true
15
+ keep_agent_buffer_count: ${lora_count}
16
+ agent_buffer_recent_k: -1
17
+ logging:
18
+ wandb:
19
+ enabled: false
20
+ project: llm-negotiation
21
+ entity: null
22
+ mode: online
23
+ name: null
24
+ group: null
25
+ tags: []
26
+ notes: null
27
+ temperature: 1.0
28
+ markov_games:
29
+ runner_method_name: LinearRunner
30
+ runner_kwargs: {}
31
+ group_by_round: true
32
+ simulation_class_name: NoPressSimulation
33
+ simulation_init_args:
34
+ nb_of_rounds: 10
35
+ quota_messages_per_agent_per_round: 0
36
+ game_type: 10-1-ties
37
+ atleast_one_conflict: true
38
+ item_types:
39
+ - hats
40
+ - books
41
+ - balls
42
+ agents:
43
+ 0:
44
+ agent_id: ${agent_0_id}
45
+ agent_name: Alice
46
+ agent_class_name: NoPressAgent
47
+ policy_id: base_llm/agent_adapter
48
+ init_kwargs:
49
+ goal: Maximize your total points over the whole game.
50
+ 1:
51
+ agent_id: ${agent_1_id}
52
+ agent_name: Bob
53
+ agent_class_name: NoPressAgent
54
+ policy_id: base_llm/agent_adapter
55
+ init_kwargs:
56
+ goal: Maximize your total points over the whole game.
57
+ models:
58
+ base_llm:
59
+ class: LeanLocalLLM
60
+ init_args:
61
+ llm_id: base_llm
62
+ model_name: Qwen/Qwen2.5-7B-Instruct
63
+ inference_backend: vllm
64
+ hf_kwargs:
65
+ device_map: auto
66
+ torch_dtype: bfloat16
67
+ max_memory:
68
+ 0: 20GiB
69
+ attn_implementation: flash_attention_2
70
+ inference_backend_init_kwargs:
71
+ enable_lora: true
72
+ seed: ${experiment.base_seed}
73
+ enable_prefix_caching: true
74
+ max_model_len: 10000.0
75
+ gpu_memory_utilization: 0.5
76
+ dtype: bfloat16
77
+ trust_remote_code: true
78
+ max_lora_rank: 32
79
+ enforce_eager: false
80
+ max_loras: ${lora_count}
81
+ max_cpu_loras: ${lora_count}
82
+ enable_sleep_mode: true
83
+ inference_backend_sampling_params:
84
+ temperature: ${temperature}
85
+ top_p: 1.0
86
+ max_tokens: 400
87
+ top_k: -1
88
+ logprobs: 0
89
+ adapter_configs:
90
+ agent_adapter:
91
+ task_type: CAUSAL_LM
92
+ r: 32
93
+ lora_alpha: 64
94
+ lora_dropout: 0.0
95
+ target_modules: all-linear
96
+ critic_adapter:
97
+ task_type: CAUSAL_LM
98
+ r: 32
99
+ lora_alpha: 64
100
+ lora_dropout: 0.0
101
+ target_modules: all-linear
102
+ enable_thinking: null
103
+ regex_max_attempts: 3
104
+ critics:
105
+ agent_critic:
106
+ module_pointer:
107
+ - base_llm
108
+ - critic_adapter
109
+ optimizers:
110
+ agent_optimizer:
111
+ module_pointer:
112
+ - base_llm
113
+ - agent_adapter
114
+ optimizer_class_name: torch.optim.Adam
115
+ init_args:
116
+ lr: 3.0e-06
117
+ weight_decay: 0.0
118
+ critic_optimizer:
119
+ module_pointer: agent_critic
120
+ optimizer_class_name: torch.optim.Adam
121
+ init_args:
122
+ lr: 3.0e-06
123
+ weight_decay: 0.0
124
+ trainers:
125
+ agent_trainer:
126
+ class: TrainerAdAlign
127
+ module_pointers:
128
+ policy:
129
+ - base_llm
130
+ - agent_adapter
131
+ policy_optimizer: agent_optimizer
132
+ critic: agent_critic
133
+ critic_optimizer: critic_optimizer
134
+ kwargs:
135
+ entropy_coeff: 0.0
136
+ entropy_topk: null
137
+ entropy_mask_regex: null
138
+ kl_coeff: 0.001
139
+ gradient_clipping: 1.0
140
+ restrict_tokens: null
141
+ mini_batch_size: 1
142
+ use_gradient_checkpointing: false
143
+ temperature: ${temperature}
144
+ device: cuda:0
145
+ use_gae: false
146
+ whiten_advantages: false
147
+ whiten_advantages_time_step_wise: false
148
+ skip_discounted_state_visitation: true
149
+ use_gae_lambda_annealing: false
150
+ gae_lambda_annealing_method: None
151
+ gae_lambda_annealing_method_params: None
152
+ gae_lambda_annealing_limit: 0.95
153
+ discount_factor: 0.9
154
+ use_rloo: true
155
+ enable_tokenwise_logging: false
156
+ pg_loss_normalization: nb_tokens
157
+ truncated_importance_sampling_ratio_cap: 2.0
158
+ reward_normalizing_constant: 100.0
159
+ ad_align_force_coop_first_step: false
160
+ ad_align_clipping: null
161
+ ad_align_gamma: 0.9
162
+ ad_align_exclude_k_equals_t: true
163
+ ad_align_use_sign: false
164
+ ad_align_beta: 2.0
165
+ use_old_ad_align: true
166
+ use_time_regularization: false
167
+ rloo_branch: false
168
+ reuse_baseline: false
169
+ train_on_which_data:
170
+ agent_trainer: ${agent_ids}
171
+ lora_count: 30
172
+ common_agent_kwargs:
173
+ goal: Maximize your total points over the whole game.
174
+ agent_0_id: Alice
175
+ agent_1_id: Bob
176
+ agent_ids:
177
+ - Alice
178
+ - Bob
.hydra/hydra.yaml ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ hydra:
2
+ run:
3
+ dir: ${oc.env:SCRATCH}/llm_negotiation/${now:%Y_%m}/${experiment.name}
4
+ sweep:
5
+ dir: multirun/${now:%Y-%m-%d}/${now:%H-%M-%S}
6
+ subdir: ${hydra.job.num}
7
+ launcher:
8
+ _target_: hydra._internal.core_plugins.basic_launcher.BasicLauncher
9
+ sweeper:
10
+ _target_: hydra._internal.core_plugins.basic_sweeper.BasicSweeper
11
+ max_batch_size: null
12
+ params: null
13
+ help:
14
+ app_name: ${hydra.job.name}
15
+ header: '${hydra.help.app_name} is powered by Hydra.
16
+
17
+ '
18
+ footer: 'Powered by Hydra (https://hydra.cc)
19
+
20
+ Use --hydra-help to view Hydra specific help
21
+
22
+ '
23
+ template: '${hydra.help.header}
24
+
25
+ == Configuration groups ==
26
+
27
+ Compose your configuration from those groups (group=option)
28
+
29
+
30
+ $APP_CONFIG_GROUPS
31
+
32
+
33
+ == Config ==
34
+
35
+ Override anything in the config (foo.bar=value)
36
+
37
+
38
+ $CONFIG
39
+
40
+
41
+ ${hydra.help.footer}
42
+
43
+ '
44
+ hydra_help:
45
+ template: 'Hydra (${hydra.runtime.version})
46
+
47
+ See https://hydra.cc for more info.
48
+
49
+
50
+ == Flags ==
51
+
52
+ $FLAGS_HELP
53
+
54
+
55
+ == Configuration groups ==
56
+
57
+ Compose your configuration from those groups (For example, append hydra/job_logging=disabled
58
+ to command line)
59
+
60
+
61
+ $HYDRA_CONFIG_GROUPS
62
+
63
+
64
+ Use ''--cfg hydra'' to Show the Hydra config.
65
+
66
+ '
67
+ hydra_help: ???
68
+ hydra_logging:
69
+ version: 1
70
+ formatters:
71
+ simple:
72
+ format: '[%(asctime)s][HYDRA] %(message)s'
73
+ handlers:
74
+ console:
75
+ class: logging.StreamHandler
76
+ formatter: simple
77
+ stream: ext://sys.stdout
78
+ root:
79
+ level: INFO
80
+ handlers:
81
+ - console
82
+ loggers:
83
+ logging_example:
84
+ level: DEBUG
85
+ disable_existing_loggers: false
86
+ job_logging:
87
+ version: 1
88
+ formatters:
89
+ simple:
90
+ format: '[%(asctime)s][%(name)s][%(levelname)s] - %(message)s'
91
+ handlers:
92
+ console:
93
+ class: logging.StreamHandler
94
+ formatter: simple
95
+ stream: ext://sys.stdout
96
+ file:
97
+ class: logging.FileHandler
98
+ formatter: simple
99
+ filename: ${hydra.runtime.output_dir}/${hydra.job.name}.log
100
+ root:
101
+ level: INFO
102
+ handlers:
103
+ - console
104
+ - file
105
+ disable_existing_loggers: false
106
+ env: {}
107
+ mode: RUN
108
+ searchpath: []
109
+ callbacks: {}
110
+ output_subdir: .hydra
111
+ overrides:
112
+ hydra:
113
+ - hydra.mode=RUN
114
+ task: []
115
+ job:
116
+ name: run
117
+ chdir: false
118
+ override_dirname: ''
119
+ id: ???
120
+ num: ???
121
+ config_name: split_no_comm_vanilla_ad_align_beta2.yaml
122
+ env_set: {}
123
+ env_copy: []
124
+ config:
125
+ override_dirname:
126
+ kv_sep: '='
127
+ item_sep: ','
128
+ exclude_keys: []
129
+ runtime:
130
+ version: 1.3.2
131
+ version_base: '1.1'
132
+ cwd: /lustre10/scratch/muqeeth/AdAlignLLM
133
+ config_sources:
134
+ - path: hydra.conf
135
+ schema: pkg
136
+ provider: hydra
137
+ - path: /lustre10/scratch/muqeeth/AdAlignLLM/configs
138
+ schema: file
139
+ provider: main
140
+ - path: ''
141
+ schema: structured
142
+ provider: schema
143
+ output_dir: /scratch/muqeeth/llm_negotiation/2026_03/split_no_comm_vanilla_ad_align_beta2
144
+ choices:
145
+ hydra/env: default
146
+ hydra/callbacks: null
147
+ hydra/job_logging: default
148
+ hydra/hydra_logging: default
149
+ hydra/hydra_help: default
150
+ hydra/help: default
151
+ hydra/sweeper: basic
152
+ hydra/launcher: basic
153
+ hydra/output: default
154
+ verbose: false
.hydra/overrides.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ []
seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/README.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: Qwen/Qwen2.5-7B-Instruct
3
+ library_name: peft
4
+ pipeline_tag: text-generation
5
+ tags:
6
+ - base_model:adapter:Qwen/Qwen2.5-7B-Instruct
7
+ - lora
8
+ - transformers
9
+ ---
10
+
11
+ # Model Card for Model ID
12
+
13
+ <!-- Provide a quick summary of what the model is/does. -->
14
+
15
+
16
+
17
+ ## Model Details
18
+
19
+ ### Model Description
20
+
21
+ <!-- Provide a longer summary of what this model is. -->
22
+
23
+
24
+
25
+ - **Developed by:** [More Information Needed]
26
+ - **Funded by [optional]:** [More Information Needed]
27
+ - **Shared by [optional]:** [More Information Needed]
28
+ - **Model type:** [More Information Needed]
29
+ - **Language(s) (NLP):** [More Information Needed]
30
+ - **License:** [More Information Needed]
31
+ - **Finetuned from model [optional]:** [More Information Needed]
32
+
33
+ ### Model Sources [optional]
34
+
35
+ <!-- Provide the basic links for the model. -->
36
+
37
+ - **Repository:** [More Information Needed]
38
+ - **Paper [optional]:** [More Information Needed]
39
+ - **Demo [optional]:** [More Information Needed]
40
+
41
+ ## Uses
42
+
43
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
44
+
45
+ ### Direct Use
46
+
47
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
48
+
49
+ [More Information Needed]
50
+
51
+ ### Downstream Use [optional]
52
+
53
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
54
+
55
+ [More Information Needed]
56
+
57
+ ### Out-of-Scope Use
58
+
59
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
60
+
61
+ [More Information Needed]
62
+
63
+ ## Bias, Risks, and Limitations
64
+
65
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
66
+
67
+ [More Information Needed]
68
+
69
+ ### Recommendations
70
+
71
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
72
+
73
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
74
+
75
+ ## How to Get Started with the Model
76
+
77
+ Use the code below to get started with the model.
78
+
79
+ [More Information Needed]
80
+
81
+ ## Training Details
82
+
83
+ ### Training Data
84
+
85
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
86
+
87
+ [More Information Needed]
88
+
89
+ ### Training Procedure
90
+
91
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
92
+
93
+ #### Preprocessing [optional]
94
+
95
+ [More Information Needed]
96
+
97
+
98
+ #### Training Hyperparameters
99
+
100
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
101
+
102
+ #### Speeds, Sizes, Times [optional]
103
+
104
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
105
+
106
+ [More Information Needed]
107
+
108
+ ## Evaluation
109
+
110
+ <!-- This section describes the evaluation protocols and provides the results. -->
111
+
112
+ ### Testing Data, Factors & Metrics
113
+
114
+ #### Testing Data
115
+
116
+ <!-- This should link to a Dataset Card if possible. -->
117
+
118
+ [More Information Needed]
119
+
120
+ #### Factors
121
+
122
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
123
+
124
+ [More Information Needed]
125
+
126
+ #### Metrics
127
+
128
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
129
+
130
+ [More Information Needed]
131
+
132
+ ### Results
133
+
134
+ [More Information Needed]
135
+
136
+ #### Summary
137
+
138
+
139
+
140
+ ## Model Examination [optional]
141
+
142
+ <!-- Relevant interpretability work for the model goes here -->
143
+
144
+ [More Information Needed]
145
+
146
+ ## Environmental Impact
147
+
148
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
149
+
150
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
151
+
152
+ - **Hardware Type:** [More Information Needed]
153
+ - **Hours used:** [More Information Needed]
154
+ - **Cloud Provider:** [More Information Needed]
155
+ - **Compute Region:** [More Information Needed]
156
+ - **Carbon Emitted:** [More Information Needed]
157
+
158
+ ## Technical Specifications [optional]
159
+
160
+ ### Model Architecture and Objective
161
+
162
+ [More Information Needed]
163
+
164
+ ### Compute Infrastructure
165
+
166
+ [More Information Needed]
167
+
168
+ #### Hardware
169
+
170
+ [More Information Needed]
171
+
172
+ #### Software
173
+
174
+ [More Information Needed]
175
+
176
+ ## Citation [optional]
177
+
178
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
179
+
180
+ **BibTeX:**
181
+
182
+ [More Information Needed]
183
+
184
+ **APA:**
185
+
186
+ [More Information Needed]
187
+
188
+ ## Glossary [optional]
189
+
190
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
191
+
192
+ [More Information Needed]
193
+
194
+ ## More Information [optional]
195
+
196
+ [More Information Needed]
197
+
198
+ ## Model Card Authors [optional]
199
+
200
+ [More Information Needed]
201
+
202
+ ## Model Card Contact
203
+
204
+ [More Information Needed]
205
+ ### Framework versions
206
+
207
+ - PEFT 0.18.1
seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/agent_adapter/adapter_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alora_invocation_tokens": null,
3
+ "alpha_pattern": {},
4
+ "arrow_config": null,
5
+ "auto_mapping": null,
6
+ "base_model_name_or_path": "Qwen/Qwen2.5-7B-Instruct",
7
+ "bias": "none",
8
+ "corda_config": null,
9
+ "ensure_weight_tying": false,
10
+ "eva_config": null,
11
+ "exclude_modules": null,
12
+ "fan_in_fan_out": false,
13
+ "inference_mode": true,
14
+ "init_lora_weights": true,
15
+ "layer_replication": null,
16
+ "layers_pattern": null,
17
+ "layers_to_transform": null,
18
+ "loftq_config": {},
19
+ "lora_alpha": 64,
20
+ "lora_bias": false,
21
+ "lora_dropout": 0.0,
22
+ "megatron_config": null,
23
+ "megatron_core": "megatron.core",
24
+ "modules_to_save": null,
25
+ "peft_type": "LORA",
26
+ "peft_version": "0.18.1",
27
+ "qalora_group_size": 16,
28
+ "r": 32,
29
+ "rank_pattern": {},
30
+ "revision": null,
31
+ "target_modules": [
32
+ "v_proj",
33
+ "gate_proj",
34
+ "o_proj",
35
+ "k_proj",
36
+ "up_proj",
37
+ "down_proj",
38
+ "q_proj"
39
+ ],
40
+ "target_parameters": null,
41
+ "task_type": "CAUSAL_LM",
42
+ "trainable_token_indices": null,
43
+ "use_dora": false,
44
+ "use_qalora": false,
45
+ "use_rslora": false
46
+ }
src_code_for_reproducibility/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ File: mllm/__init__.py
3
+ Summary: Initializes the multi-agent large language model package namespace.
4
+ """
src_code_for_reproducibility/chat_utils/__pycache__/apply_template.cpython-312.pyc ADDED
Binary file (4.13 kB). View file
 
src_code_for_reproducibility/chat_utils/__pycache__/chat_turn.cpython-312.pyc ADDED
Binary file (1.46 kB). View file
 
src_code_for_reproducibility/chat_utils/__pycache__/template_specific.cpython-312.pyc ADDED
Binary file (4.4 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (297 Bytes). View file
 
src_code_for_reproducibility/markov_games/__pycache__/agent.cpython-312.pyc ADDED
Binary file (3.16 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/linear_runner.cpython-312.pyc ADDED
Binary file (1.64 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/__pycache__/run_markov_games.cpython-312.pyc ADDED
Binary file (1.53 kB). View file
 
src_code_for_reproducibility/markov_games/ipd/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/ipd/__init__.py
3
+ Summary: Marks the Iterated Prisoner's Dilemma subpackage.
4
+ """
5
+
6
+ from .Ipd_hard_coded_agents import AlwaysCooperateIPDAgent, AlwaysDefectIPDAgent
7
+
8
+ __all__ = [
9
+ "AlwaysCooperateIPDAgent",
10
+ "AlwaysDefectIPDAgent",
11
+ ]
src_code_for_reproducibility/markov_games/ipd/__pycache__/Ipd_hard_coded_agents.cpython-312.pyc ADDED
Binary file (3.05 kB). View file
 
src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (435 Bytes). View file
 
src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_agent.cpython-312.pyc ADDED
Binary file (4.97 kB). View file
 
src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_simulation.cpython-312.pyc ADDED
Binary file (6.87 kB). View file
 
src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_statistics.cpython-312.pyc ADDED
Binary file (1.42 kB). View file
 
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/__pycache__/dond_agent.cpython-312.pyc ADDED
Binary file (4.66 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_agent.cpython-312.pyc ADDED
Binary file (11.7 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_hard_coded_policies.cpython-312.pyc ADDED
Binary file (3.39 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_simulation.cpython-312.pyc ADDED
Binary file (12.6 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/negotiation_statistics.cpython-312.pyc ADDED
Binary file (14.3 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_agent.cpython-312.pyc ADDED
Binary file (6.11 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_simulation.cpython-312.pyc ADDED
Binary file (9.72 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_agent.cpython-312.pyc ADDED
Binary file (6.05 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_simulation.cpython-312.pyc ADDED
Binary file (11.7 kB). View file
 
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/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_agent.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/no_press_nego_agent.py
3
+ Summary: Agent variant for no-press negotiations without explicit messaging.
4
+ """
5
+
6
+ from typing import Any, Dict, List, Tuple
7
+
8
+ from mllm.markov_games.negotiation.nego_agent import (
9
+ NegotiationAgent,
10
+ NegotiationAgentState,
11
+ )
12
+ from mllm.markov_games.negotiation.nego_simulation import Split
13
+ from mllm.markov_games.negotiation.no_press_nego_simulation import NoPressObs
14
+ from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
15
+
16
+
17
+ class NoPressAgent(NegotiationAgent):
18
+ def __init__(self, *args, **kwargs):
19
+ super().__init__(*args, **kwargs)
20
+ # No communication in this variant
21
+ self.intro_prompt = (
22
+ "Welcome to an iterated game. You are {agent}. The other agent is {other_agent}.\n"
23
+ "Setup:\n"
24
+ "1. The game consists of multiple independent rounds.\n"
25
+ "2. In each round, there are multiple items to split between the two agents.\n"
26
+ "3. Both agents are assigned a per-item value between 1 and 20 (inclusive) in each round.\n"
27
+ "4. You can observe per-item values of both agents.\n"
28
+ "5. Because assignments are random, both agents are equally likely to have same expected per-item value.\n"
29
+ "\n"
30
+ "Protocol:\n"
31
+ "1. Both agents simultaneously propose the amount of each item they will keep.\n"
32
+ "2. If the total sum of proposals is less than or equal to the item quantity, both agents receive their proposed amounts.\n"
33
+ "3. If the total sum of proposals exceeds the item quantity, they are allocated proportionally.\n"
34
+ "4. Your points for the round = (amount you receive per item) x (your per-item value for that round), added across all items.\n"
35
+ "5. Points are accumulated across rounds.\n"
36
+ "Your goal: {goal}\n"
37
+ )
38
+ self.new_round_prompt = (
39
+ "A New Round Begins\n"
40
+ "The items to split are {quantities}.\n"
41
+ "Your per-item values are {value} and {other_agent}'s per-item values are {other_value}."
42
+ )
43
+ self.last_round_prompt = (
44
+ "Last Round Summary:\n"
45
+ " - Items to split: {last_quantities}\n"
46
+ " - Your per-item values: {last_value_agent}\n"
47
+ " - {other_agent}'s per-item values: {last_value_coagent}\n"
48
+ " - You proposed: {last_split_agent}\n"
49
+ " - You earned: {last_points_agent} points\n"
50
+ " - {other_agent} proposed: {last_split_coagent}\n"
51
+ " - {other_agent} earned: {last_points_coagent} points\n"
52
+ " - Round Complete.\n"
53
+ )
54
+ self.send_split_prompt = "Submit Your Proposal\n" "Respond as {proposal_style}"
55
+
56
+ def get_message_regex(self, observation: NoPressObs) -> str:
57
+ """Return an empty pattern because the no-press variant forbids chat."""
58
+ return r"^$" # No messages allowed
59
+
60
+ def get_split_regex(self, observation: NoPressObs) -> str:
61
+ """Match proposals like ``Proposal: 4 coins, 6 apples`` case-insensitively."""
62
+ items = list(observation.quantities.keys())
63
+ # Accept both singular and plural forms
64
+ item_pattern = "|".join(
65
+ [f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?" for item in items]
66
+ )
67
+ regex = rf"(?i)Proposal:\s*((?:\s*(?P<num>(10|[0-9]))\s*(?P<item>{item_pattern})\s*,?)+)"
68
+ return regex
69
+
70
+ def get_split_action(self, policy_output: str, observation: NoPressObs) -> Split:
71
+ """
72
+ Parse the LLM proposal into a normalized ``Split`` structure.
73
+
74
+ The regex-based parser is lenient (accepts pluralization variants) so that
75
+ prompt tweaks do not require re-training the extraction logic.
76
+ """
77
+ items = list(observation.quantities.keys())
78
+ import re as _re
79
+
80
+ split_regex = self.get_split_regex(observation)
81
+ items_given_to_self = {item: 0 for item in items}
82
+ m = _re.match(split_regex, policy_output.strip())
83
+ if m:
84
+ # Find all (number, item) pairs
85
+ item_pattern = "|".join(
86
+ [
87
+ f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?"
88
+ for item in items
89
+ ]
90
+ )
91
+ inner_regex = rf"(?i)(10|[0-9])\s*({item_pattern})"
92
+
93
+ def normalize_item_name(item_str):
94
+ """Canonicalize plural/singular user text back to the config item id."""
95
+ for orig in items:
96
+ if item_str.lower() == orig.lower():
97
+ return orig
98
+ if orig.endswith("s") and item_str.lower() == orig[:-1].lower():
99
+ return orig
100
+ if (
101
+ not orig.endswith("s")
102
+ and item_str.lower() == orig.lower() + "s"
103
+ ):
104
+ return orig
105
+
106
+ for num, item in _re.findall(inner_regex, m.group(1)):
107
+ items_given_to_self[normalize_item_name(item)] = int(num)
108
+ return Split(items_given_to_self=items_given_to_self)
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/utils/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/__init__.py
3
+ Summary: Utility package exposing helper modules.
4
+ """
src_code_for_reproducibility/utils/gather_training_stats.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/gather_training_stats.py
3
+ Summary: Aggregates training statistics from rollouts and exports artifacts.
4
+ """
5
+
6
+ import copy
7
+ import csv
8
+ import gc
9
+ import json
10
+ import logging
11
+ import os
12
+ import pickle
13
+ import random
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ from datetime import datetime
19
+ from statistics import mean
20
+ from typing import Any, Dict
21
+
22
+ import hydra
23
+ import matplotlib.pyplot as plt
24
+ import numpy as np
25
+ import pandas as pd
26
+ import torch
27
+ from omegaconf import OmegaConf
28
+
29
+ from mllm.training.tally_metrics import Tally
30
+ from mllm.utils.stat_pack import StatPack
31
+
32
+
33
+ def get_from_nested_dict(dictio: dict, path: list[str]):
34
+ for sp in path[:-1]:
35
+ dictio = dictio[sp]
36
+ return dictio.get(path[-1])
37
+
38
+
39
+ def set_at_path(dictio: dict, path: list[str], value):
40
+ for sp in path[:-1]:
41
+ if sp not in dictio:
42
+ dictio[sp] = {}
43
+ dictio = dictio[sp]
44
+ dictio[path[-1]] = value
45
+
46
+
47
+ def produce_tabular_render(inpath: str, outpath: str = None):
48
+ """
49
+ Convert a JSON metrics dump into per-rollout CSV tables for easier inspection.
50
+ """
51
+ with open(inpath, "r") as f:
52
+ data = json.load(f)
53
+ rollout_paths = data.keys()
54
+ for rollout_path in rollout_paths:
55
+ if outpath is None:
56
+ m_path = rollout_path.replace("/", "|")
57
+ m_path = m_path.replace(".json", "")
58
+ m_path = (
59
+ os.path.split(inpath)[0]
60
+ + "/contextualized_tabular_renders/"
61
+ + m_path
62
+ + "_tabular_render.render.csv"
63
+ )
64
+ # import pdb; pdb.set_trace()
65
+ os.makedirs(os.path.split(m_path)[0], exist_ok=True)
66
+ metrics = data[rollout_path]
67
+ d = {k: [] for k in metrics[0].keys()}
68
+ for m in metrics:
69
+ for k, v in m.items():
70
+ d[k].append(v)
71
+ d = pd.DataFrame(d)
72
+ d.to_csv(m_path)
73
+
74
+
75
+ def get_metric_paths(data: list[dict]):
76
+ d = data[0]
77
+ paths = []
78
+
79
+ def traverse_dict(d, current_path=[]):
80
+ for key, value in d.items():
81
+ new_path = current_path + [key]
82
+ if isinstance(value, dict):
83
+ traverse_dict(value, new_path)
84
+ else:
85
+ paths.append(new_path)
86
+
87
+ traverse_dict(d)
88
+ return paths
89
+
90
+
91
+ def print_metric_paths(data: list[dict]):
92
+ paths = get_metric_paths(data)
93
+ for p in paths:
94
+ print(p)
95
+
96
+
97
+ def get_metric_iteration_list(data: list[dict], metric_path: list[str]):
98
+ if isinstance(metric_path, str):
99
+ metric_path = [metric_path]
100
+ sgl = []
101
+ for d in data:
102
+ sgl.append(get_from_nested_dict(d, metric_path))
103
+ return sgl
104
+
105
+
106
+ def to_1d_numeric(x):
107
+ """Return a 1-D float array (or None if not numeric). Accepts scalars, numpy arrays, or nested list/tuple of them."""
108
+ if x is None:
109
+ return None
110
+ if isinstance(x, (int, float, np.number)):
111
+ return np.array([float(x)], dtype=float)
112
+ if isinstance(x, np.ndarray):
113
+ try:
114
+ return x.astype(float).ravel()
115
+ except Exception:
116
+ return None
117
+ if isinstance(x, (list, tuple)):
118
+ parts = []
119
+ for e in x:
120
+ arr = to_1d_numeric(e)
121
+ if arr is not None and arr.size > 0:
122
+ parts.append(arr)
123
+ if parts:
124
+ return np.concatenate(parts)
125
+ return None
126
+ return None
127
+
128
+
129
+ def get_single_metric_vector(data, metric_path, iterations=None):
130
+ if isinstance(metric_path, str):
131
+ metric_path = [metric_path]
132
+ if iterations == None:
133
+ iterations = len(data)
134
+ vecs = []
135
+ for d in data:
136
+ ar = get_from_nested_dict(d, metric_path)
137
+ arr = to_1d_numeric(ar)
138
+ if arr is not None:
139
+ vecs.append(arr)
140
+
141
+ return np.concatenate(vecs) if vecs else np.empty(0, dtype=float)
142
+
143
+
144
+ def _load_metrics_file(file_path: str):
145
+ if not (file_path.endswith(".tally.pkl") or file_path.endswith(".pkl")):
146
+ raise ValueError("Only *.tally.pkl files are supported.")
147
+ import pickle
148
+
149
+ with open(file_path, "rb") as f:
150
+ tree = pickle.load(f)
151
+ return tree
152
+
153
+
154
+ def get_leaf_items(array_tally: dict, prefix: list[str] = None):
155
+ if prefix is None:
156
+ prefix = []
157
+ for key, value in array_tally.items():
158
+ next_prefix = prefix + [str(key)]
159
+ if isinstance(value, dict):
160
+ yield from get_leaf_items(value, next_prefix)
161
+ else:
162
+ yield next_prefix, value
163
+
164
+
165
+ def _sanitize_filename_part(part: str) -> str:
166
+ s = part.replace("/", "|")
167
+ s = s.replace(" ", "_")
168
+ return s
169
+
170
+
171
+ def render_rt_tally_pkl_to_csvs(pkl_path: str, outdir: str):
172
+ """
173
+ This method takes care of tokenwise logging.
174
+ """
175
+ with open(pkl_path, "rb") as f:
176
+ payload = pickle.load(f)
177
+ # Backward compatibility: older tallies stored the dict directly
178
+ if isinstance(payload, dict) and "array_tally" in payload:
179
+ array_tally = payload.get("array_tally", {})
180
+ else:
181
+ array_tally = payload
182
+
183
+ os.makedirs(outdir, exist_ok=True)
184
+ trainer_id = os.path.basename(pkl_path).replace(".rt_tally.pkl", "")
185
+ for path_list, rollout_tally_items in get_leaf_items(array_tally):
186
+ # Create file and initiate writer
187
+ path_part = ".".join(_sanitize_filename_part(p) for p in path_list)
188
+ filename = f"{trainer_id}__{path_part}.render.csv"
189
+ out_path = os.path.join(outdir, filename)
190
+
191
+ # Write metric rows to CSV
192
+ with open(out_path, "w", newline="") as f:
193
+ writer = csv.writer(f)
194
+
195
+ # Write header row - need to determine metric column count from first rollout_tally_item
196
+ first_item = rollout_tally_items[0]
197
+ metric_cols = (
198
+ first_item.metric_matrix.shape[1]
199
+ if first_item.metric_matrix.ndim > 1
200
+ else 1
201
+ )
202
+ header = ["agent_id", "crn_id", "rollout_id"] + [
203
+ f"t_{i}" for i in range(metric_cols)
204
+ ]
205
+ writer.writerow(header)
206
+
207
+ for rollout_tally_item in rollout_tally_items:
208
+ crn_ids = rollout_tally_item.crn_ids
209
+ rollout_ids = rollout_tally_item.rollout_ids
210
+ agent_ids = rollout_tally_item.agent_ids
211
+ metric_matrix = rollout_tally_item.metric_matrix
212
+ for i in range(metric_matrix.shape[0]):
213
+ row_vals = metric_matrix[i].reshape(-1)
214
+ # Convert row_vals to a list to avoid numpy concatenation issues
215
+ row_vals = (
216
+ row_vals.tolist()
217
+ if hasattr(row_vals, "tolist")
218
+ else list(row_vals)
219
+ )
220
+ row_prefix = [
221
+ agent_ids[i],
222
+ crn_ids[i],
223
+ rollout_ids[i],
224
+ ]
225
+ writer.writerow(row_prefix + row_vals)
226
+
227
+
228
+ def tally_to_stat_pack(tally: Dict[str, Any]):
229
+ stat_pack = StatPack()
230
+ if "array_tally" in tally:
231
+ tally = tally["array_tally"]
232
+
233
+ # backward compatibility: will remove later, flatten keys in tally
234
+ def get_from_nested_dict(dictio: dict, path: list[str]):
235
+ for sp in path[:-1]:
236
+ dictio = dictio[sp]
237
+ return dictio.get(path[-1])
238
+
239
+ def get_metric_paths(tally: dict):
240
+ paths = []
241
+
242
+ def traverse_dict(tally, current_path=[]):
243
+ for key, value in tally.items():
244
+ new_path = current_path + [key]
245
+ if isinstance(value, dict):
246
+ traverse_dict(value, new_path)
247
+ else:
248
+ paths.append(new_path)
249
+
250
+ traverse_dict(tally)
251
+ return paths
252
+
253
+ paths = get_metric_paths(tally)
254
+ modified_tally = {}
255
+ for p in paths:
256
+ val = get_from_nested_dict(tally, p)
257
+ modified_tally["_".join(p)] = np.mean(val)
258
+ del tally
259
+ tally = modified_tally
260
+ for key, value in tally.items():
261
+ stat_pack.add_stat(key, value)
262
+ return stat_pack
src_code_for_reproducibility/utils/get_stochastic_game_lengths.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/get_stochastic_game_lengths.py
3
+ Summary: Computes distributions over stochastic game lengths.
4
+ """
5
+
6
+ import numpy as np
7
+
8
+
9
+ def get_stochastic_game_lengths(
10
+ max_length, nb_games, continuation_prob, same_length_batch=False
11
+ ):
12
+ """
13
+ Generates stochastic game lengths based on a geometric distribution.
14
+
15
+ Args:
16
+ max_length (int): The maximum length a game can have.
17
+ nb_games (int): The number of games to generate lengths for.
18
+ continuation_prob (float): The probability of the game continuing after each round.
19
+ same_length_batch (bool): If True, all games will have the same length.
20
+
21
+ Returns:
22
+ Array: An array of game lengths.
23
+ """
24
+ if continuation_prob == 1:
25
+ return [max_length] * nb_games
26
+ if same_length_batch:
27
+ length = np.random.geometric(1 - continuation_prob, 1)
28
+ game_lengths = np.repeat(length, nb_games)
29
+ else:
30
+ game_lengths = np.random.geometric(1 - continuation_prob, nb_games)
31
+
32
+ game_lengths = np.where(game_lengths > max_length, max_length, game_lengths)
33
+ return game_lengths.tolist()
src_code_for_reproducibility/utils/rollout_tree_chat_htmls.py ADDED
@@ -0,0 +1,1597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/rollout_tree_chat_htmls.py
3
+ Summary: Renders rollout tree chat transcripts into HTML artifacts.
4
+ """
5
+
6
+ from pathlib import Path
7
+ from typing import List
8
+
9
+ from mllm.utils.rollout_tree_gather_utils import *
10
+
11
+
12
+ def html_from_chat_turns(chat_turns: List[ChatTurnLog]) -> str:
13
+ """
14
+ Render chat turns as a single, wrapping sequence of messages in time order.
15
+ Keep badge and message bubble styles, include time on every badge and
16
+ include rewards on assistant badges. Each message is individually
17
+ hide/show by click; when hidden, only the badge remains and "(...)" is
18
+ shown inline (not inside a bubble).
19
+ """
20
+ import html
21
+ import re as _re
22
+
23
+ # Prepare ordering: sort by (time_step, original_index) to keep stable order within same step
24
+ indexed_turns = list(enumerate(chat_turns))
25
+ indexed_turns.sort(key=lambda t: (t[1].time_step, t[0]))
26
+
27
+ # Get unique agent IDs and sort alphabetically for consistent assignment
28
+ # Agent with alphabetically lower name gets agent-0 (left, green)
29
+ # Agent with alphabetically higher name gets agent-1 (right, orange)
30
+ unique_agent_ids = sorted(
31
+ set(turn.agent_id for turn in chat_turns if turn.role == "assistant")
32
+ )
33
+ agent_id_to_index = {aid: idx for idx, aid in enumerate(unique_agent_ids)}
34
+
35
+ # CSS styles (simplified layout; no time-step or agent-column backgrounds)
36
+ css = """
37
+ <style>
38
+ :root {
39
+ --font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
40
+ --bg: #ffffff;
41
+ --text: #1c0b00;
42
+ --muted-text: #2C3E50;
43
+ --accent-muted: #BDC3C7;
44
+ --accent-muted-2: #D0D7DE;
45
+ --panel-bg: #F8FAFC;
46
+ --reward-color: #3a2e00; /* dark text for reward pill */
47
+ --font-size: 14px;
48
+ --border-width: 2px;
49
+ --corner-radius: 6px;
50
+ --pill-radius-left: 999px 0 0 999px;
51
+ --pill-radius-right: 0 999px 999px 0;
52
+ --inset-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
53
+
54
+ /* Chat View Colors */
55
+ --agent-0-bg: #dcf8c6;
56
+ --agent-0-border: #0eb224;
57
+ --agent-1-bg: #ffe4cc;
58
+ --agent-1-border: #ef8323;
59
+ --user-bg: #f5f5f5;
60
+ --chat-bg: #ffffff;
61
+ }
62
+ body {
63
+ font-family: var(--font-family);
64
+ margin: 12px;
65
+ background-color: var(--bg);
66
+ color: var(--text);
67
+ font-size: var(--font-size);
68
+ line-height: 1.5;
69
+ }
70
+
71
+ /* Chat View Styles */
72
+ #flow-chat {
73
+ max-width: 900px;
74
+ margin: 0 auto;
75
+ background: var(--chat-bg);
76
+ padding: 12px 16px 12px 8px;
77
+ border-radius: 8px;
78
+ }
79
+
80
+ .simultaneous-messages {
81
+ display: flex !important;
82
+ flex-direction: row !important;
83
+ flex-wrap: nowrap !important;
84
+ gap: 8px;
85
+ margin-bottom: 4px;
86
+ align-items: flex-start;
87
+ width: 100%;
88
+ overflow: hidden;
89
+ box-sizing: border-box;
90
+ }
91
+
92
+ .simultaneous-messages .chat-message {
93
+ flex: 1 1 0 !important;
94
+ margin-bottom: 0 !important;
95
+ display: flex !important;
96
+ flex-direction: row !important;
97
+ align-items: flex-start !important;
98
+ margin-left: 0 !important;
99
+ min-width: 0 !important;
100
+ max-width: 50% !important;
101
+ gap: 0 !important;
102
+ overflow: hidden !important;
103
+ }
104
+
105
+ .simultaneous-messages .chat-message-content {
106
+ max-width: 100% !important;
107
+ width: 100%;
108
+ align-items: flex-start !important;
109
+ margin-left: 0 !important;
110
+ overflow: hidden !important;
111
+ }
112
+
113
+ .simultaneous-messages .chat-message.agent-0 {
114
+ justify-content: flex-start !important;
115
+ }
116
+
117
+ .simultaneous-messages .chat-message.agent-1 {
118
+ justify-content: flex-end !important;
119
+ }
120
+
121
+ .simultaneous-messages .chat-message.agent-0 .chat-message-content {
122
+ margin-left: 0 !important;
123
+ align-items: flex-start !important;
124
+ }
125
+
126
+ .simultaneous-messages .chat-message.agent-1 .chat-message-content {
127
+ margin-left: auto !important;
128
+ margin-right: 0 !important;
129
+ align-items: flex-end !important;
130
+ }
131
+
132
+ .simultaneous-messages .chat-bubble {
133
+ max-width: 100%;
134
+ word-break: break-word;
135
+ overflow-wrap: break-word;
136
+ box-sizing: border-box;
137
+ }
138
+
139
+ .simultaneous-messages .chat-message.agent-0 .chat-bubble {
140
+ border-radius: 10px;
141
+ }
142
+
143
+ .simultaneous-messages .chat-message.agent-1 .chat-bubble {
144
+ border-radius: 10px;
145
+ }
146
+
147
+ .simultaneous-messages .chat-message.agent-0 .chat-header {
148
+ justify-content: flex-start;
149
+ flex-shrink: 0;
150
+ }
151
+
152
+ .simultaneous-messages .chat-message.agent-1 .chat-header {
153
+ justify-content: flex-end;
154
+ flex-shrink: 0;
155
+ }
156
+
157
+ .simultaneous-messages .chat-reasoning {
158
+ max-width: 100%;
159
+ overflow-wrap: break-word;
160
+ }
161
+
162
+ /* Styling for user prompts in simultaneous-messages */
163
+ .simultaneous-messages .chat-message.role-user {
164
+ flex: 1 1 0 !important;
165
+ margin-bottom: 0 !important;
166
+ display: flex !important;
167
+ opacity: 0.7;
168
+ cursor: pointer;
169
+ }
170
+
171
+ .simultaneous-messages .chat-message.role-user:hover {
172
+ opacity: 1;
173
+ }
174
+
175
+ .simultaneous-messages .chat-message.role-user.collapsed .chat-bubble {
176
+ display: none;
177
+ }
178
+
179
+ .simultaneous-messages .chat-message.role-user.collapsed .chat-header::after {
180
+ content: ' (collapsed)';
181
+ font-weight: normal;
182
+ font-style: italic;
183
+ color: #999;
184
+ font-size: 0.9em;
185
+ }
186
+
187
+ .simultaneous-messages .chat-message.role-user.agent-0 {
188
+ justify-content: flex-start !important;
189
+ }
190
+
191
+ .simultaneous-messages .chat-message.role-user.agent-1 {
192
+ justify-content: flex-end !important;
193
+ }
194
+
195
+ .simultaneous-messages .chat-message.role-user.agent-0 .chat-message-content {
196
+ margin-left: 0 !important;
197
+ align-items: flex-start !important;
198
+ }
199
+
200
+ .simultaneous-messages .chat-message.role-user.agent-1 .chat-message-content {
201
+ margin-left: auto !important;
202
+ margin-right: 0 !important;
203
+ align-items: flex-end !important;
204
+ }
205
+
206
+ /* Styling for split-agent-context when wrapped */
207
+ .simultaneous-messages .split-agent-context {
208
+ width: 100%;
209
+ display: flex !important;
210
+ }
211
+
212
+ .chat-message {
213
+ display: flex;
214
+ margin-bottom: 2px;
215
+ align-items: flex-end;
216
+ gap: 6px;
217
+ position: relative;
218
+ margin-left: 36px;
219
+ }
220
+
221
+ .chat-message.agent-0 {
222
+ margin-left: 0;
223
+ }
224
+
225
+ .chat-message.agent-1 {
226
+ margin-left: 0;
227
+ }
228
+
229
+ .chat-message.agent-0::before {
230
+ left: 0;
231
+ }
232
+
233
+ .chat-message.agent-1::before {
234
+ left: 0;
235
+ }
236
+
237
+ .chat-message.role-user {
238
+ opacity: 0.7;
239
+ cursor: pointer;
240
+ }
241
+
242
+ .chat-message.role-user.collapsed .chat-bubble {
243
+ display: none;
244
+ }
245
+
246
+ .chat-message.role-user.collapsed .chat-header::after {
247
+ content: ' (collapsed)';
248
+ font-weight: normal;
249
+ font-style: italic;
250
+ color: #999;
251
+ font-size: 0.9em;
252
+ }
253
+
254
+ .chat-message.role-user:hover {
255
+ opacity: 1;
256
+ }
257
+
258
+ .chat-message::before {
259
+ content: '';
260
+ position: absolute;
261
+ left: -36px;
262
+ top: 0;
263
+ bottom: 0;
264
+ width: 36px;
265
+ pointer-events: auto;
266
+ }
267
+
268
+ .merge-btn {
269
+ position: absolute;
270
+ left: -30px;
271
+ top: 50%;
272
+ transform: translateY(-50%);
273
+ width: 26px;
274
+ height: 26px;
275
+ border-radius: 4px;
276
+ border: 1.5px solid var(--accent-muted);
277
+ background: white;
278
+ cursor: pointer;
279
+ font-size: var(--font-size);
280
+ opacity: 0;
281
+ display: flex;
282
+ align-items: center;
283
+ justify-content: center;
284
+ transition: opacity 0.2s ease, transform 0.1s ease;
285
+ padding: 0;
286
+ line-height: 1;
287
+ z-index: 10;
288
+ }
289
+
290
+ .chat-message:hover .merge-btn,
291
+ .merge-btn:hover {
292
+ opacity: 1;
293
+ }
294
+
295
+ .merge-btn:hover {
296
+ background: var(--panel-bg);
297
+ border-color: var(--accent-muted-2);
298
+ transform: translateY(-50%) scale(1.15);
299
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
300
+ }
301
+
302
+ .merge-btn:active {
303
+ transform: translateY(-50%) scale(0.95);
304
+ }
305
+
306
+ .chat-message.agent-0 .merge-btn {
307
+ left: -30px;
308
+ }
309
+
310
+ .chat-message.agent-1 .merge-btn {
311
+ left: -30px;
312
+ }
313
+
314
+ .chat-message.role-user .merge-btn {
315
+ display: none !important;
316
+ }
317
+
318
+ .simultaneous-messages .merge-btn {
319
+ opacity: 0 !important;
320
+ pointer-events: none;
321
+ }
322
+
323
+ .simultaneous-messages {
324
+ padding: 6px 0 6px 0 !important;
325
+ margin-left: 0 !important;
326
+ margin-right: 0 !important;
327
+ position: relative !important;
328
+ background: transparent !important;
329
+ border-radius: 0 !important;
330
+ box-sizing: border-box !important;
331
+ overflow: visible !important;
332
+ max-width: 100% !important;
333
+ border: none !important;
334
+ transition: padding 0.2s ease !important;
335
+ }
336
+
337
+ .simultaneous-messages:hover {
338
+ padding-top: 40px !important;
339
+ }
340
+
341
+ .simultaneous-messages::before {
342
+ content: '⇅ Merged';
343
+ position: absolute;
344
+ left: 0 !important;
345
+ top: 8px !important;
346
+ font-size: var(--font-size);
347
+ font-weight: 500;
348
+ color: #888;
349
+ pointer-events: none;
350
+ opacity: 0;
351
+ transition: opacity 0.2s ease;
352
+ }
353
+
354
+ .simultaneous-messages:hover::before {
355
+ opacity: 1;
356
+ }
357
+
358
+ .unmerge-btn {
359
+ position: absolute !important;
360
+ right: 0 !important;
361
+ top: 6px !important;
362
+ width: 36px !important;
363
+ height: 28px !important;
364
+ border-radius: 5px !important;
365
+ border: 2px solid #d63031 !important;
366
+ background: white !important;
367
+ cursor: pointer !important;
368
+ font-size: var(--font-size) !important;
369
+ font-weight: bold !important;
370
+ color: #d63031 !important;
371
+ display: flex !important;
372
+ align-items: center !important;
373
+ justify-content: center !important;
374
+ transition: all 0.2s ease !important;
375
+ padding: 0 !important;
376
+ line-height: 1 !important;
377
+ z-index: 1000 !important;
378
+ flex: none !important;
379
+ pointer-events: auto !important;
380
+ box-shadow: 0 2px 6px rgba(214, 48, 49, 0.3) !important;
381
+ opacity: 0 !important;
382
+ }
383
+
384
+ .simultaneous-messages:hover .unmerge-btn {
385
+ opacity: 1 !important;
386
+ }
387
+
388
+ .unmerge-btn:hover {
389
+ background: #ffe5e5 !important;
390
+ border-color: #b71c1c !important;
391
+ transform: scale(1.1) !important;
392
+ box-shadow: 0 3px 8px rgba(214, 48, 49, 0.4) !important;
393
+ }
394
+
395
+ .unmerge-btn:active {
396
+ transform: scale(0.95) !important;
397
+ background: #ffcccc !important;
398
+ }
399
+
400
+ .chat-message-content {
401
+ max-width: 72%;
402
+ display: flex;
403
+ flex-direction: column;
404
+ gap: 2px;
405
+ }
406
+
407
+ .chat-message.agent-0 .chat-message-content {
408
+ align-items: flex-start;
409
+ }
410
+
411
+ .chat-message.agent-1 .chat-message-content {
412
+ align-items: flex-end;
413
+ margin-left: auto;
414
+ }
415
+
416
+ .chat-bubble {
417
+ padding: 6px 10px;
418
+ border-radius: 10px;
419
+ word-wrap: break-word;
420
+ position: relative;
421
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
422
+ line-height: 1.4;
423
+ }
424
+
425
+ .chat-message.agent-0 .chat-bubble {
426
+ background: var(--agent-0-bg);
427
+ border: 2px solid var(--agent-0-border);
428
+ border-radius: 10px 10px 10px 2px;
429
+ }
430
+
431
+ .chat-message.agent-1 .chat-bubble {
432
+ background: var(--agent-1-bg);
433
+ border: 2px solid var(--agent-1-border);
434
+ border-radius: 10px 10px 2px 10px;
435
+ }
436
+
437
+ .chat-message.role-user .chat-bubble {
438
+ background: var(--user-bg);
439
+ border: 2px solid #d0d0d0;
440
+ }
441
+
442
+ .chat-header {
443
+ display: flex;
444
+ align-items: center;
445
+ gap: 4px;
446
+ margin-bottom: 2px;
447
+ font-size: var(--font-size);
448
+ font-weight: 600;
449
+ line-height: 1.2;
450
+ }
451
+
452
+ .chat-message.agent-0 .chat-header {
453
+ color: var(--agent-0-border);
454
+ }
455
+
456
+ .chat-message.agent-1 .chat-header {
457
+ color: var(--agent-1-border);
458
+ }
459
+
460
+ .chat-timestamp {
461
+ font-size: var(--font-size);
462
+ color: var(--muted-text);
463
+ margin-top: 1px;
464
+ opacity: 0.75;
465
+ }
466
+
467
+ .chat-reward {
468
+ display: inline-flex;
469
+ align-items: center;
470
+ background: linear-gradient(90deg, #fffdf2 0%, #ffffff 75%);
471
+ color: #000000;
472
+ font-weight: 600;
473
+ font-size: var(--font-size);
474
+ padding: 1px 5px;
475
+ border-radius: 3px;
476
+ border: 1px solid #f4e6a8;
477
+ margin-left: 4px;
478
+ line-height: 1.3;
479
+ }
480
+
481
+ .chat-reasoning {
482
+ font-size: var(--font-size);
483
+ font-style: italic;
484
+ color: #555;
485
+ margin-bottom: 2px;
486
+ padding: 4px 8px;
487
+ background: rgba(0, 0, 0, 0.03);
488
+ border-radius: 5px;
489
+ cursor: pointer;
490
+ line-height: 1.3;
491
+ }
492
+
493
+ .chat-reasoning.collapsed .reasoning-text {
494
+ display: none;
495
+ }
496
+
497
+ .chat-reasoning.collapsed::after {
498
+ content: ' (click to expand)';
499
+ color: #777;
500
+ }
501
+
502
+ .chat-group-divider {
503
+ display: flex;
504
+ align-items: center;
505
+ gap: 8px;
506
+ width: 100%;
507
+ margin: 8px 0 4px 0;
508
+ position: relative;
509
+ cursor: pointer;
510
+ user-select: none;
511
+ }
512
+
513
+ .chat-group-divider::before,
514
+ .chat-group-divider::after {
515
+ content: "";
516
+ flex: 1 1 auto;
517
+ height: 2px;
518
+ background: linear-gradient(90deg, rgba(224,230,235,0), var(--accent-muted-2) 30%, var(--accent-muted-2) 70%, rgba(224,230,235,0));
519
+ }
520
+
521
+ .chat-group-label {
522
+ display: inline-block;
523
+ background: white;
524
+ padding: 2px 12px;
525
+ border-radius: 999px;
526
+ font-size: var(--font-size);
527
+ font-weight: 700;
528
+ color: var(--muted-text);
529
+ border: 1.5px solid var(--accent-muted);
530
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
531
+ line-height: 1.4;
532
+ position: relative;
533
+ transition: background 0.2s ease;
534
+ }
535
+
536
+ .chat-group-divider:hover .chat-group-label {
537
+ background: var(--panel-bg);
538
+ }
539
+
540
+ .chat-group-label::before {
541
+ content: '▼ ';
542
+ font-size: 0.8em;
543
+ display: inline-block;
544
+ transition: transform 0.2s ease;
545
+ opacity: 0;
546
+ }
547
+
548
+ .chat-group-divider:hover .chat-group-label::before {
549
+ opacity: 1;
550
+ }
551
+
552
+ .chat-group-divider.collapsed .chat-group-label::before {
553
+ content: '▶ ';
554
+ opacity: 1;
555
+ }
556
+
557
+ .chat-group-divider.collapsed + * {
558
+ display: none !important;
559
+ }
560
+
561
+ /* Hide collapsed rounds in strong hide mode */
562
+ .strong-hide .chat-group-divider.collapsed {
563
+ display: none !important;
564
+ }
565
+
566
+ /* Chat view width control */
567
+ #flow-chat {
568
+ --chat-width: 900px;
569
+ max-width: var(--chat-width);
570
+ margin: 0 auto;
571
+ }
572
+
573
+ /* Hide user messages when toggle is on */
574
+ #flow-chat.hide-user-messages .chat-message.role-user {
575
+ display: none;
576
+ }
577
+
578
+ /* Hide rewards when hiding user messages */
579
+ #flow-chat.hide-user-messages .chat-reward {
580
+ display: none;
581
+ }
582
+
583
+ /* Round context annotations */
584
+ .round-context {
585
+ text-align: center;
586
+ margin: 4px auto;
587
+ max-width: 100%;
588
+ }
589
+
590
+ .round-context-edit {
591
+ min-height: 20px;
592
+ padding: 5px 10px;
593
+ border: 1.5px dashed var(--accent-muted);
594
+ border-radius: 6px;
595
+ background: #fafafa;
596
+ cursor: text;
597
+ transition: all 0.2s ease;
598
+ outline: none;
599
+ font-size: var(--font-size);
600
+ line-height: 1.3;
601
+ user-select: text;
602
+ -webkit-user-select: text;
603
+ -moz-user-select: text;
604
+ -ms-user-select: text;
605
+ }
606
+
607
+ .round-context-edit:focus {
608
+ border-style: solid;
609
+ border-color: var(--accent-muted-2);
610
+ background: #ffffff;
611
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
612
+ }
613
+
614
+ .round-context-edit:empty:before {
615
+ content: attr(data-placeholder);
616
+ color: #999;
617
+ font-style: italic;
618
+ }
619
+
620
+ .round-context-controls {
621
+ display: none;
622
+ justify-content: center;
623
+ gap: 4px;
624
+ margin-top: 4px;
625
+ flex-wrap: wrap;
626
+ }
627
+
628
+ .round-context-edit:focus + .round-context-controls,
629
+ .round-context-controls:hover,
630
+ .round-context:focus-within .round-context-controls {
631
+ display: flex;
632
+ }
633
+
634
+ .context-color-btn {
635
+ width: 22px;
636
+ height: 22px;
637
+ border-radius: 50%;
638
+ border: 1.5px solid #fff;
639
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
640
+ cursor: pointer;
641
+ transition: transform 0.1s ease;
642
+ }
643
+
644
+ .context-color-btn:hover {
645
+ transform: scale(1.15);
646
+ }
647
+
648
+ .context-color-btn:active {
649
+ transform: scale(0.95);
650
+ }
651
+
652
+ /* Split agent context boxes */
653
+ .split-agent-context {
654
+ display: flex;
655
+ gap: 6px;
656
+ margin: 4px auto;
657
+ max-width: 100%;
658
+ align-items: flex-start;
659
+ }
660
+
661
+ .agent-context-box {
662
+ flex: 1;
663
+ min-width: 0;
664
+ position: relative;
665
+ }
666
+
667
+ .agent-context-box .round-context-edit {
668
+ margin: 0;
669
+ border-radius: 6px;
670
+ padding: 4px 8px;
671
+ min-height: 18px;
672
+ }
673
+
674
+ .agent-context-box.agent-0 .round-context-edit {
675
+ border-color: var(--agent-0-border);
676
+ background: rgba(14, 178, 36, 0.03);
677
+ }
678
+
679
+ .agent-context-box.agent-1 .round-context-edit {
680
+ border-color: var(--agent-1-border);
681
+ background: rgba(239, 131, 35, 0.03);
682
+ }
683
+
684
+ .agent-context-box.agent-0 .round-context-edit:focus {
685
+ border-color: var(--agent-0-border);
686
+ box-shadow: 0 2px 8px rgba(14, 178, 36, 0.2);
687
+ background: rgba(14, 178, 36, 0.05);
688
+ }
689
+
690
+ .agent-context-box.agent-1 .round-context-edit:focus {
691
+ border-color: var(--agent-1-border);
692
+ box-shadow: 0 2px 8px rgba(239, 131, 35, 0.2);
693
+ background: rgba(239, 131, 35, 0.05);
694
+ }
695
+
696
+ .agent-context-box .round-context-edit::before {
697
+ font-weight: 700;
698
+ font-size: var(--font-size);
699
+ margin-right: 5px;
700
+ letter-spacing: 0.2px;
701
+ }
702
+
703
+ .agent-context-box.agent-0 .round-context-edit::before {
704
+ content: 'Agent 0 Prompt Summary:';
705
+ color: var(--agent-0-border);
706
+ }
707
+
708
+ .agent-context-box.agent-1 .round-context-edit::before {
709
+ content: 'Agent 1 Prompt Summary:';
710
+ color: var(--agent-1-border);
711
+ }
712
+
713
+ /* Empty context boxes will be hidden by JavaScript when strong hide is enabled */
714
+ .toolbar {
715
+ display: flex;
716
+ align-items: center;
717
+ gap: 8px;
718
+ margin-bottom: 0;
719
+ font-size: var(--font-size);
720
+ max-height: 0;
721
+ overflow: hidden;
722
+ opacity: 0;
723
+ pointer-events: none;
724
+ transition: max-height 0.2s ease, opacity 0.2s ease;
725
+ flex-wrap: wrap;
726
+ }
727
+ .toolbar-wrap { position: sticky; top: 0; z-index: 10; background: var(--bg); }
728
+ .toolbar-hotzone { height: 6px; }
729
+ .toolbar-wrap:hover .toolbar { max-height: 500px; opacity: 1; pointer-events: auto; margin-bottom: 12px; }
730
+ .toolbar * { pointer-events: auto !important; }
731
+ .toolbar input,
732
+ .toolbar select { z-index: 100 !important; position: relative; }
733
+ .toolbar input[type="number"],
734
+ .toolbar input[type="text"],
735
+ .toolbar select {
736
+ width: 72px;
737
+ padding: 2px 6px;
738
+ border: 1px solid var(--accent-muted);
739
+ border-radius: var(--corner-radius);
740
+ background: var(--bg);
741
+ user-select: text !important;
742
+ -webkit-user-select: text !important;
743
+ -moz-user-select: text !important;
744
+ -ms-user-select: text !important;
745
+ pointer-events: auto !important;
746
+ cursor: pointer !important;
747
+ }
748
+ .toolbar input[type="text"] {
749
+ cursor: text !important;
750
+ }
751
+ .toolbar input[type="text"]:focus,
752
+ .toolbar input[type="number"]:focus,
753
+ .toolbar select:focus {
754
+ outline: 2px solid #0066cc;
755
+ outline-offset: 1px;
756
+ }
757
+ .toolbar button {
758
+ padding: 4px 8px;
759
+ border: 1px solid var(--accent-muted);
760
+ background: var(--panel-bg);
761
+ border-radius: var(--corner-radius);
762
+ cursor: pointer;
763
+ }
764
+ .emoji-bw { filter: grayscale(100%); opacity: 0.95; font-size: var(--font-size); vertical-align: baseline; margin: 0; position: relative; top: -1px; line-height: 1; display: inline-block; }
765
+ </style>
766
+ """
767
+
768
+ # HTML structure
769
+ html_parts = [
770
+ "<!DOCTYPE html>",
771
+ "<html>",
772
+ "<head>",
773
+ "<meta charset='UTF-8'>",
774
+ "<title>Chat Turns</title>",
775
+ css,
776
+ "<script>\n"
777
+ "document.addEventListener('DOMContentLoaded', function() {\n"
778
+ " const chatFlow = document.getElementById('flow-chat');\n"
779
+ " let strongHideOn = false;\n"
780
+ " let hideUserMessages = false;\n"
781
+ " const hideUserBtn = document.getElementById('toggle-hide-user-messages');\n"
782
+ " const hideUserStateEl = document.getElementById('hide-user-state');\n"
783
+ " const widthControl = document.getElementById('chat-width-control');\n"
784
+ " const widthSlider = document.getElementById('chat-width-slider');\n"
785
+ " const widthValue = document.getElementById('chat-width-value');\n"
786
+ " const strongHideBtn = document.getElementById('toggle-strong-hide');\n"
787
+ " const strongHideStateEl = document.getElementById('strong-hide-state');\n"
788
+ " if (strongHideBtn) {\n"
789
+ " const setLabel = () => { if (strongHideStateEl) { strongHideStateEl.textContent = strongHideOn ? 'On' : 'Off'; } };\n"
790
+ " strongHideBtn.addEventListener('click', () => { strongHideOn = !strongHideOn; chatFlow.classList.toggle('strong-hide', strongHideOn); setLabel(); applyStrongHideToChat(); });\n"
791
+ " setLabel();\n"
792
+ " }\n"
793
+ " if (hideUserBtn && hideUserStateEl && chatFlow) {\n"
794
+ " const updateHideUser = () => { hideUserStateEl.textContent = hideUserMessages ? 'On' : 'Off'; };\n"
795
+ " hideUserBtn.addEventListener('click', () => {\n"
796
+ " hideUserMessages = !hideUserMessages;\n"
797
+ " chatFlow.classList.toggle('hide-user-messages', hideUserMessages);\n"
798
+ " updateHideUser();\n"
799
+ " });\n"
800
+ " updateHideUser();\n"
801
+ " }\n"
802
+ " if (widthSlider && widthValue && chatFlow) {\n"
803
+ " const savedWidth = localStorage.getItem('chat-view-width');\n"
804
+ " if (savedWidth) {\n"
805
+ " widthSlider.value = savedWidth;\n"
806
+ " chatFlow.style.setProperty('--chat-width', savedWidth + 'px');\n"
807
+ " widthValue.textContent = savedWidth + 'px';\n"
808
+ " }\n"
809
+ " widthSlider.addEventListener('input', (e) => {\n"
810
+ " const width = e.target.value;\n"
811
+ " chatFlow.style.setProperty('--chat-width', width + 'px');\n"
812
+ " widthValue.textContent = width + 'px';\n"
813
+ " localStorage.setItem('chat-view-width', width);\n"
814
+ " });\n"
815
+ " }\n"
816
+ " const fontFamilySelect = document.getElementById('font-family-select');\n"
817
+ " const fontSizeInput = document.getElementById('font-size-input');\n"
818
+ " if (fontFamilySelect) {\n"
819
+ " const savedFont = localStorage.getItem('render-font-family');\n"
820
+ " if (savedFont) {\n"
821
+ " fontFamilySelect.value = savedFont;\n"
822
+ " document.body.style.setProperty('--font-family', savedFont);\n"
823
+ " }\n"
824
+ " fontFamilySelect.addEventListener('change', (e) => {\n"
825
+ " const font = e.target.value;\n"
826
+ " document.body.style.setProperty('--font-family', font);\n"
827
+ " localStorage.setItem('render-font-family', font);\n"
828
+ " });\n"
829
+ " }\n"
830
+ " if (fontSizeInput) {\n"
831
+ " const savedSize = localStorage.getItem('render-font-size');\n"
832
+ " if (savedSize) {\n"
833
+ " fontSizeInput.value = savedSize;\n"
834
+ " document.body.style.setProperty('--font-size', savedSize + 'px');\n"
835
+ " }\n"
836
+ " fontSizeInput.addEventListener('input', (e) => {\n"
837
+ " const size = e.target.value;\n"
838
+ " document.body.style.setProperty('--font-size', size + 'px');\n"
839
+ " localStorage.setItem('render-font-size', size);\n"
840
+ " });\n"
841
+ " }\n"
842
+ " const agent0EmojiInput = document.getElementById('agent0-emoji-input');\n"
843
+ " const agent0NameInput = document.getElementById('agent0-name-input');\n"
844
+ " const agent1EmojiInput = document.getElementById('agent1-emoji-input');\n"
845
+ " const agent1NameInput = document.getElementById('agent1-name-input');\n"
846
+ " const applyAgentNamesBtn = document.getElementById('apply-agent-names');\n"
847
+ " function loadAgentNames() {\n"
848
+ " if (agent0EmojiInput && agent0NameInput && agent1EmojiInput && agent1NameInput) {\n"
849
+ " const savedAgent0Emoji = localStorage.getItem('agent0-emoji') || '🤖';\n"
850
+ " const savedAgent0Name = localStorage.getItem('agent0-name') || document.getElementById('agent0-name-input').placeholder;\n"
851
+ " const savedAgent1Emoji = localStorage.getItem('agent1-emoji') || '🤖';\n"
852
+ " const savedAgent1Name = localStorage.getItem('agent1-name') || document.getElementById('agent1-name-input').placeholder;\n"
853
+ " agent0EmojiInput.value = savedAgent0Emoji;\n"
854
+ " agent0NameInput.value = savedAgent0Name;\n"
855
+ " agent1EmojiInput.value = savedAgent1Emoji;\n"
856
+ " agent1NameInput.value = savedAgent1Name;\n"
857
+ " applyAgentNamesToDOM(savedAgent0Emoji, savedAgent0Name, savedAgent1Emoji, savedAgent1Name);\n"
858
+ " }\n"
859
+ " }\n"
860
+ " function applyAgentNamesToDOM(agent0Emoji, agent0Name, agent1Emoji, agent1Name) {\n"
861
+ " const agentMap = { '0': { name: agent0Name, emoji: agent0Emoji }, '1': { name: agent1Name, emoji: agent1Emoji } };\n"
862
+ " document.querySelectorAll('[data-agent-index]').forEach(el => {\n"
863
+ " const agentIndex = el.getAttribute('data-agent-index');\n"
864
+ " if (!agentMap[agentIndex]) return;\n"
865
+ " if (el.classList.contains('agent-name')) {\n"
866
+ " el.textContent = agentMap[agentIndex].name;\n"
867
+ " } else if (el.classList.contains('emoji-bw')) {\n"
868
+ " const currentEmoji = el.textContent.trim();\n"
869
+ " if (currentEmoji === '🤖' || currentEmoji === '👤') {\n"
870
+ " el.textContent = agentMap[agentIndex].emoji;\n"
871
+ " }\n"
872
+ " }\n"
873
+ " });\n"
874
+ " const style = document.createElement('style');\n"
875
+ " style.id = 'dynamic-agent-names-style';\n"
876
+ " const existingStyle = document.getElementById('dynamic-agent-names-style');\n"
877
+ " if (existingStyle) existingStyle.remove();\n"
878
+ " style.textContent = `\n"
879
+ " .agent-context-box.agent-0 .round-context-edit::before {\n"
880
+ " content: '${agent0Name} Prompt Summary:';\n"
881
+ " }\n"
882
+ " .agent-context-box.agent-1 .round-context-edit::before {\n"
883
+ " content: '${agent1Name} Prompt Summary:';\n"
884
+ " }\n"
885
+ " `;\n"
886
+ " document.head.appendChild(style);\n"
887
+ " }\n"
888
+ " if (applyAgentNamesBtn && agent0EmojiInput && agent0NameInput && agent1EmojiInput && agent1NameInput) {\n"
889
+ " [agent0EmojiInput, agent0NameInput, agent1EmojiInput, agent1NameInput].forEach(input => {\n"
890
+ " input.style.pointerEvents = 'auto';\n"
891
+ " if (input.tagName === 'INPUT') {\n"
892
+ " input.style.userSelect = 'text';\n"
893
+ " input.style.webkitUserSelect = 'text';\n"
894
+ " input.readOnly = false;\n"
895
+ " }\n"
896
+ " input.disabled = false;\n"
897
+ " const stopAll = (e) => { e.stopPropagation(); e.stopImmediatePropagation(); };\n"
898
+ " input.addEventListener('mousedown', stopAll, true);\n"
899
+ " input.addEventListener('mouseup', stopAll, true);\n"
900
+ " input.addEventListener('click', stopAll, true);\n"
901
+ " input.addEventListener('dblclick', stopAll, true);\n"
902
+ " input.addEventListener('focus', stopAll, true);\n"
903
+ " input.addEventListener('blur', stopAll, true);\n"
904
+ " input.addEventListener('paste', stopAll, true);\n"
905
+ " input.addEventListener('cut', stopAll, true);\n"
906
+ " input.addEventListener('copy', stopAll, true);\n"
907
+ " input.addEventListener('select', stopAll, true);\n"
908
+ " input.addEventListener('selectstart', stopAll, true);\n"
909
+ " input.addEventListener('keydown', stopAll, true);\n"
910
+ " input.addEventListener('keyup', stopAll, true);\n"
911
+ " input.addEventListener('keypress', stopAll, true);\n"
912
+ " input.addEventListener('input', stopAll, true);\n"
913
+ " input.addEventListener('change', stopAll, true);\n"
914
+ " input.addEventListener('contextmenu', stopAll, true);\n"
915
+ " });\n"
916
+ " const applyNames = () => {\n"
917
+ " const agent0Emoji = agent0EmojiInput.value || '🤖';\n"
918
+ " const agent0Name = agent0NameInput.value.trim() || agent0NameInput.placeholder;\n"
919
+ " const agent1Emoji = agent1EmojiInput.value || '🤖';\n"
920
+ " const agent1Name = agent1NameInput.value.trim() || agent1NameInput.placeholder;\n"
921
+ " localStorage.setItem('agent0-emoji', agent0Emoji);\n"
922
+ " localStorage.setItem('agent0-name', agent0Name);\n"
923
+ " localStorage.setItem('agent1-emoji', agent1Emoji);\n"
924
+ " localStorage.setItem('agent1-name', agent1Name);\n"
925
+ " applyAgentNamesToDOM(agent0Emoji, agent0Name, agent1Emoji, agent1Name);\n"
926
+ " };\n"
927
+ " applyAgentNamesBtn.addEventListener('click', applyNames);\n"
928
+ " [agent0NameInput, agent1NameInput].forEach(input => {\n"
929
+ " input.addEventListener('keydown', (e) => {\n"
930
+ " if (e.key === 'Enter') {\n"
931
+ " e.preventDefault();\n"
932
+ " e.stopPropagation();\n"
933
+ " e.stopImmediatePropagation();\n"
934
+ " applyNames();\n"
935
+ " }\n"
936
+ " }, true);\n"
937
+ " });\n"
938
+ " [agent0EmojiInput, agent1EmojiInput].forEach(select => {\n"
939
+ " select.addEventListener('change', applyNames);\n"
940
+ " });\n"
941
+ " }\n"
942
+ " loadAgentNames();\n"
943
+ " function setupRoundCollapse() {\n"
944
+ " document.addEventListener('click', function(e) {\n"
945
+ " if (e.target.closest('input, textarea, select, button, .round-context-edit, .toolbar')) { return; }\n"
946
+ " const divider = e.target.closest('.chat-group-divider, .group-divider');\n"
947
+ " if (!divider) return;\n"
948
+ " divider.classList.toggle('collapsed');\n"
949
+ " const isCollapsed = divider.classList.contains('collapsed');\n"
950
+ " let nextElement = divider.nextElementSibling;\n"
951
+ " while (nextElement) {\n"
952
+ " if (nextElement.classList.contains('chat-group-divider') || nextElement.classList.contains('group-divider')) {\n"
953
+ " break;\n"
954
+ " }\n"
955
+ " if (isCollapsed) {\n"
956
+ " if (!nextElement.dataset.originalDisplay) {\n"
957
+ " nextElement.dataset.originalDisplay = nextElement.style.display || getComputedStyle(nextElement).display;\n"
958
+ " }\n"
959
+ " nextElement.style.display = 'none';\n"
960
+ " } else {\n"
961
+ " if (nextElement.dataset.originalDisplay) {\n"
962
+ " const originalDisplay = nextElement.dataset.originalDisplay;\n"
963
+ " nextElement.style.display = originalDisplay === 'none' ? '' : originalDisplay;\n"
964
+ " if (nextElement.style.display === originalDisplay && originalDisplay !== 'none') {\n"
965
+ " nextElement.style.display = '';\n"
966
+ " }\n"
967
+ " delete nextElement.dataset.originalDisplay;\n"
968
+ " } else {\n"
969
+ " nextElement.style.display = '';\n"
970
+ " }\n"
971
+ " }\n"
972
+ " nextElement = nextElement.nextElementSibling;\n"
973
+ " }\n"
974
+ " e.stopPropagation();\n"
975
+ " });\n"
976
+ " }\n"
977
+ " setupRoundCollapse();\n"
978
+ " const strongHideBtnChat = document.getElementById('toggle-strong-hide');\n"
979
+ " function applyStrongHideToChat() {\n"
980
+ " if (!chatFlow) return;\n"
981
+ " chatFlow.classList.toggle('strong-hide', strongHideOn);\n"
982
+ " const contextEdits = chatFlow.querySelectorAll('.round-context-edit');\n"
983
+ " contextEdits.forEach(edit => {\n"
984
+ " const parent = edit.closest('.round-context, .agent-context-box, .split-agent-context');\n"
985
+ " if (parent) {\n"
986
+ " if (strongHideOn && edit.textContent.trim() === '') {\n"
987
+ " parent.style.display = 'none';\n"
988
+ " } else {\n"
989
+ " parent.style.display = '';\n"
990
+ " }\n"
991
+ " }\n"
992
+ " });\n"
993
+ " const splitContexts = chatFlow.querySelectorAll('.split-agent-context');\n"
994
+ " splitContexts.forEach(split => {\n"
995
+ " if (strongHideOn) {\n"
996
+ " const boxes = split.querySelectorAll('.agent-context-box');\n"
997
+ " const allEmpty = Array.from(boxes).every(box => {\n"
998
+ " const edit = box.querySelector('.round-context-edit');\n"
999
+ " return edit && edit.textContent.trim() === '';\n"
1000
+ " });\n"
1001
+ " if (allEmpty) split.style.display = 'none';\n"
1002
+ " }\n"
1003
+ " });\n"
1004
+ " }\n"
1005
+ " if (strongHideBtnChat && chatFlow) {\n"
1006
+ " strongHideBtnChat.addEventListener('click', () => {\n"
1007
+ " setTimeout(() => applyStrongHideToChat(), 0);\n"
1008
+ " });\n"
1009
+ " }\n"
1010
+ " document.addEventListener('click', function(e) {\n"
1011
+ " if (e.target.closest('input, textarea, select, .round-context-edit, .toolbar')) { return; }\n"
1012
+ " const chatReasoning = e.target.closest('.chat-reasoning');\n"
1013
+ " if (chatReasoning) {\n"
1014
+ " chatReasoning.classList.toggle('collapsed');\n"
1015
+ " return;\n"
1016
+ " }\n"
1017
+ " const userMessage = e.target.closest('.chat-message.role-user');\n"
1018
+ " if (userMessage && !e.target.closest('.merge-btn, .unmerge-btn')) {\n"
1019
+ " userMessage.classList.toggle('collapsed');\n"
1020
+ " }\n"
1021
+ " });\n"
1022
+ " function applyColorToSelection(color, element) {\n"
1023
+ " const selection = window.getSelection();\n"
1024
+ " if (!selection.rangeCount) return false;\n"
1025
+ " const range = selection.getRangeAt(0);\n"
1026
+ " if (!element.contains(range.commonAncestorContainer)) return false;\n"
1027
+ " const selectedText = range.toString();\n"
1028
+ " if (!selectedText) return false;\n"
1029
+ " if (color === 'default') {\n"
1030
+ " // Remove styling - just extract the text content\n"
1031
+ " const textNode = document.createTextNode(selectedText);\n"
1032
+ " range.deleteContents();\n"
1033
+ " range.insertNode(textNode);\n"
1034
+ " } else {\n"
1035
+ " const span = document.createElement('span');\n"
1036
+ " span.style.color = color;\n"
1037
+ " span.style.fontWeight = '600';\n"
1038
+ " try {\n"
1039
+ " range.surroundContents(span);\n"
1040
+ " } catch (e) {\n"
1041
+ " const contents = range.extractContents();\n"
1042
+ " span.appendChild(contents);\n"
1043
+ " range.insertNode(span);\n"
1044
+ " }\n"
1045
+ " }\n"
1046
+ " return true;\n"
1047
+ " }\n"
1048
+ " let lastFocusedContextEdit = null;\n"
1049
+ " document.addEventListener('focusin', function(e) {\n"
1050
+ " if (e.target.classList.contains('round-context-edit')) {\n"
1051
+ " lastFocusedContextEdit = e.target;\n"
1052
+ " }\n"
1053
+ " });\n"
1054
+ " document.addEventListener('mousedown', function(e) {\n"
1055
+ " if (e.target.classList.contains('context-color-btn')) {\n"
1056
+ " e.preventDefault();\n"
1057
+ " }\n"
1058
+ " });\n"
1059
+ " document.addEventListener('click', function(e) {\n"
1060
+ " if (e.target.closest('input:not(.round-context-edit), textarea, select') && !e.target.classList.contains('context-color-btn')) { return; }\n"
1061
+ " if (e.target.classList.contains('context-color-btn')) {\n"
1062
+ " e.preventDefault();\n"
1063
+ " const color = e.target.dataset.color;\n"
1064
+ " const controls = e.target.closest('.round-context-controls');\n"
1065
+ " const contextEdit = controls ? controls.previousElementSibling : null;\n"
1066
+ " if (contextEdit && contextEdit.classList.contains('round-context-edit')) {\n"
1067
+ " contextEdit.focus();\n"
1068
+ " const selection = window.getSelection();\n"
1069
+ " if (selection.rangeCount > 0 && selection.toString().length > 0 && contextEdit.contains(selection.anchorNode)) {\n"
1070
+ " if (applyColorToSelection(color, contextEdit)) {\n"
1071
+ " const key = contextEdit.dataset.contextKey;\n"
1072
+ " localStorage.setItem(key, contextEdit.innerHTML);\n"
1073
+ " }\n"
1074
+ " } else {\n"
1075
+ " try {\n"
1076
+ " if (color !== 'default') {\n"
1077
+ " document.execCommand('styleWithCSS', false, true);\n"
1078
+ " document.execCommand('foreColor', false, color);\n"
1079
+ " }\n"
1080
+ " const key = contextEdit.dataset.contextKey;\n"
1081
+ " setTimeout(() => localStorage.setItem(key, contextEdit.innerHTML), 10);\n"
1082
+ " } catch (e) {\n"
1083
+ " console.log('Color command failed:', e);\n"
1084
+ " }\n"
1085
+ " }\n"
1086
+ " }\n"
1087
+ " }\n"
1088
+ " });\n"
1089
+ " const contextEdits = document.querySelectorAll('.round-context-edit');\n"
1090
+ " contextEdits.forEach(edit => {\n"
1091
+ " edit.addEventListener('input', function() {\n"
1092
+ " const key = this.dataset.contextKey;\n"
1093
+ " localStorage.setItem(key, this.innerHTML);\n"
1094
+ " });\n"
1095
+ " const key = edit.dataset.contextKey;\n"
1096
+ " const saved = localStorage.getItem(key);\n"
1097
+ " if (saved) {\n"
1098
+ " edit.innerHTML = saved;\n"
1099
+ " }\n"
1100
+ " });\n"
1101
+ " document.addEventListener('click', function(e) {\n"
1102
+ " if (e.target.closest('input, textarea, select, .round-context-edit') && !e.target.classList.contains('merge-btn') && !e.target.classList.contains('unmerge-btn')) { return; }\n"
1103
+ " if (e.target.classList.contains('merge-btn')) {\n"
1104
+ " e.preventDefault();\n"
1105
+ " e.stopPropagation();\n"
1106
+ " const msgId = e.target.dataset.msgId;\n"
1107
+ " const currentMsg = e.target.closest('.chat-message');\n"
1108
+ " if (!currentMsg) return;\n"
1109
+ " if (currentMsg.classList.contains('role-user')) {\n"
1110
+ " alert('Cannot merge user messages');\n"
1111
+ " return;\n"
1112
+ " }\n"
1113
+ " let nextMsg = currentMsg.nextElementSibling;\n"
1114
+ " while (nextMsg && !nextMsg.classList.contains('chat-message')) {\n"
1115
+ " nextMsg = nextMsg.nextElementSibling;\n"
1116
+ " }\n"
1117
+ " while (nextMsg && nextMsg.classList.contains('role-user')) {\n"
1118
+ " nextMsg = nextMsg.nextElementSibling;\n"
1119
+ " while (nextMsg && !nextMsg.classList.contains('chat-message')) {\n"
1120
+ " nextMsg = nextMsg.nextElementSibling;\n"
1121
+ " }\n"
1122
+ " }\n"
1123
+ " if (!nextMsg || nextMsg.classList.contains('chat-message') === false) {\n"
1124
+ " alert('No next assistant message to merge with');\n"
1125
+ " return;\n"
1126
+ " }\n"
1127
+ " if (nextMsg.classList.contains('role-user')) {\n"
1128
+ " alert('Cannot merge with user messages');\n"
1129
+ " return;\n"
1130
+ " }\n"
1131
+ " \n"
1132
+ " // Find the user prompts that precede each assistant message\n"
1133
+ " let currentPrompt = currentMsg.previousElementSibling;\n"
1134
+ " while (currentPrompt && !currentPrompt.classList.contains('chat-message')) {\n"
1135
+ " currentPrompt = currentPrompt.previousElementSibling;\n"
1136
+ " }\n"
1137
+ " if (currentPrompt && !currentPrompt.classList.contains('role-user')) {\n"
1138
+ " currentPrompt = null;\n"
1139
+ " }\n"
1140
+ " \n"
1141
+ " let nextPrompt = nextMsg.previousElementSibling;\n"
1142
+ " while (nextPrompt && !nextPrompt.classList.contains('chat-message')) {\n"
1143
+ " nextPrompt = nextPrompt.previousElementSibling;\n"
1144
+ " }\n"
1145
+ " if (nextPrompt && !nextPrompt.classList.contains('role-user')) {\n"
1146
+ " nextPrompt = null;\n"
1147
+ " }\n"
1148
+ " \n"
1149
+ " // Find the split-agent-context that precedes the first prompt or assistant message\n"
1150
+ " let splitContext = null;\n"
1151
+ " let searchStart = currentPrompt || currentMsg;\n"
1152
+ " let elem = searchStart.previousElementSibling;\n"
1153
+ " while (elem) {\n"
1154
+ " if (elem.classList.contains('split-agent-context')) {\n"
1155
+ " splitContext = elem;\n"
1156
+ " break;\n"
1157
+ " }\n"
1158
+ " if (elem.classList.contains('chat-message') || elem.classList.contains('chat-group-divider')) {\n"
1159
+ " break;\n"
1160
+ " }\n"
1161
+ " elem = elem.previousElementSibling;\n"
1162
+ " }\n"
1163
+ " \n"
1164
+ " const parent = currentMsg.parentElement;\n"
1165
+ " if (parent.classList.contains('simultaneous-messages')) {\n"
1166
+ " const wrapper = parent;\n"
1167
+ " currentMsg.style.display = '';\n"
1168
+ " currentMsg.classList.remove('merged');\n"
1169
+ " const refNode = wrapper.nextElementSibling;\n"
1170
+ " parent.parentElement.insertBefore(currentMsg, refNode);\n"
1171
+ " if (nextMsg.parentElement === wrapper) {\n"
1172
+ " parent.parentElement.insertBefore(nextMsg, refNode);\n"
1173
+ " }\n"
1174
+ " if (wrapper.children.length === 0) {\n"
1175
+ " wrapper.remove();\n"
1176
+ " }\n"
1177
+ " } else {\n"
1178
+ " // If split-agent-context exists, wrap it\n"
1179
+ " if (splitContext && !splitContext.classList.contains('merged')) {\n"
1180
+ " const splitWrapper = document.createElement('div');\n"
1181
+ " splitWrapper.className = 'simultaneous-messages';\n"
1182
+ " const splitUnmergeBtn = document.createElement('button');\n"
1183
+ " splitUnmergeBtn.className = 'unmerge-btn';\n"
1184
+ " splitUnmergeBtn.innerHTML = '✕';\n"
1185
+ " splitUnmergeBtn.title = 'Click to unmerge messages';\n"
1186
+ " splitWrapper.appendChild(splitUnmergeBtn);\n"
1187
+ " splitWrapper.dataset.isSplitContext = 'true';\n"
1188
+ " parent.insertBefore(splitWrapper, splitContext);\n"
1189
+ " splitWrapper.appendChild(splitContext);\n"
1190
+ " splitContext.classList.add('merged');\n"
1191
+ " }\n"
1192
+ " \n"
1193
+ " // Create wrapper for prompts if both exist\n"
1194
+ " if (currentPrompt && nextPrompt) {\n"
1195
+ " const promptWrapper = document.createElement('div');\n"
1196
+ " promptWrapper.className = 'simultaneous-messages';\n"
1197
+ " const promptUnmergeBtn = document.createElement('button');\n"
1198
+ " promptUnmergeBtn.className = 'unmerge-btn';\n"
1199
+ " promptUnmergeBtn.innerHTML = '✕';\n"
1200
+ " promptUnmergeBtn.title = 'Click to unmerge messages';\n"
1201
+ " promptWrapper.appendChild(promptUnmergeBtn);\n"
1202
+ " promptWrapper.dataset.firstMsgId = currentPrompt.dataset.msgId;\n"
1203
+ " promptWrapper.dataset.secondMsgId = nextPrompt.dataset.msgId;\n"
1204
+ " \n"
1205
+ " // Determine order: agent-0 first, agent-1 second\n"
1206
+ " const firstPrompt = currentPrompt.classList.contains('agent-0') ? currentPrompt : nextPrompt;\n"
1207
+ " const secondPrompt = currentPrompt.classList.contains('agent-0') ? nextPrompt : currentPrompt;\n"
1208
+ " \n"
1209
+ " parent.insertBefore(promptWrapper, currentPrompt);\n"
1210
+ " promptWrapper.appendChild(firstPrompt);\n"
1211
+ " promptWrapper.appendChild(secondPrompt);\n"
1212
+ " currentPrompt.classList.add('merged');\n"
1213
+ " nextPrompt.classList.add('merged');\n"
1214
+ " }\n"
1215
+ " \n"
1216
+ " // Create wrapper for assistant messages\n"
1217
+ " const wrapper = document.createElement('div');\n"
1218
+ " wrapper.className = 'simultaneous-messages';\n"
1219
+ " const unmergeBtn = document.createElement('button');\n"
1220
+ " unmergeBtn.className = 'unmerge-btn';\n"
1221
+ " unmergeBtn.innerHTML = '✕';\n"
1222
+ " unmergeBtn.title = 'Click to unmerge messages';\n"
1223
+ " wrapper.appendChild(unmergeBtn);\n"
1224
+ " wrapper.dataset.firstMsgId = currentMsg.dataset.msgId;\n"
1225
+ " wrapper.dataset.secondMsgId = nextMsg.dataset.msgId;\n"
1226
+ " \n"
1227
+ " // Determine order: agent-0 first, agent-1 second\n"
1228
+ " const firstAssistant = currentMsg.classList.contains('agent-0') ? currentMsg : nextMsg;\n"
1229
+ " const secondAssistant = currentMsg.classList.contains('agent-0') ? nextMsg : currentMsg;\n"
1230
+ " \n"
1231
+ " parent.insertBefore(wrapper, currentMsg);\n"
1232
+ " wrapper.appendChild(firstAssistant);\n"
1233
+ " wrapper.appendChild(secondAssistant);\n"
1234
+ " currentMsg.classList.add('merged');\n"
1235
+ " nextMsg.classList.add('merged');\n"
1236
+ " }\n"
1237
+ " }\n"
1238
+ " if (e.target.classList.contains('unmerge-btn')) {\n"
1239
+ " const wrapper = e.target.closest('.simultaneous-messages');\n"
1240
+ " if (!wrapper) return;\n"
1241
+ " const parent = wrapper.parentElement;\n"
1242
+ " \n"
1243
+ " // Check if this is a split-context wrapper\n"
1244
+ " if (wrapper.dataset.isSplitContext === 'true') {\n"
1245
+ " const splitContext = wrapper.querySelector('.split-agent-context');\n"
1246
+ " if (splitContext) {\n"
1247
+ " splitContext.classList.remove('merged');\n"
1248
+ " parent.insertBefore(splitContext, wrapper.nextElementSibling);\n"
1249
+ " }\n"
1250
+ " wrapper.remove();\n"
1251
+ " return;\n"
1252
+ " }\n"
1253
+ " \n"
1254
+ " const firstMsgId = wrapper.dataset.firstMsgId;\n"
1255
+ " const secondMsgId = wrapper.dataset.secondMsgId;\n"
1256
+ " const messages = Array.from(wrapper.querySelectorAll('.chat-message'));\n"
1257
+ " const refNode = wrapper.nextElementSibling;\n"
1258
+ " const firstMsg = messages.find(m => m.dataset.msgId === firstMsgId);\n"
1259
+ " const secondMsg = messages.find(m => m.dataset.msgId === secondMsgId);\n"
1260
+ " \n"
1261
+ " // Check for preceding wrappers to also unmerge (prompts and split-context)\n"
1262
+ " let currentElem = wrapper.previousElementSibling;\n"
1263
+ " const wrappersToUnmerge = [];\n"
1264
+ " \n"
1265
+ " while (currentElem) {\n"
1266
+ " if (currentElem.classList.contains('simultaneous-messages')) {\n"
1267
+ " wrappersToUnmerge.push(currentElem);\n"
1268
+ " } else if (currentElem.classList.contains('chat-message') || currentElem.classList.contains('chat-group-divider')) {\n"
1269
+ " break;\n"
1270
+ " }\n"
1271
+ " currentElem = currentElem.previousElementSibling;\n"
1272
+ " }\n"
1273
+ " \n"
1274
+ " // Unmerge preceding wrappers\n"
1275
+ " for (const prevWrapper of wrappersToUnmerge) {\n"
1276
+ " if (prevWrapper.dataset.isSplitContext === 'true') {\n"
1277
+ " const splitContext = prevWrapper.querySelector('.split-agent-context');\n"
1278
+ " if (splitContext) {\n"
1279
+ " splitContext.classList.remove('merged');\n"
1280
+ " parent.insertBefore(splitContext, prevWrapper.nextElementSibling);\n"
1281
+ " }\n"
1282
+ " prevWrapper.remove();\n"
1283
+ " } else {\n"
1284
+ " const prevMessages = Array.from(prevWrapper.querySelectorAll('.chat-message'));\n"
1285
+ " const prevFirstMsgId = prevWrapper.dataset.firstMsgId;\n"
1286
+ " const prevSecondMsgId = prevWrapper.dataset.secondMsgId;\n"
1287
+ " const prevFirstMsg = prevMessages.find(m => m.dataset.msgId === prevFirstMsgId);\n"
1288
+ " const prevSecondMsg = prevMessages.find(m => m.dataset.msgId === prevSecondMsgId);\n"
1289
+ " const prevRefNode = prevWrapper.nextElementSibling;\n"
1290
+ " \n"
1291
+ " if (prevFirstMsg) {\n"
1292
+ " prevFirstMsg.classList.remove('merged');\n"
1293
+ " prevFirstMsg.style.display = '';\n"
1294
+ " parent.insertBefore(prevFirstMsg, prevRefNode);\n"
1295
+ " }\n"
1296
+ " if (prevSecondMsg) {\n"
1297
+ " prevSecondMsg.classList.remove('merged');\n"
1298
+ " prevSecondMsg.style.display = '';\n"
1299
+ " parent.insertBefore(prevSecondMsg, prevRefNode);\n"
1300
+ " }\n"
1301
+ " prevWrapper.remove();\n"
1302
+ " }\n"
1303
+ " }\n"
1304
+ " \n"
1305
+ " // Unmerge the main assistant messages\n"
1306
+ " if (firstMsg) {\n"
1307
+ " firstMsg.classList.remove('merged');\n"
1308
+ " firstMsg.style.display = '';\n"
1309
+ " parent.insertBefore(firstMsg, refNode);\n"
1310
+ " }\n"
1311
+ " if (secondMsg) {\n"
1312
+ " secondMsg.classList.remove('merged');\n"
1313
+ " secondMsg.style.display = '';\n"
1314
+ " parent.insertBefore(secondMsg, refNode);\n"
1315
+ " }\n"
1316
+ " wrapper.remove();\n"
1317
+ " }\n"
1318
+ " });\n"
1319
+ "});\n"
1320
+ "</script>",
1321
+ "</head>",
1322
+ "<body>",
1323
+ '<div class="toolbar-wrap">',
1324
+ '<div class="toolbar-hotzone"></div>',
1325
+ '<div class="toolbar">',
1326
+ '<button id="toggle-strong-hide"><span class="emoji-bw">🗜️</span> Strong Hide: <span id="strong-hide-state">Off</span></button>',
1327
+ '<button id="toggle-hide-user-messages"><span class="emoji-bw">👁️</span> Hide Prompts: <span id="hide-user-state">Off</span></button>',
1328
+ '<span id="chat-width-control" style="margin-left:8px;">',
1329
+ '<label for="chat-width-slider"><span class="emoji-bw">↔️</span> Width:</label>',
1330
+ '<input id="chat-width-slider" type="range" min="600" max="1600" step="50" value="900" style="width:120px; vertical-align:middle;" />',
1331
+ '<span id="chat-width-value" style="margin-left:4px;">900px</span>',
1332
+ "</span>",
1333
+ '<span style="margin-left:12px;">',
1334
+ '<label for="font-family-select"><span class="emoji-bw">🔤</span> Font:</label>',
1335
+ '<select id="font-family-select" style="padding:2px 6px; border:1px solid var(--accent-muted); border-radius:var(--corner-radius); background:var(--bg);">',
1336
+ "<option value=\"'Segoe UI', Tahoma, Geneva, Verdana, sans-serif\">Segoe UI</option>",
1337
+ '<option value="Arial, sans-serif">Arial</option>',
1338
+ "<option value=\"'Helvetica Neue', Helvetica, sans-serif\">Helvetica</option>",
1339
+ "<option value=\"'Times New Roman', Times, serif\">Times New Roman</option>",
1340
+ '<option value="Georgia, serif">Georgia</option>',
1341
+ "<option value=\"'Courier New', Courier, monospace\">Courier New</option>",
1342
+ "<option value=\"'Comic Sans MS', cursive\">Comic Sans</option>",
1343
+ "<option value=\"'Trebuchet MS', sans-serif\">Trebuchet MS</option>",
1344
+ '<option value="Verdana, sans-serif">Verdana</option>',
1345
+ "<option value=\"'Palatino Linotype', 'Book Antiqua', Palatino, serif\">Palatino</option>",
1346
+ "<option value=\"'Lucida Console', Monaco, monospace\">Lucida Console</option>",
1347
+ "</select>",
1348
+ "</span>",
1349
+ '<span style="margin-left:8px;">',
1350
+ '<label for="font-size-input"><span class="emoji-bw">📏</span> Size:</label>',
1351
+ '<input id="font-size-input" type="number" min="8" max="24" step="1" value="14" style="width:50px;" />',
1352
+ "<span>px</span>",
1353
+ "</span>",
1354
+ '<span style="margin-left:12px; display:flex; align-items:center; gap:8px;">',
1355
+ '<label style="font-weight:600;">Agent Names:</label>',
1356
+ f'<select id="agent0-emoji-input" style="width:65px; padding:2px 6px; border:1px solid var(--accent-muted); border-radius:var(--corner-radius); background:var(--bg);">',
1357
+ '<option value="🤖">🤖 Robot</option>',
1358
+ '<option value="👤">👤 Human</option>',
1359
+ "</select>",
1360
+ f'<input id="agent0-name-input" type="text" placeholder="{html.escape(unique_agent_ids[0]) if len(unique_agent_ids) > 0 else "Agent 0"}" style="width:80px; padding:2px 6px; border:1px solid var(--accent-muted); border-radius:var(--corner-radius); background:var(--bg);" />',
1361
+ '<span style="margin:0 4px;">|</span>',
1362
+ f'<select id="agent1-emoji-input" style="width:65px; padding:2px 6px; border:1px solid var(--accent-muted); border-radius:var(--corner-radius); background:var(--bg);">',
1363
+ '<option value="🤖">🤖 Robot</option>',
1364
+ '<option value="👤">👤 Human</option>',
1365
+ "</select>",
1366
+ f'<input id="agent1-name-input" type="text" placeholder="{html.escape(unique_agent_ids[1]) if len(unique_agent_ids) > 1 else "Agent 1"}" style="width:80px; padding:2px 6px; border:1px solid var(--accent-muted); border-radius:var(--corner-radius); background:var(--bg);" />',
1367
+ '<button id="apply-agent-names" style="padding:4px 8px; border:1px solid var(--accent-muted); background:var(--panel-bg); border-radius:var(--corner-radius); cursor:pointer;">Apply</button>',
1368
+ "</span>",
1369
+ "</div>",
1370
+ "</div>",
1371
+ ]
1372
+
1373
+ # Add Chat View
1374
+ import html as _html_mod
1375
+
1376
+ html_parts.append('<div id="flow-chat" class="messages-flow">')
1377
+
1378
+ # Helper function to add context annotation areas
1379
+ def add_context_area(position: str, time_step: int):
1380
+ context_key = f"round-context-{position}-{time_step}"
1381
+ placeholder = f"Add context {position} round {time_step}..."
1382
+ color_buttons = ""
1383
+ # Add default/reset color button first
1384
+ color_buttons += (
1385
+ f'<div class="context-color-btn" data-color="default" '
1386
+ f'style="background: linear-gradient(135deg, #000 25%, transparent 25%, transparent 75%, #000 75%), '
1387
+ f"linear-gradient(135deg, #000 25%, transparent 25%, transparent 75%, #000 75%); "
1388
+ f"background-size: 4px 4px; background-position: 0 0, 2px 2px; "
1389
+ f'background-color: #fff;" title="Default color"></div>'
1390
+ )
1391
+ for color_name, color_value in [
1392
+ ("red", "#d32f2f"),
1393
+ ("orange", "#f57c00"),
1394
+ ("yellow", "#f9a825"),
1395
+ ("green", "#388e3c"),
1396
+ ("blue", "#1976d2"),
1397
+ ("purple", "#7b1fa2"),
1398
+ ("gray", "#666666"),
1399
+ ]:
1400
+ color_buttons += (
1401
+ f'<div class="context-color-btn" data-color="{color_value}" '
1402
+ f'style="background-color: {color_value};" title="{color_name}"></div>'
1403
+ )
1404
+
1405
+ html_parts.append(
1406
+ f'<div class="round-context">'
1407
+ f'<div class="round-context-edit" contenteditable="true" spellcheck="true" '
1408
+ f'data-context-key="{context_key}" '
1409
+ f'data-placeholder="{placeholder}"></div>'
1410
+ f'<div class="round-context-controls">{color_buttons}</div>'
1411
+ f"</div>"
1412
+ )
1413
+
1414
+ # Helper function to add split agent context boxes
1415
+ def add_split_agent_contexts(position: str, time_step: int):
1416
+ color_buttons = ""
1417
+ # Add default/reset color button first
1418
+ color_buttons += (
1419
+ f'<div class="context-color-btn" data-color="default" '
1420
+ f'style="background: linear-gradient(135deg, #000 25%, transparent 25%, transparent 75%, #000 75%), '
1421
+ f"linear-gradient(135deg, #000 25%, transparent 25%, transparent 75%, #000 75%); "
1422
+ f"background-size: 4px 4px; background-position: 0 0, 2px 2px; "
1423
+ f'background-color: #fff;" title="Default color"></div>'
1424
+ )
1425
+ for color_name, color_value in [
1426
+ ("red", "#d32f2f"),
1427
+ ("orange", "#f57c00"),
1428
+ ("yellow", "#f9a825"),
1429
+ ("green", "#388e3c"),
1430
+ ("blue", "#1976d2"),
1431
+ ("purple", "#7b1fa2"),
1432
+ ("gray", "#666666"),
1433
+ ]:
1434
+ color_buttons += (
1435
+ f'<div class="context-color-btn" data-color="{color_value}" '
1436
+ f'style="background-color: {color_value};" title="{color_name}"></div>'
1437
+ )
1438
+
1439
+ html_parts.append('<div class="split-agent-context">')
1440
+
1441
+ # Agent 0 box
1442
+ agent0_key = f"agent-context-0-{position}-{time_step}"
1443
+ agent0_placeholder = f"..."
1444
+ html_parts.append(
1445
+ f'<div class="agent-context-box agent-0">'
1446
+ f'<div class="round-context-edit" contenteditable="true" spellcheck="true" '
1447
+ f'data-context-key="{agent0_key}" '
1448
+ f'data-placeholder="{agent0_placeholder}"></div>'
1449
+ f'<div class="round-context-controls">{color_buttons}</div>'
1450
+ f"</div>"
1451
+ )
1452
+
1453
+ # Agent 1 box
1454
+ agent1_key = f"agent-context-1-{position}-{time_step}"
1455
+ agent1_placeholder = f"..."
1456
+ html_parts.append(
1457
+ f'<div class="agent-context-box agent-1">'
1458
+ f'<div class="round-context-edit" contenteditable="true" spellcheck="true" '
1459
+ f'data-context-key="{agent1_key}" '
1460
+ f'data-placeholder="{agent1_placeholder}"></div>'
1461
+ f'<div class="round-context-controls">{color_buttons}</div>'
1462
+ f"</div>"
1463
+ )
1464
+
1465
+ html_parts.append("</div>") # split-agent-context
1466
+
1467
+ last_time_step_chat = None
1468
+ for original_index, turn in indexed_turns:
1469
+ # Use agent index for CSS class (agent-0 or agent-1) instead of agent ID
1470
+ agent_index = agent_id_to_index.get(turn.agent_id, 0)
1471
+ agent_class = f"agent-{agent_index}"
1472
+ role_class = f"role-{turn.role}"
1473
+
1474
+ # Add time step divider and beginning context
1475
+ if last_time_step_chat is None or turn.time_step != last_time_step_chat:
1476
+ # Add end contexts for previous round (only regular context, not prompt summary)
1477
+ if last_time_step_chat is not None:
1478
+ add_context_area("end", last_time_step_chat)
1479
+
1480
+ html_parts.append(
1481
+ f'<div class="chat-group-divider">'
1482
+ f'<span class="chat-group-label">⏱ Round {turn.time_step + 1}</span>'
1483
+ f"</div>"
1484
+ )
1485
+
1486
+ # Add beginning contexts for new round (both context and prompt summary)
1487
+ add_context_area("beginning", turn.time_step)
1488
+ add_split_agent_contexts("beginning", turn.time_step)
1489
+
1490
+ last_time_step_chat = turn.time_step
1491
+
1492
+ # Build chat message with merge controls
1493
+ html_parts.append(
1494
+ f'<div class="chat-message {agent_class} {role_class}" data-msg-id="{original_index}">'
1495
+ )
1496
+
1497
+ # Add merge control button
1498
+ html_parts.append(
1499
+ f'<button class="merge-btn" title="Merge with next message" data-msg-id="{original_index}">⇄</button>'
1500
+ )
1501
+
1502
+ html_parts.append('<div class="chat-message-content">')
1503
+
1504
+ # Header with agent name and reward (always show reward)
1505
+ if turn.role == "assistant":
1506
+ name = _html_mod.escape(turn.agent_id)
1507
+ raw_val = turn.reward
1508
+ if isinstance(raw_val, (int, float)):
1509
+ reward_val = f"{raw_val:.4f}".rstrip("0").rstrip(".")
1510
+ if len(reward_val) > 8:
1511
+ reward_val = reward_val[:8] + "…"
1512
+ else:
1513
+ reward_val = str(raw_val)
1514
+ header_html = (
1515
+ f'<div class="chat-header">'
1516
+ f'<span class="emoji-bw" data-agent-index="{agent_index}">🤖</span> <span class="agent-name" data-agent-index="{agent_index}">{name}</span>'
1517
+ f'<span class="chat-reward">⚑ {reward_val}</span>'
1518
+ f"</div>"
1519
+ )
1520
+ else:
1521
+ name = _html_mod.escape(turn.agent_id)
1522
+ header_html = f'<div class="chat-header">Prompt of <span class="agent-name" data-agent-index="{agent_index}">{name}</span></div>'
1523
+
1524
+ html_parts.append(header_html)
1525
+
1526
+ # Reasoning content if present
1527
+ if turn.reasoning_content:
1528
+ _raw_reasoning = turn.reasoning_content.replace("\r\n", "\n")
1529
+ _raw_reasoning = _re.sub(r"^\s*\n+", "", _raw_reasoning)
1530
+ esc_reasoning = _html_mod.escape(_raw_reasoning)
1531
+ html_parts.append(
1532
+ f'<div class="chat-reasoning collapsed">'
1533
+ f'<span class="reasoning-icon">💭</span> '
1534
+ f'<span class="reasoning-text">{esc_reasoning}</span>'
1535
+ f"</div>"
1536
+ )
1537
+
1538
+ # Message bubble
1539
+ esc_content = _html_mod.escape(turn.content)
1540
+ html_parts.append(f'<div class="chat-bubble">{esc_content}</div>')
1541
+
1542
+ html_parts.append("</div>") # chat-message-content
1543
+ html_parts.append("</div>") # chat-message
1544
+
1545
+ # Add end contexts for the last round (only regular context, not prompt summary)
1546
+ if last_time_step_chat is not None:
1547
+ add_context_area("end", last_time_step_chat)
1548
+
1549
+ html_parts.append("</div>") # flow-chat
1550
+ html_parts.extend(["</body>", "</html>"])
1551
+
1552
+ return "\n".join(html_parts)
1553
+
1554
+
1555
+ def export_html_from_rollout_tree(path: Path, outdir: Path, main_only: bool = False):
1556
+ """Process a rollout tree file and generate HTML files for each path.
1557
+ Creates separate HTML files for the main path and each branch path.
1558
+ The main path is saved in the root output directory, while branch paths
1559
+ are saved in a 'branches' subdirectory.
1560
+
1561
+ Args:
1562
+ path: Path to the rollout tree JSON file
1563
+ outdir: Output directory for HTML files
1564
+ main_only: If True, only export the main trajectory (default: False)
1565
+ """
1566
+ root = load_rollout_tree(path)
1567
+ mgid = root.id
1568
+
1569
+ main_path, branch_paths = get_rollout_tree_paths(root)
1570
+
1571
+ outdir.mkdir(parents=True, exist_ok=True)
1572
+
1573
+ # Create branches subdirectory if we have branch paths
1574
+ if not main_only and branch_paths:
1575
+ branches_dir = outdir / f"mgid:{mgid}_branches_html_renders"
1576
+ branches_dir.mkdir(parents=True, exist_ok=True)
1577
+
1578
+ # Generate HTML for the main path
1579
+ chat_turns = gather_all_chat_turns_for_path(main_path)
1580
+ html_content = html_from_chat_turns(chat_turns)
1581
+ output_file = outdir / f"mgid:{mgid}_main_html_render.render.html"
1582
+ with open(output_file, "w", encoding="utf-8") as f:
1583
+ f.write(html_content)
1584
+
1585
+ # Generate HTML for each branch path
1586
+ for path_obj in branch_paths:
1587
+ chat_turns = gather_all_chat_turns_for_path(path_obj)
1588
+
1589
+ html_content = html_from_chat_turns(chat_turns)
1590
+
1591
+ path_id: str = path_obj.id
1592
+ output_filename = f"{path_id}_html_render.render.html"
1593
+
1594
+ output_file = branches_dir / output_filename
1595
+
1596
+ with open(output_file, "w", encoding="utf-8") as f:
1597
+ f.write(html_content)
src_code_for_reproducibility/utils/rollout_tree_gather_utils.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/rollout_tree_gather_utils.py
3
+ Summary: Utilities for gathering rollout tree files and metadata.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import csv
9
+ import os
10
+ import pickle
11
+ import re
12
+ from collections import defaultdict
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
16
+
17
+ from mllm.markov_games.rollout_tree import *
18
+
19
+
20
+ def load_rollout_tree(path: Path) -> RolloutTreeRootNode:
21
+ """Load a rollout tree from a PKL file containing a dict."""
22
+ with open(path, "rb") as f:
23
+ data = pickle.load(f)
24
+ return RolloutTreeRootNode.model_validate(data)
25
+
26
+
27
+ @dataclass
28
+ class RolloutNodeList:
29
+ id: str
30
+ nodes: List[RolloutTreeNode]
31
+
32
+
33
+ def get_rollout_tree_paths(
34
+ root: RolloutTreeRootNode, mgid: Optional[str] = None
35
+ ) -> Tuple[RolloutNodeList, List[RolloutNodeList]]:
36
+ """
37
+ Returns:
38
+ main_path: The main path from the root to the end of the tree.
39
+ branch_paths: A list of all branch paths from the root to the end of the tree.
40
+ Each branch path contains a list of nodes that are part of the branch, including the nodes from the main path before the branch was taken.
41
+ """
42
+ branch_paths = []
43
+
44
+ def collect_path_nodes(current) -> List[RolloutTreeNode]:
45
+ """Recursively collect all nodes in a path starting from current node."""
46
+ if current is None:
47
+ return []
48
+
49
+ if isinstance(current, RolloutTreeNode):
50
+ return [current] + collect_path_nodes(current.child)
51
+
52
+ elif isinstance(current, RolloutTreeBranchNode):
53
+ # For branch nodes, we only follow the main_child for path collection
54
+ if current.main_child:
55
+ return [current.main_child] + collect_path_nodes(
56
+ current.main_child.child
57
+ )
58
+ else:
59
+ return []
60
+
61
+ def traverse_for_branches(
62
+ current,
63
+ main_path_prefix: List[RolloutTreeNode],
64
+ path_id: str,
65
+ current_time_step: Optional[int] = 0,
66
+ ):
67
+ """Traverse tree to collect all branch paths."""
68
+ if current is None:
69
+ return
70
+
71
+ if isinstance(current, RolloutTreeNode):
72
+ # Continue traversing with this node added to the main path prefix
73
+ new_prefix = main_path_prefix + [current]
74
+ traverse_for_branches(current.child, new_prefix, path_id, current.time_step)
75
+
76
+ elif isinstance(current, RolloutTreeBranchNode):
77
+ # Collect all branch paths
78
+ if current.branches:
79
+ for agent_id, branch_node_list in current.branches.items():
80
+ if branch_node_list:
81
+ # Start with the main path prefix, then recursively collect all nodes in this branch
82
+ branch_path_nodes = main_path_prefix.copy()
83
+ for branch_node in branch_node_list:
84
+ branch_path_nodes.extend(collect_path_nodes(branch_node))
85
+
86
+ # Create proper branch path ID with mgid, agent_id, and time_step
87
+ mgid_str = mgid or str(root.id)
88
+ branch_path_id = f"mgid:{mgid_str}_type:branch_agent:{agent_id}_time_step:{current_time_step}"
89
+ branch_paths.append(
90
+ RolloutNodeList(id=branch_path_id, nodes=branch_path_nodes)
91
+ )
92
+
93
+ # Process the main child and add to prefix
94
+ new_prefix = main_path_prefix
95
+ if current.main_child:
96
+ new_prefix = main_path_prefix + [current.main_child]
97
+
98
+ # Continue traversing the main path
99
+ if current.main_child:
100
+ traverse_for_branches(
101
+ current.main_child.child,
102
+ new_prefix,
103
+ path_id,
104
+ current.main_child.time_step,
105
+ )
106
+
107
+ # Collect the main path nodes
108
+ main_path_nodes = collect_path_nodes(root.child)
109
+
110
+ # Traverse to collect all branch paths
111
+ traverse_for_branches(root.child, [], "")
112
+
113
+ # Create the main path with proper mgid format
114
+ mgid_str = mgid or str(root.id)
115
+ main_path = RolloutNodeList(id=f"mgid:{mgid_str}_type:main", nodes=main_path_nodes)
116
+
117
+ return main_path, branch_paths
118
+
119
+
120
+ class ChatTurnLog(BaseModel):
121
+ time_step: int
122
+ agent_id: str
123
+ role: str
124
+ content: str
125
+ reasoning_content: Optional[str] = None
126
+ is_state_end: bool
127
+ reward: float
128
+
129
+
130
+ def gather_agent_chat_turns_for_path(
131
+ agent_id: str, path: RolloutNodeList
132
+ ) -> List[ChatTurnLog]:
133
+ """Iterate through all chat turns for a specific agent in a path sorted by time step."""
134
+ turns = []
135
+ for node in path.nodes:
136
+ action_log = node.step_log.action_logs.get(agent_id, [])
137
+ if action_log:
138
+ for chat_turn in action_log.chat_turns or []:
139
+ turns.append(
140
+ ChatTurnLog(
141
+ time_step=node.time_step,
142
+ agent_id=agent_id,
143
+ role=chat_turn.role,
144
+ content=chat_turn.content,
145
+ reasoning_content=getattr(chat_turn, "reasoning_content", None),
146
+ is_state_end=chat_turn.is_state_end,
147
+ reward=node.step_log.simulation_step_log.rewards.get(
148
+ agent_id, 0
149
+ ),
150
+ )
151
+ )
152
+ return turns
153
+
154
+
155
+ def gather_all_chat_turns_for_path(path: RolloutNodeList) -> List[ChatTurnLog]:
156
+ """Iterate through all chat turns for all agents in a path sorted by time step."""
157
+ turns = []
158
+
159
+ # Collect turns from all agents, but interleave them per timestep by (user, assistant) pairs
160
+ for node in path.nodes:
161
+ # Build (user[, assistant]) pairs for each agent at this timestep
162
+ agent_ids = sorted(list(node.step_log.action_logs.keys()))
163
+ per_agent_pairs: Dict[str, List[List[ChatTurnLog]]] = {}
164
+
165
+ for agent_id in agent_ids:
166
+ action_log = node.step_log.action_logs.get(agent_id)
167
+ pairs: List[List[ChatTurnLog]] = []
168
+ current_pair: List[ChatTurnLog] = []
169
+
170
+ if action_log and action_log.chat_turns:
171
+ for chat_turn in action_log.chat_turns:
172
+ turn_log = ChatTurnLog(
173
+ time_step=node.time_step,
174
+ agent_id=agent_id,
175
+ role=chat_turn.role,
176
+ content=chat_turn.content,
177
+ reasoning_content=getattr(chat_turn, "reasoning_content", None),
178
+ is_state_end=chat_turn.is_state_end,
179
+ reward=node.step_log.simulation_step_log.rewards.get(
180
+ agent_id, 0
181
+ ),
182
+ )
183
+
184
+ if chat_turn.role == "user":
185
+ # If a previous pair is open, close it and start a new one
186
+ if current_pair:
187
+ pairs.append(current_pair)
188
+ current_pair = []
189
+ current_pair = [turn_log]
190
+ else:
191
+ # assistant: attach to an open user message if present; otherwise stand alone
192
+ if (
193
+ current_pair
194
+ and len(current_pair) == 1
195
+ and current_pair[0].role == "user"
196
+ ):
197
+ current_pair.append(turn_log)
198
+ pairs.append(current_pair)
199
+ current_pair = []
200
+ else:
201
+ # No preceding user or already paired; treat as its own unit
202
+ pairs.append([turn_log])
203
+
204
+ if current_pair:
205
+ # Unpaired trailing user message
206
+ pairs.append(current_pair)
207
+
208
+ per_agent_pairs[agent_id] = pairs
209
+
210
+ # Interleave pairs across agents: A1, B1, A2, B2, ...
211
+ index = 0
212
+ while True:
213
+ added_any = False
214
+ for agent_id in agent_ids:
215
+ agent_pairs = per_agent_pairs.get(agent_id, [])
216
+ if index < len(agent_pairs):
217
+ for tl in agent_pairs[index]:
218
+ turns.append(tl)
219
+ added_any = True
220
+ if not added_any:
221
+ break
222
+ index += 1
223
+
224
+ return turns
225
+
226
+
227
+ def chat_turns_to_dict(chat_turns: Iterator[ChatTurnLog]) -> Iterator[Dict[str, Any]]:
228
+ """Render all chat turns for a path as structured data for JSON."""
229
+ for chat_turn in chat_turns:
230
+ yield chat_turn.model_dump()
231
+
232
+
233
+ def get_all_agents(root: RolloutTreeRootNode) -> List[str]:
234
+ """list of all agent IDs that appear in the tree."""
235
+ if root.child is None:
236
+ return []
237
+
238
+ # Get the first node to extract all agent IDs
239
+ first_node = root.child
240
+ if isinstance(first_node, RolloutTreeBranchNode):
241
+ first_node = first_node.main_child
242
+
243
+ if first_node is None:
244
+ return []
245
+
246
+ # All agents should be present in the first node
247
+ agents = set(first_node.step_log.action_logs.keys())
248
+ agents.update(first_node.step_log.simulation_step_log.rewards.keys())
249
+
250
+ return sorted(list(agents))
251
+
252
+
253
+ def gather_agent_main_rewards(agent_id: str, path: RolloutNodeList) -> List[float]:
254
+ """Gather main rewards for a specific agent in a path."""
255
+ rewards = []
256
+ for node in path.nodes:
257
+ reward = node.step_log.simulation_step_log.rewards[agent_id]
258
+ rewards.append(reward)
259
+ return rewards
260
+
261
+
262
+ def gather_all_rewards(path: RolloutNodeList) -> List[Dict[AgentId, float]]:
263
+ """Gather main rewards from main trajectory in a path."""
264
+ rewards = []
265
+ for node in path.nodes:
266
+ rewards.append(node.step_log.simulation_step_log.rewards.copy())
267
+ return rewards
268
+
269
+
270
+ def gather_simulation_stats(
271
+ path: RolloutNodeList,
272
+ filter: Callable[[SimulationStepLog], bool],
273
+ stat_func: Callable[[SimulationStepLog], Any],
274
+ ) -> List[Any]:
275
+ """Gather stats from main trajectory in a path."""
276
+ stats = []
277
+ for node in path.nodes:
278
+ sl = node.step_log.simulation_step_log
279
+ if filter(sl):
280
+ stats.append(stat_func(sl))
281
+ return stats
282
+
283
+
284
+ def gather_simulation_step_logs(path: RolloutNodeList) -> List[SimulationStepLog]:
285
+ """Gather simulation information from main trajectory in a path."""
286
+ infos = []
287
+ for node in path.nodes:
288
+ infos.append(node.step_log.simulation_step_log)
289
+ return infos
290
+
291
+
292
+ def export_chat_logs(path: Path, outdir: Path):
293
+ """Process a rollout tree PKL file and generate a JSONL of chat turns as dicts.
294
+ Each line contains an object with path_id and chat_turns for a single path.
295
+ """
296
+ import json
297
+
298
+ root = load_rollout_tree(path)
299
+ mgid = root.id
300
+
301
+ main_path, branch_paths = get_rollout_tree_paths(root)
302
+ all_paths = [main_path] + branch_paths
303
+
304
+ outdir.mkdir(parents=True, exist_ok=True)
305
+ output_file = outdir / f"mgid:{mgid}_plucked_chats.render.jsonl"
306
+
307
+ with open(output_file, "w", encoding="utf-8") as f:
308
+ for path_obj in all_paths:
309
+ chat_turns = gather_all_chat_turns_for_path(path_obj)
310
+ output_obj = {
311
+ "path_id": str(path_obj.id),
312
+ "chat_turns": list(chat_turns_to_dict(iter(chat_turns))),
313
+ }
314
+ f.write(json.dumps(output_obj, ensure_ascii=False) + "\n")
src_code_for_reproducibility/utils/rollout_tree_stats.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/rollout_tree_stats.py
3
+ Summary: Computes descriptive statistics from rollout tree collections.
4
+ """
5
+
6
+ from typing import Any, Callable, List, Tuple
7
+
8
+ from mllm.markov_games.rollout_tree import RolloutTreeRootNode
9
+ from mllm.markov_games.simulation import SimulationStepLog
10
+ from mllm.utils.rollout_tree_gather_utils import (
11
+ gather_simulation_step_logs,
12
+ get_rollout_tree_paths,
13
+ )
14
+ from mllm.utils.stat_pack import StatPack
15
+
16
+
17
+ def get_rollout_tree_stat_tally(
18
+ rollout_tree: RolloutTreeRootNode,
19
+ metrics: List[Callable[[SimulationStepLog], List[Tuple[str, float]]]],
20
+ ) -> StatPack:
21
+ stat_tally = StatPack()
22
+ # get simulation step logs
23
+ node_list = get_rollout_tree_paths(rollout_tree)[0]
24
+ simulation_step_logs = gather_simulation_step_logs(node_list)
25
+ for simulation_step_log in simulation_step_logs:
26
+ for metric in metrics:
27
+ metric_result = metric(simulation_step_log)
28
+ if metric_result is not None:
29
+ for key, value in metric_result:
30
+ stat_tally.add_stat(key, value)
31
+ return stat_tally
32
+
33
+
34
+ def get_rollout_tree_mean_stats(
35
+ rollout_tree: RolloutTreeRootNode, metrics: List[Callable[[SimulationStepLog], Any]]
36
+ ) -> StatPack:
37
+ """Get the mean stats for a rollout tree."""
38
+ stat_tally = get_rollout_tree_stat_tally(rollout_tree, metrics)
39
+ return stat_tally.mean()
40
+
41
+
42
+ def get_mean_rollout_tree_stats(
43
+ rollout_trees: List[RolloutTreeRootNode],
44
+ metrics: List[Callable[[SimulationStepLog], Any]],
45
+ ) -> StatPack:
46
+ """Get the mean stats for a list of rollout trees."""
47
+ # Compute per-rollout means first, then aggregate them across the entire batch.
48
+ stat_tallies = [
49
+ get_rollout_tree_mean_stats(rollout_tree, metrics)
50
+ for rollout_tree in rollout_trees
51
+ ]
52
+ mean_stat_tally = StatPack()
53
+ for stat_tally in stat_tallies:
54
+ mean_stat_tally.add_stats(stat_tally)
55
+ return mean_stat_tally.mean()
src_code_for_reproducibility/utils/short_id_gen.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/short_id_gen.py
3
+ Summary: Generates short unique identifiers for experiment assets.
4
+ """
5
+
6
+ import uuid
7
+
8
+
9
+ def generate_short_id() -> int:
10
+ """
11
+ Generates a short unique ID for tracking adapter versions.
12
+
13
+ Returns:
14
+ int: An 8-digit integer ID.
15
+ """
16
+ return int(str(uuid.uuid4().int)[:8])
src_code_for_reproducibility/utils/stat_pack.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/stat_pack.py
3
+ Summary: Implements the StatPack container for incremental statistics.
4
+ """
5
+
6
+ import csv
7
+ import json
8
+ import os
9
+ import pickle
10
+ from collections import Counter
11
+ from copy import deepcopy
12
+ from locale import strcoll
13
+ from statistics import mean
14
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, TypedDict
15
+
16
+ import matplotlib.pyplot as plt
17
+ import numpy as np
18
+
19
+ style_path = os.environ.get("ADALIGN_MPLSTYLE")
20
+ if style_path:
21
+ plt.style.use(style_path)
22
+
23
+ import wandb
24
+
25
+ from . import wandb_utils
26
+
27
+
28
+ class StatPack:
29
+ def __init__(self):
30
+ self.data = {}
31
+
32
+ def add_stat(self, key: str, value: float | int | None):
33
+ assert (
34
+ isinstance(value, float) or isinstance(value, int) or value is None
35
+ ), f"Value {value} is not a valid type"
36
+ if key not in self.data:
37
+ self.data[key] = []
38
+ self.data[key].append(value)
39
+
40
+ def add_stats(self, other: "StatPack"):
41
+ for key in other.keys():
42
+ self.add_stat(key, other[key])
43
+
44
+ def __getitem__(self, key: str):
45
+ return self.data[key]
46
+
47
+ def __setitem__(self, key: str, value: Any):
48
+ self.data[key] = value
49
+
50
+ def __contains__(self, key: str):
51
+ return key in self.data
52
+
53
+ def __len__(self):
54
+ return len(self.data)
55
+
56
+ def __iter__(self):
57
+ return iter(self.data)
58
+
59
+ def keys(self):
60
+ return self.data.keys()
61
+
62
+ def values(self):
63
+ return self.data.values()
64
+
65
+ def items(self):
66
+ return self.data.items()
67
+
68
+ def mean(self):
69
+ mean_st = StatPack()
70
+ for key in self.keys():
71
+ if isinstance(self[key], list):
72
+ # Ignore None entries so missing measurements do not bias the mean.
73
+ non_none_values = [v for v in self[key] if v is not None]
74
+ if non_none_values:
75
+ mean_st[key] = np.mean(np.array(non_none_values))
76
+ else:
77
+ mean_st[key] = None
78
+ return mean_st
79
+
80
+ def store_plots(self, folder: str):
81
+ os.makedirs(folder, exist_ok=True)
82
+ for key in self.keys():
83
+ plt.figure(figsize=(10, 5))
84
+ plt.plot(self[key])
85
+ plt.title(key)
86
+ plt.savefig(os.path.join(folder, f"{key}.pdf"))
87
+ plt.close()
88
+
89
+ def store_numpy(self, folder: str):
90
+ os.makedirs(folder, exist_ok=True)
91
+ for key in self.keys():
92
+ # Sanitize filename components (avoid slashes, spaces, etc.)
93
+ safe_key = str(key).replace(os.sep, "_").replace("/", "_").replace(" ", "_")
94
+ values = self[key]
95
+ # Convert None to NaN for numpy compatibility
96
+ arr = np.array(
97
+ [(np.nan if (v is None) else v) for v in values], dtype=float
98
+ )
99
+ np.save(os.path.join(folder, f"{safe_key}.npy"), arr)
100
+
101
+ def store_json(self, folder: str, filename: str = "stats.json"):
102
+ os.makedirs(folder, exist_ok=True)
103
+ with open(os.path.join(folder, filename), "w") as f:
104
+ json.dump(self.data, f, indent=4)
105
+
106
+ def store_csv(self, folder: str):
107
+ os.makedirs(folder, exist_ok=True)
108
+ for key in self.keys():
109
+ with open(os.path.join(folder, f"stats.csv"), "w") as f:
110
+ writer = csv.writer(f)
111
+ writer.writerow([key] + self[key])
112
+
113
+ def store_pickle(self, folder: str):
114
+ os.makedirs(folder, exist_ok=True)
115
+ for key in self.keys():
116
+ with open(os.path.join(folder, f"stats.pkl"), "wb") as f:
117
+ pickle.dump(self[key], f)
src_code_for_reproducibility/utils/wandb_utils.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/wandb_utils.py
3
+ Summary: Shared Weights & Biases helper functions.
4
+ """
5
+
6
+ import os
7
+ from typing import Any, Dict, Optional
8
+
9
+ _WANDB_AVAILABLE = False
10
+ _WANDB_RUN = None
11
+
12
+
13
+ def _try_import_wandb():
14
+ global _WANDB_AVAILABLE
15
+ if _WANDB_AVAILABLE:
16
+ return True
17
+ try:
18
+ import wandb # type: ignore
19
+
20
+ _WANDB_AVAILABLE = True
21
+ return True
22
+ except Exception:
23
+ _WANDB_AVAILABLE = False
24
+ return False
25
+
26
+
27
+ def _safe_get(cfg: Dict[str, Any], path: list[str], default: Any = None) -> Any:
28
+ cur: Any = cfg
29
+ for key in path:
30
+ if not isinstance(cur, dict) or key not in cur:
31
+ return default
32
+ cur = cur[key]
33
+ return cur
34
+
35
+
36
+ def is_enabled(cfg: Dict[str, Any]) -> bool:
37
+ return bool(_safe_get(cfg, ["logging", "wandb", "enabled"], False))
38
+
39
+
40
+ def init(cfg: Dict[str, Any], run_dir: str, run_name: Optional[str] = None) -> None:
41
+ """
42
+ Initialize Weights & Biases if enabled in config. No-op if disabled or wandb not installed.
43
+ """
44
+ global _WANDB_RUN
45
+ if not is_enabled(cfg):
46
+ return
47
+ if not _try_import_wandb():
48
+ return
49
+
50
+ import wandb # type: ignore
51
+
52
+ project = _safe_get(cfg, ["logging", "wandb", "project"], "llm-negotiation")
53
+ entity = _safe_get(cfg, ["logging", "wandb", "entity"], None)
54
+ mode = _safe_get(cfg, ["logging", "wandb", "mode"], "online")
55
+ tags = _safe_get(cfg, ["logging", "wandb", "tags"], []) or []
56
+ notes = _safe_get(cfg, ["logging", "wandb", "notes"], None)
57
+ group = _safe_get(cfg, ["logging", "wandb", "group"], None)
58
+ name = _safe_get(cfg, ["logging", "wandb", "name"], run_name)
59
+
60
+ # Ensure files are written into the hydra run directory
61
+ os.makedirs(run_dir, exist_ok=True)
62
+ os.environ.setdefault("WANDB_DIR", run_dir)
63
+
64
+ # Convert cfg to plain types for W&B config; fallback to minimal dictionary
65
+ try:
66
+ from omegaconf import OmegaConf # type: ignore
67
+
68
+ cfg_container = OmegaConf.to_container(cfg, resolve=True) # type: ignore
69
+ except Exception:
70
+ cfg_container = cfg
71
+
72
+ _WANDB_RUN = wandb.init(
73
+ project=project,
74
+ entity=entity,
75
+ mode=mode,
76
+ name=name,
77
+ group=group,
78
+ tags=tags,
79
+ notes=notes,
80
+ config=cfg_container,
81
+ dir=run_dir,
82
+ reinit=True,
83
+ )
84
+
85
+
86
+ def log(metrics: Dict[str, Any], step: Optional[int] = None) -> None:
87
+ """Log a flat dictionary of metrics to W&B if active."""
88
+ if not _WANDB_AVAILABLE or _WANDB_RUN is None:
89
+ return
90
+ try:
91
+ import wandb # type: ignore
92
+
93
+ wandb.log(metrics if step is None else dict(metrics, step=step))
94
+ except Exception:
95
+ pass
96
+
97
+
98
+ def _flatten(prefix: str, data: Dict[str, Any], out: Dict[str, Any]) -> None:
99
+ for k, v in data.items():
100
+ key = f"{prefix}.{k}" if prefix else k
101
+ if isinstance(v, dict):
102
+ _flatten(key, v, out)
103
+ else:
104
+ out[key] = v
105
+
106
+
107
+ def _summarize_value(value: Any) -> Dict[str, Any]:
108
+ import numpy as np # local import to avoid hard dependency during disabled mode
109
+
110
+ if value is None:
111
+ return {"none": 1}
112
+ # Scalars
113
+ if isinstance(value, (int, float)):
114
+ return {"value": float(value)}
115
+ # Lists or arrays
116
+ try:
117
+ arr = np.asarray(value)
118
+ if arr.size == 0:
119
+ return {"size": 0}
120
+ return {
121
+ "mean": float(np.nanmean(arr)),
122
+ "min": float(np.nanmin(arr)),
123
+ "max": float(np.nanmax(arr)),
124
+ "last": float(arr.reshape(-1)[-1]),
125
+ "size": int(arr.size),
126
+ }
127
+ except Exception:
128
+ # Fallback: string repr
129
+ return {"text": str(value)}
130
+
131
+
132
+ def log_tally(
133
+ array_tally: Dict[str, Any], prefix: str = "", step: Optional[int] = None
134
+ ) -> None:
135
+ """
136
+ Flatten and summarize Tally.array_tally and log to WandB.
137
+ Each leaf list/array is summarized with mean/min/max/last/size.
138
+ """
139
+ if not _WANDB_AVAILABLE or _WANDB_RUN is None:
140
+ return
141
+ summarized: Dict[str, Any] = {}
142
+
143
+ def walk(node: Any, path: list[str]):
144
+ if isinstance(node, dict):
145
+ for k, v in node.items():
146
+ walk(v, path + [k])
147
+ return
148
+ # node is a list of values accumulated over time
149
+ key = ".".join([p for p in ([prefix] if prefix else []) + path])
150
+ try:
151
+ summary = _summarize_value(node)
152
+ for sk, sv in summary.items():
153
+ summarized[f"{key}.{sk}"] = sv
154
+ except Exception:
155
+ summarized[f"{key}.error"] = 1
156
+
157
+ walk(array_tally, [])
158
+ if summarized:
159
+ log(summarized, step=step)
160
+
161
+
162
+ def log_flat_stats(
163
+ stats: Dict[str, Any], prefix: str = "", step: Optional[int] = None
164
+ ) -> None:
165
+ if not _WANDB_AVAILABLE or _WANDB_RUN is None:
166
+ return
167
+ flat: Dict[str, Any] = {}
168
+ _flatten(prefix, stats, flat)
169
+ if flat:
170
+ log(flat, step=step)