Muqeeth commited on
Commit
143850b
·
verified ·
1 Parent(s): eeb6360

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .hydra/config.yaml +168 -0
  2. .hydra/hydra.yaml +154 -0
  3. .hydra/overrides.yaml +1 -0
  4. seed_42/Qwen/Qwen2.5-7B-Instruct/adapters/agent_adapter/adapter_config.json +46 -0
  5. seed_42/Qwen/Qwen2.5-7B-Instruct/adapters/critic_adapter/adapter_config.json +46 -0
  6. src_code_for_reproducibility/chat_utils/__pycache__/apply_template.cpython-312.pyc +0 -0
  7. src_code_for_reproducibility/chat_utils/__pycache__/chat_turn.cpython-312.pyc +0 -0
  8. src_code_for_reproducibility/chat_utils/__pycache__/template_specific.cpython-312.pyc +0 -0
  9. src_code_for_reproducibility/markov_games/__pycache__/__init__.cpython-312.pyc +0 -0
  10. src_code_for_reproducibility/markov_games/__pycache__/alternative_actions_runner.cpython-312.pyc +0 -0
  11. src_code_for_reproducibility/markov_games/__pycache__/linear_runner.cpython-312.pyc +0 -0
  12. src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc +0 -0
  13. src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc +0 -0
  14. src_code_for_reproducibility/markov_games/ipd/Ipd_hard_coded_agents.py +76 -0
  15. src_code_for_reproducibility/markov_games/ipd/__init__.py +11 -0
  16. src_code_for_reproducibility/markov_games/ipd/__pycache__/Ipd_hard_coded_agents.cpython-312.pyc +0 -0
  17. src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc +0 -0
  18. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_agent.cpython-312.pyc +0 -0
  19. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_simulation.cpython-312.pyc +0 -0
  20. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_statistics.cpython-312.pyc +0 -0
  21. src_code_for_reproducibility/markov_games/ipd/ipd_agent.py +120 -0
  22. src_code_for_reproducibility/markov_games/ipd/ipd_simulation.py +167 -0
  23. src_code_for_reproducibility/markov_games/ipd/ipd_statistics.py +24 -0
  24. src_code_for_reproducibility/markov_games/negotiation/README.md +27 -0
  25. src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_agent.cpython-312.pyc +0 -0
  26. src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_simulation.cpython-312.pyc +0 -0
  27. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_agent.cpython-312.pyc +0 -0
  28. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_hard_coded_policies.cpython-312.pyc +0 -0
  29. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_simulation.cpython-312.pyc +0 -0
  30. src_code_for_reproducibility/markov_games/negotiation/__pycache__/negotiation_statistics.cpython-312.pyc +0 -0
  31. src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_agent.cpython-312.pyc +0 -0
  32. src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_simulation.cpython-312.pyc +0 -0
  33. src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_agent.cpython-312.pyc +0 -0
  34. src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_simulation.cpython-312.pyc +0 -0
  35. src_code_for_reproducibility/markov_games/negotiation/nego_simulation.py +252 -0
  36. src_code_for_reproducibility/markov_games/negotiation/no_press_nego_agent.py +108 -0
  37. src_code_for_reproducibility/markov_games/negotiation/tas_rps_simulation.py +257 -0
  38. src_code_for_reproducibility/models/__pycache__/large_language_model_api.cpython-312.pyc +0 -0
  39. src_code_for_reproducibility/models/__pycache__/large_language_model_local.cpython-312.pyc +0 -0
  40. src_code_for_reproducibility/training/__pycache__/__init__.cpython-312.pyc +0 -0
  41. src_code_for_reproducibility/training/credit_methods.py +307 -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/resource_context.py +83 -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,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: 50
7
+ start_epoch: 0
8
+ resume_experiment: true
9
+ base_seed: 42
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_naive_seed42
14
+ agent_buffer: false
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: TrainerNaive
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
+ train_on_which_data:
160
+ agent_trainer: ${agent_ids}
161
+ lora_count: 30
162
+ common_agent_kwargs:
163
+ goal: Maximize your total points over the whole game.
164
+ agent_0_id: Alice
165
+ agent_1_id: Bob
166
+ agent_ids:
167
+ - Alice
168
+ - 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_naive_seed42.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_naive_seed42
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_42/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
+ "gate_proj",
33
+ "down_proj",
34
+ "q_proj",
35
+ "o_proj",
36
+ "k_proj",
37
+ "v_proj",
38
+ "up_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
+ }
seed_42/Qwen/Qwen2.5-7B-Instruct/adapters/critic_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
+ "gate_proj",
33
+ "down_proj",
34
+ "q_proj",
35
+ "o_proj",
36
+ "k_proj",
37
+ "v_proj",
38
+ "up_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/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__/alternative_actions_runner.cpython-312.pyc ADDED
Binary file (5.43 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__/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/Ipd_hard_coded_agents.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/ipd/Ipd_hard_coded_agents.py
3
+ Summary: Contains hand-crafted IPD policies used as deterministic baselines.
4
+ """
5
+
6
+ from dataclasses import dataclass
7
+ from typing import Any, Tuple
8
+
9
+ from mllm.markov_games.ipd.ipd_agent import IPDAgent
10
+ from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
11
+
12
+
13
+ @dataclass
14
+ class AlwaysCooperateIPDAgent(IPDAgent):
15
+ async def act(self, observation) -> Tuple[Any, AgentActLog]:
16
+ """
17
+ Always plays the cooperate action, ignoring observation.
18
+ Returns the configured cooperate_string so the simulation parses it as "C".
19
+ """
20
+
21
+ action = self.cooperate_string
22
+
23
+ # Log a minimal, structured chat turn for consistency with other agents
24
+ turn_text = f"Playing cooperate: {action}"
25
+ self.state.chat_history.append(
26
+ ChatTurn(
27
+ agent_id=self.agent_id,
28
+ role="assistant",
29
+ content=turn_text,
30
+ is_state_end=True,
31
+ )
32
+ )
33
+
34
+ act_log = AgentActLog(
35
+ chat_turns=[self.state.chat_history[-1]],
36
+ info=None,
37
+ )
38
+
39
+ # Advance internal counters similar to IPDAgent semantics
40
+ self.state.chat_counter = len(self.state.chat_history)
41
+ self.state.round_nb = observation.round_nb
42
+
43
+ return action, act_log
44
+
45
+
46
+ @dataclass
47
+ class AlwaysDefectIPDAgent(IPDAgent):
48
+ async def act(self, observation) -> Tuple[Any, AgentActLog]:
49
+ """
50
+ Always plays the defect action, ignoring observation.
51
+ Returns the configured defect_string so the simulation parses it as "D".
52
+ """
53
+
54
+ action = self.defect_string
55
+
56
+ # Log a minimal, structured chat turn for consistency with other agents
57
+ turn_text = f"Playing defect: {action}"
58
+ self.state.chat_history.append(
59
+ ChatTurn(
60
+ agent_id=self.agent_id,
61
+ role="assistant",
62
+ content=turn_text,
63
+ is_state_end=True,
64
+ )
65
+ )
66
+
67
+ act_log = AgentActLog(
68
+ chat_turns=[self.state.chat_history[-1]],
69
+ info=None,
70
+ )
71
+
72
+ # Advance internal counters similar to IPDAgent semantics
73
+ self.state.chat_counter = len(self.state.chat_history)
74
+ self.state.round_nb = observation.round_nb
75
+
76
+ return action, act_log
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/ipd/ipd_agent.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/ipd/ipd_agent.py
3
+ Summary: Implements the IPD agent abstraction used during simulations.
4
+ """
5
+
6
+ import copy
7
+ import json
8
+ import random
9
+ import re
10
+ from collections.abc import Callable
11
+ from copy import deepcopy
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Dict, List, Optional, Tuple, Union
14
+
15
+ from mllm.markov_games.agent import Agent
16
+ from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
17
+
18
+
19
+ @dataclass
20
+ class IPDAgentState:
21
+ """
22
+ Tracks retry count, round index, and chat history for a single IPD agent.
23
+ """
24
+
25
+ nb_retries: int
26
+ round_nb: int
27
+ chat_counter: int
28
+ chat_history: List[ChatTurn]
29
+
30
+
31
+ @dataclass
32
+ class IPDAgent(Agent):
33
+ seed: int
34
+ agent_id: str
35
+ agent_name: str
36
+ policy: Callable[[List[Dict]], str]
37
+ intro_prompt: str # Introduction prompt explaining the game rules
38
+ goal_prompt: str # Prompt explaining the agent's goal
39
+ strategy_prompt: str # Prompt suggesting a strategy to the agent
40
+ max_errors: int # Maximum number of errors allowed before default action
41
+ allow_reasoning: bool # Whether to allow reasoning in the response
42
+ max_reasoning_chars: int # Maximum number of characters for reasoning
43
+ cooperate_string: str # string parsed as playing cooperate by simulation
44
+ defect_string: str # string parsed as playing defect by simulation
45
+
46
+ def __post_init__(self):
47
+ self.state = IPDAgentState(
48
+ nb_retries=0, round_nb=0, chat_counter=0, chat_history=[]
49
+ )
50
+
51
+ async def act(self, observation) -> Tuple[Any, AgentActLog]:
52
+ """
53
+ Run the LLM policy conversation until a valid cooperate/defect action is produced.
54
+ """
55
+
56
+ action = None
57
+ action_is_ready = False
58
+ round_nb = observation.round_nb
59
+
60
+ # If it's the first round, we need to send the intro prompt
61
+ if round_nb == 0 and self.state.chat_counter == 0:
62
+ self.state.chat_history.append(
63
+ ChatTurn(
64
+ agent_id=self.agent_id,
65
+ role="user",
66
+ content=self.intro_prompt,
67
+ is_state_end=True,
68
+ )
69
+ )
70
+
71
+ # If new round
72
+ if round_nb > self.state.round_nb:
73
+ coagent_action = observation.last_coagent_move
74
+ user_message = f"Last round, the other agent played {coagent_action}."
75
+ self.state.chat_history.append(
76
+ ChatTurn(
77
+ agent_id=self.agent_id,
78
+ role="user",
79
+ content=user_message,
80
+ is_state_end=True,
81
+ )
82
+ )
83
+
84
+ # If not new round, try to get valid action from policy
85
+ output_chat_turn: ChatTurn = await self.policy(
86
+ state=self.state.chat_history,
87
+ agent_id=self.agent_id,
88
+ regex=f"({self.cooperate_string}|{self.defect_string})",
89
+ )
90
+ self.state.chat_history.append(output_chat_turn)
91
+ action = output_chat_turn.content
92
+
93
+ agent_step_log = AgentActLog(
94
+ chat_turns=self.state.chat_history[self.state.chat_counter :], info=None
95
+ )
96
+ self.state.chat_counter = len(self.state.chat_history)
97
+ self.state.round_nb = round_nb
98
+
99
+ return action, agent_step_log
100
+
101
+ def get_safe_copy(self):
102
+ """
103
+ Return a safe copy of the agent.
104
+ """
105
+ agent_copy = copy.copy(self)
106
+ agent_copy.state = copy.deepcopy(self.state)
107
+ return agent_copy
108
+
109
+ def reset(self):
110
+ self.state = IPDAgentState()
111
+ raise NotImplementedError
112
+
113
+ def render(self):
114
+ pass
115
+
116
+ def close(self):
117
+ pass
118
+
119
+ def get_agent_info(self):
120
+ pass
src_code_for_reproducibility/markov_games/ipd/ipd_simulation.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/ipd/ipd_simulation.py
3
+ Summary: Runs Iterated Prisoner's Dilemma simulations under the Markov-game API.
4
+ """
5
+
6
+ import copy
7
+ import random
8
+ from dataclasses import dataclass
9
+ from typing import Any, Dict, List, Optional, Tuple
10
+
11
+ import numpy as np
12
+
13
+ from mllm.markov_games.markov_game import Simulation
14
+ from mllm.markov_games.rollout_tree import SimulationStepLog
15
+ from mllm.utils.get_coagent_id import get_coagent_id
16
+
17
+
18
+ @dataclass
19
+ class IPDState:
20
+ """
21
+ State of the Iterated Prisoner's Dilemma game.
22
+ """
23
+
24
+ round_nb: int = 0
25
+ done: bool = False
26
+ last_moves: Dict[str, str] | None = None
27
+
28
+
29
+ @dataclass
30
+ class IPDObs:
31
+ """
32
+ Observation in Iterated Prisoner's Dilemma game.
33
+ """
34
+
35
+ round_nb: int
36
+ last_coagent_move: str | None
37
+
38
+
39
+ class IPD(Simulation):
40
+ """
41
+ Iterated Prisoner's Dilemma simulation following the standard.
42
+
43
+ In each round of the game, two agents simultaneously choose to either cooperate (C) or defect (D).
44
+ The payoffs are as follows:
45
+ - If both cooperate: Both receive the "reward" (usually 3 points)
46
+ - If both defect: Both receive the "punishment" (usually 1 point)
47
+ - If one cooperates and one defects: The defector receives the "temptation" (usually 5 points)
48
+ and the cooperator receives the "sucker" payoff (usually 0 points)
49
+
50
+ The game is played for a specified number of rounds.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ agent_ids: List[str],
56
+ agent_names: List[str],
57
+ seed: int,
58
+ rounds_per_game: int,
59
+ reward: float, # Both cooperate
60
+ punishment: float, # Both defect
61
+ temptation: float, # Defector's reward when other cooperates
62
+ sucker: float, # Cooperator's reward when other defects
63
+ cooperate_actions: List[str],
64
+ defect_actions: List[str],
65
+ ):
66
+ self.agent_ids = agent_ids
67
+ self.agent_names = agent_names
68
+ self.seed = seed
69
+ self.rounds_per_game = rounds_per_game
70
+ self.reward = reward
71
+ self.punishment = punishment
72
+ self.temptation = temptation
73
+ self.sucker = sucker
74
+ self.cooperate_actions = cooperate_actions
75
+ self.defect_actions = defect_actions
76
+ self.state = IPDState()
77
+
78
+ def step(self, actions: Dict[str, str]) -> Tuple[bool, SimulationStepLog]:
79
+ """
80
+ Take a step in the environment using the provided actions.
81
+ Here, the observations are just the states of the game.
82
+
83
+ Args:
84
+ actions (dict): A dictionary where keys are agent identifiers and values are actions ('C' or 'D').
85
+
86
+ Returns:
87
+ observations (dict): A dictionary where keys are agent identifiers and values are observations.
88
+ done (bool): Whether the episode has ended.
89
+ info (dict): Additional information about the environment.
90
+ """
91
+
92
+ # Calculate rewards using payoff matrix
93
+ agent0_action = actions[self.agent_ids[0]]
94
+ agent1_action = actions[self.agent_ids[1]]
95
+
96
+ # Normalize actions to standard cooperate/defect/gibberish format
97
+ def normalize_action(action):
98
+ if action in self.cooperate_actions:
99
+ return "C"
100
+ elif action in self.defect_actions:
101
+ return "D"
102
+ else:
103
+ return "D"
104
+
105
+ norm_action0 = normalize_action(agent0_action)
106
+ norm_action1 = normalize_action(agent1_action)
107
+
108
+ payoffs = {
109
+ ("C", "C"): [self.reward, self.reward],
110
+ ("C", "D"): [self.sucker, self.temptation],
111
+ ("D", "C"): [self.temptation, self.sucker],
112
+ ("D", "D"): [self.punishment, self.punishment],
113
+ }
114
+
115
+ round_rewards = {
116
+ self.agent_ids[0]: payoffs[(norm_action0, norm_action1)][0],
117
+ self.agent_ids[1]: payoffs[(norm_action0, norm_action1)][1],
118
+ }
119
+
120
+ # Update game state
121
+ self.state.round_nb += 1
122
+ self.state.last_moves = copy.deepcopy(actions)
123
+ done = self.state.round_nb >= self.rounds_per_game
124
+ step_log = SimulationStepLog(
125
+ rewards=round_rewards,
126
+ info={
127
+ "actions": {
128
+ self.agent_ids[0]: norm_action0,
129
+ self.agent_ids[1]: norm_action1,
130
+ }
131
+ },
132
+ )
133
+
134
+ return done, step_log
135
+
136
+ def get_obs(self):
137
+ """Returns all agent observations in dict
138
+ Returns:
139
+ observations
140
+ """
141
+ observations = {}
142
+ for agent_id in self.agent_ids:
143
+ observations[agent_id] = self.get_obs_agent(agent_id)
144
+ return observations
145
+
146
+ def get_obs_agent(self, agent_id):
147
+ """Returns observation for agent_id"""
148
+ if self.state.last_moves != None:
149
+ other_id = get_coagent_id(self.agent_ids, agent_id)
150
+ last_coagent_move = self.state.last_moves[other_id]
151
+ else:
152
+ last_coagent_move = None
153
+ obs = IPDObs(round_nb=self.state.round_nb, last_coagent_move=last_coagent_move)
154
+ return obs
155
+
156
+ def reset(self):
157
+ """Returns initial observations and states"""
158
+ self.state = IPDState()
159
+ return self.get_obs()
160
+
161
+ def get_safe_copy(self):
162
+ """
163
+ Return a safe copy of the simulation.
164
+ """
165
+ simulation_copy = copy.copy(self)
166
+ simulation_copy.state = copy.deepcopy(self.state)
167
+ return simulation_copy
src_code_for_reproducibility/markov_games/ipd/ipd_statistics.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/ipd/ipd_statistics.py
3
+ Summary: Computes statistics and summaries for IPD experiments.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Callable, Dict, List, Tuple
9
+
10
+ from mllm.markov_games.rollout_tree import SimulationStepLog
11
+
12
+
13
+ def avg_reward(sl: SimulationStepLog) -> List[Tuple[str, float]]:
14
+ for aid in sl.rewards.keys():
15
+ if "buffer" in str(aid) and "live" not in str(aid):
16
+ return None
17
+ # One value per agent at each step
18
+ rewards_dict = {f"reward-{aid}": float(v) for aid, v in (sl.rewards or {}).items()}
19
+ return [(key, value) for key, value in rewards_dict.items() if value is not None]
20
+
21
+
22
+ stat_functs: list[Callable[[SimulationStepLog], List[Tuple[str, float]]]] = [
23
+ avg_reward,
24
+ ]
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__/dond_simulation.cpython-312.pyc ADDED
Binary file (10.7 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/nego_simulation.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/nego_simulation.py
3
+ Summary: Simulation harness for general negotiation environments.
4
+ """
5
+
6
+ import copy
7
+ from abc import abstractmethod
8
+ from dataclasses import dataclass
9
+ from typing import Any, Dict, List, Tuple
10
+
11
+ from numpy.random import default_rng
12
+
13
+ from mllm.markov_games.rollout_tree import SimulationStepLog
14
+ from mllm.markov_games.simulation import Simulation
15
+ from mllm.utils.get_coagent_id import get_coagent_id
16
+
17
+ AgentId = str
18
+
19
+
20
+ @dataclass
21
+ class Split:
22
+ """Structured proposal describing how many units of each item an agent keeps."""
23
+
24
+ items_given_to_self: Dict[str, int]
25
+
26
+
27
+ @dataclass
28
+ class Message:
29
+ """Single chat utterance exchanged during the negotiation phase."""
30
+
31
+ message: str
32
+
33
+
34
+ @dataclass # gets extended by variants
35
+ class NegotiationState:
36
+ """Full simulator state snapshot shared by all negotiation variants."""
37
+
38
+ round_nb: int
39
+ last_message: str
40
+ current_agent: AgentId
41
+ quantities: Dict[str, int]
42
+ values: Dict[AgentId, Dict[str, float]]
43
+ splits: Dict[AgentId, Split | None]
44
+ nb_messages_sent: Dict[AgentId, int]
45
+ previous_values: Dict[AgentId, Dict[str, float]] | None
46
+ previous_splits: Dict[AgentId, Dict[str, int] | None] | None
47
+ previous_points: Dict[AgentId, float] | None
48
+ previous_quantities: Dict[str, int] | None
49
+ split_phase: bool
50
+
51
+
52
+ @dataclass # gets extended by variants
53
+ class NegotiationObs:
54
+ """Observation presented to agents each turn (base fields; variants extend)."""
55
+
56
+ round_nb: int
57
+ last_message: str
58
+ quota_messages_per_agent_per_round: int
59
+ current_agent: AgentId
60
+ other_agent: str
61
+ quantities: Dict[str, int]
62
+ item_types: List[str]
63
+ value: Dict[str, int]
64
+ split_phase: bool
65
+ last_split_agent: Dict[str, int] | None
66
+ last_value_agent: Dict[str, int] | None
67
+ last_points_agent: float | None
68
+ last_split_coagent: Dict[str, int] | None
69
+ last_value_coagent: Dict[str, int] | None
70
+ last_points_coagent: float | None
71
+ last_quantities: Dict[str, int] | None
72
+
73
+
74
+ def compute_tas_style_rewards(
75
+ agent_ids: List[AgentId],
76
+ values: Dict[AgentId, float],
77
+ splits: Dict[AgentId, Split],
78
+ quantities: Dict[str, int],
79
+ ) -> Dict[AgentId, float]:
80
+ """
81
+ TAS-like reward computation: if sum of proposed coins exceeds max_coins,
82
+ allocate proportionally. Otherwise, use proposed amounts directly.
83
+ Rewards are quantity_kept * per-coin value for each agent.
84
+ """
85
+ a0, a1 = agent_ids[0], agent_ids[1]
86
+ r0, r1 = 0.0, 0.0
87
+
88
+ for item in quantities:
89
+ max_item = quantities[item]
90
+ item_to_self_0 = int(
91
+ (splits[a0].items_given_to_self.get(item, 0))
92
+ if splits[a0] is not None
93
+ else 0
94
+ )
95
+ item_to_self_1 = int(
96
+ (splits[a1].items_given_to_self.get(item, 0))
97
+ if splits[a1] is not None
98
+ else 0
99
+ )
100
+ denom = max(int(max_item), item_to_self_0 + item_to_self_1)
101
+ q0 = float(max_item) * float(item_to_self_0) / float(denom)
102
+ q1 = float(max_item) * float(item_to_self_1) / float(denom)
103
+ if type(values[a0]) is not dict:
104
+ r0 += q0 * float(values[a0])
105
+ r1 += q1 * float(values[a1])
106
+ else:
107
+ r0 += q0 * float(values[a0][item])
108
+ r1 += q1 * float(values[a1][item])
109
+ return {a0: r0, a1: r1}
110
+
111
+
112
+ class NegotiationSimulation(Simulation):
113
+ def __init__(
114
+ self,
115
+ agent_ids: List[AgentId],
116
+ agent_names: List[str],
117
+ seed: int,
118
+ nb_of_rounds: int,
119
+ quota_messages_per_agent_per_round: int,
120
+ item_types: List[str] | None = None,
121
+ ):
122
+ self.seed = seed
123
+ self.rng = default_rng(self.seed)
124
+ self.agent_ids = list(agent_ids)
125
+ self.agent_names = agent_names
126
+ self.agent_id_to_name = {
127
+ agent_id: agent_name for agent_id, agent_name in zip(agent_ids, agent_names)
128
+ }
129
+ self.nb_of_rounds = int(nb_of_rounds)
130
+ self.quota_messages_per_agent_per_round = int(
131
+ quota_messages_per_agent_per_round
132
+ )
133
+ if item_types is not None:
134
+ self.item_types = [item.lower() for item in item_types]
135
+ else:
136
+ self.item_types = ["coins"]
137
+ self.state: NegotiationState | None = None
138
+ self._starting_agent_index = self.rng.choice([0, 1])
139
+ self.reset()
140
+
141
+ def _other(self, agent_id: AgentId) -> AgentId:
142
+ return get_coagent_id(self.agent_ids, agent_id)
143
+
144
+ @abstractmethod
145
+ def set_new_round_of_variant(self):
146
+ """Variant hook: sample new private values / stock before each round."""
147
+ pass
148
+
149
+ @abstractmethod
150
+ def get_info_of_variant(
151
+ self, state: NegotiationState, actions: Dict[AgentId, Any]
152
+ ) -> Dict[str, Any]:
153
+ """Variant hook: populate SimulationStepLog.info with custom diagnostics."""
154
+ pass
155
+
156
+ def step(self, actions: Any) -> Tuple[bool, SimulationStepLog]:
157
+ """
158
+ Returns terminated, step_log
159
+ """
160
+ assert self.state is not None
161
+ current_agent = self.state.current_agent
162
+ a0, a1 = self.agent_ids[0], self.agent_ids[1]
163
+ action = actions.get(current_agent)
164
+
165
+ # Split phase: require both splits in the same timestep
166
+ if self.state.split_phase:
167
+ action_a0 = actions.get(a0)
168
+ action_a1 = actions.get(a1)
169
+ have_both_splits = isinstance(action_a0, Split) and isinstance(
170
+ action_a1, Split
171
+ )
172
+ if not have_both_splits:
173
+ rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
174
+ return False, SimulationStepLog(
175
+ rewards=rewards, info={"type": "waiting_for_splits"}
176
+ )
177
+
178
+ # Record splits
179
+ self.state.splits[a0] = action_a0
180
+ self.state.splits[a1] = action_a1
181
+
182
+ # Compute rewards and end round
183
+ rewards = self.get_rewards(self.state.splits)
184
+
185
+ # Info
186
+ info = self.get_info_of_variant(self.state, actions)
187
+
188
+ # Prepare next round
189
+ # Alternate starting agent
190
+ self.state.round_nb += 1
191
+ self._starting_agent_index = 1 - self._starting_agent_index
192
+ self.state.current_agent = self.agent_ids[self._starting_agent_index]
193
+ self.state.previous_values = copy.deepcopy(self.state.values)
194
+ self.state.previous_splits = copy.deepcopy(self.state.splits)
195
+ self.state.previous_quantities = copy.deepcopy(self.state.quantities)
196
+ self.state.previous_points = copy.deepcopy(rewards)
197
+ self.state.last_message = ""
198
+ self.set_new_round_of_variant() # variant specific
199
+ self.state.splits = {agent_id: None for agent_id in self.agent_ids}
200
+ self.state.nb_messages_sent = {agent_id: 0 for agent_id in self.agent_ids}
201
+ is_last_timestep_in_round = True
202
+ done = self.state.round_nb >= self.nb_of_rounds
203
+
204
+ # Message phase: roll the conversation forward a single turn.
205
+ elif isinstance(action, Message):
206
+ self.state.last_message = action.message
207
+ self.state.nb_messages_sent[current_agent] += 1
208
+
209
+ # Move turn to other agent
210
+ self.state.current_agent = self._other(current_agent)
211
+
212
+ # If both agents have reached their message quota, enter split phase
213
+ if all(
214
+ self.state.nb_messages_sent[agent_id]
215
+ >= self.quota_messages_per_agent_per_round
216
+ for agent_id in self.agent_ids
217
+ ):
218
+ self.state.split_phase = True
219
+ is_last_timestep_in_round = False
220
+ done = False
221
+ rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
222
+ info = {"type": "message"}
223
+
224
+ info[
225
+ "is_last_timestep_in_round"
226
+ ] = is_last_timestep_in_round # Used later to group round timesteps if needed
227
+ return done, SimulationStepLog(rewards=rewards, info=info)
228
+
229
+ def get_obs(self):
230
+ """Returns all agent observations in dict"""
231
+ return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
232
+
233
+ @abstractmethod
234
+ def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
235
+ pass
236
+
237
+ @abstractmethod
238
+ def get_obs_agent(self, agent_id):
239
+ pass
240
+
241
+ def get_state(self):
242
+ return self.state
243
+
244
+ def get_safe_copy(self):
245
+ """Return a safe copy of the simulation."""
246
+ simulation_copy = copy.copy(self)
247
+ simulation_copy.state = copy.deepcopy(self.state)
248
+ return simulation_copy
249
+
250
+ @abstractmethod
251
+ def reset(self) -> dict[AgentId, NegotiationObs]:
252
+ pass
src_code_for_reproducibility/markov_games/negotiation/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/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/models/__pycache__/large_language_model_api.cpython-312.pyc ADDED
Binary file (7.08 kB). View file
 
src_code_for_reproducibility/models/__pycache__/large_language_model_local.cpython-312.pyc ADDED
Binary file (16.5 kB). View file
 
src_code_for_reproducibility/training/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (277 Bytes). View file
 
src_code_for_reproducibility/training/credit_methods.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/credit_methods.py
3
+ Summary: Holds credit-assignment routines for reinforcement learning updates.
4
+ """
5
+
6
+ import torch
7
+
8
+
9
+ def whiten_advantages(advantages: torch.Tensor) -> torch.Tensor:
10
+ """
11
+ Normalize a vector of advantages to zero mean / unit variance (global).
12
+
13
+ Useful for variance reduction before computing gradients.
14
+ """
15
+ whitened_advantages = (advantages - torch.mean(advantages)) / (
16
+ torch.std(advantages) + 1e-9
17
+ )
18
+ return whitened_advantages
19
+
20
+
21
+ def whiten_advantages_time_step_wise(
22
+ advantages: torch.Tensor, # (B, T)
23
+ ) -> torch.Tensor:
24
+ """
25
+ Whiten advantages independently per timestep (column-wise mean/std).
26
+
27
+ Helps when rollout lengths differ or certain positions have very different scales.
28
+ """
29
+ assert advantages.dim() == 2, "Wrong dimensions."
30
+ whitened_advantages_time_step_wise = (
31
+ advantages - advantages.mean(dim=0, keepdim=True)
32
+ ) / (advantages.std(dim=0, keepdim=True) + 1e-9)
33
+ return whitened_advantages_time_step_wise
34
+
35
+
36
+ def get_discounted_state_visitation_credits(
37
+ credits: torch.Tensor, discount_factor: float # (B, T)
38
+ ) -> torch.Tensor:
39
+ """
40
+ Apply geometric discounting to credits so earlier visits count less.
41
+
42
+ Equivalent to per-timestep multiplication by ``gamma^t``.
43
+ """
44
+ return credits * (
45
+ discount_factor ** torch.arange(credits.shape[1], device=credits.device)
46
+ )
47
+
48
+
49
+ def get_discounted_returns(
50
+ rewards: torch.Tensor, # (B, T)
51
+ discount_factor: float,
52
+ ) -> torch.Tensor:
53
+ """
54
+ Computes Monte Carlo discounted returns for a sequence of rewards.
55
+
56
+ Args:
57
+ rewards (torch.Tensor): Array of rewards for each timestep.
58
+
59
+ Returns:
60
+ torch.Tensor: Array of discounted returns.
61
+ """
62
+ assert rewards.dim() == 2, "Wrong dimensions."
63
+ B, T = rewards.shape
64
+ discounted_returns = torch.zeros_like(rewards)
65
+ accumulator = torch.zeros(B, device=rewards.device, dtype=rewards.dtype)
66
+ for t in reversed(range(T)):
67
+ accumulator = rewards[:, t] + discount_factor * accumulator
68
+ discounted_returns[:, t] = accumulator
69
+ return discounted_returns
70
+
71
+
72
+ def get_rloo_credits(credits: torch.Tensor): # (B, S)
73
+ """Compute leave-one-out baselines for a batch of credits."""
74
+ assert credits.dim() == 2, "Wrong dimensions."
75
+ rloo_baselines = torch.zeros_like(credits)
76
+ n = credits.shape[0]
77
+ if n == 1:
78
+ return credits, rloo_baselines
79
+ rloo_baselines = (torch.sum(credits, dim=0, keepdim=True) - credits) / (n - 1)
80
+ rloo_credits = credits - rloo_baselines
81
+ return rloo_credits, rloo_baselines
82
+
83
+
84
+ def get_generalized_advantage_estimates(
85
+ rewards: torch.Tensor, # (B, T)
86
+ value_estimates: torch.Tensor, # (B, T+1)
87
+ discount_factor: float,
88
+ lambda_coef: float,
89
+ ) -> torch.Tensor:
90
+ """
91
+ Compute Generalized Advantage Estimates (GAE).
92
+
93
+ See https://arxiv.org/pdf/1506.02438 for derivation.
94
+ """
95
+ assert rewards.dim() == value_estimates.dim() == 2, "Wrong dimensions."
96
+
97
+ assert (
98
+ rewards.shape[0] == value_estimates.shape[0]
99
+ ), f"Got shapes {rewards.shape} and {value_estimates.shape} of rewards and value estimates."
100
+ assert (
101
+ rewards.shape[1] == value_estimates.shape[1] - 1
102
+ ), f"Got shapes {rewards.shape} and {value_estimates.shape} of rewards and value estimates."
103
+
104
+ T = rewards.shape[1]
105
+ tds = rewards + discount_factor * value_estimates[:, 1:] - value_estimates[:, :-1]
106
+ gaes = torch.zeros_like(tds)
107
+ acc = 0.0
108
+ for t in reversed(range(T)):
109
+ acc = tds[:, t] + lambda_coef * discount_factor * acc
110
+ gaes[:, t] = acc
111
+ return gaes
112
+
113
+
114
+ def get_advantage_alignment_weights(
115
+ advantages: torch.Tensor, # (B, T)
116
+ exclude_k_equals_t: bool,
117
+ gamma: float,
118
+ discount_t: bool,
119
+ ) -> torch.Tensor:
120
+ """
121
+ The advantage alignment credit is calculated as
122
+
123
+ \[
124
+ A^*(s_t, a_t, b_t) = A^1(s_t, a_t, b_t) + \beta \cdot
125
+ \left( \sum_{k < t} \gamma^{t-k} A^1(s_k, a_k, b_k) \right)
126
+ A^2(s_t, a_t, b_t)
127
+ \]
128
+
129
+ Here, the weights are defined as \( \beta \cdot
130
+ \left( \sum_{k < t} \gamma^{t-k} A^1(s_k, a_k, b_k) \)
131
+ """
132
+ T = advantages.shape[1]
133
+ discounted_advantages = advantages * (
134
+ gamma * torch.ones((1, T), device=advantages.device)
135
+ ) ** (-torch.arange(0, T, 1, device=advantages.device))
136
+ if exclude_k_equals_t:
137
+ sub = torch.eye(T, device=advantages.device)
138
+ else:
139
+ sub = torch.zeros((T, T), device=advantages.device)
140
+ # Identity is for \( k < t \), remove for \( k \leq t \)
141
+ ad_align_weights = discounted_advantages @ (
142
+ torch.triu(torch.ones((T, T), device=advantages.device)) - sub
143
+ )
144
+ t_discounts = (gamma * torch.ones((1, T), device=advantages.device)) ** (
145
+ torch.arange(0, T, 1, device=advantages.device)
146
+ )
147
+ ad_align_weights = t_discounts * ad_align_weights
148
+ if discount_t:
149
+ time_discounted_advantages = advantages * (
150
+ gamma * torch.ones((1, T), device=advantages.device)
151
+ ) ** (torch.arange(0, T, 1, device=advantages.device))
152
+ ad_align_weights = ad_align_weights - advantages + time_discounted_advantages
153
+ return ad_align_weights
154
+
155
+
156
+ def get_advantage_alignment_credits(
157
+ a1: torch.Tensor, # (B, S)
158
+ a1_alternative: torch.Tensor, # (B, S, A)
159
+ a2: torch.Tensor, # (B, S)
160
+ exclude_k_equals_t: bool,
161
+ beta: float,
162
+ gamma: float = 1.0,
163
+ use_old_ad_align: bool = False,
164
+ use_sign: bool = False,
165
+ clipping: float | None = None,
166
+ use_time_regularization: bool = False,
167
+ force_coop_first_step: bool = False,
168
+ use_variance_regularization: bool = False,
169
+ rloo_branch: bool = False,
170
+ reuse_baseline: bool = False,
171
+ mean_normalize_ad_align: bool = False,
172
+ whiten_adalign_advantages: bool = False,
173
+ whiten_adalign_advantages_time_step_wise: bool = False,
174
+ discount_t: bool = False,
175
+ ) -> torch.Tensor:
176
+ """
177
+ Calculate the advantage alignment credits with vectorization, as described in https://arxiv.org/abs/2406.14662.
178
+
179
+ Recall that the advantage opponent shaping term of the AdAlign policy gradient is:
180
+ \[
181
+ \beta \mathbb{E}_{\substack{
182
+ \tau \sim \text{Pr}_{\mu}^{\pi^1, \pi^2} \\
183
+ a_t' \sim \pi^1(\cdot \mid s_t)
184
+ }}
185
+ \left[\sum_{t=0}^\infty \gamma^{t}\left( \sum_{k\leq t} A^1(s_k,a^{\prime}_k,b_k) \right) A^{2}(s_t,a_t, b_t)\nabla_{\theta^1}\text{log } \pi^1(a_t|s_t) \right]
186
+ \]
187
+
188
+ This method computes the following:
189
+ \[
190
+ Credit(s_t, a_t, b_t) = \gamma^t \left[ A^1(s_t, a_t, b_t) + \beta \left( \sum_{k\leq t} A^1(s_k,a^{\prime}_k,b_k) \right) A^{2}(s_t,a_t, b_t) \right]
191
+ \]
192
+
193
+ Args:
194
+ a1: Advantages of the main trajectories for the current agent.
195
+ a1_alternative: Advantages of the alternative trajectories for the current agent.
196
+ a2: Advantages of the main trajectories for the other agent.
197
+ discount_factor: Discount factor for the advantage alignment.
198
+ beta: Beta parameter for the advantage alignment.
199
+ gamma: Gamma parameter for the advantage alignment.
200
+ use_sign_in_ad_align: Whether to use sign in the advantage alignment.
201
+
202
+ Returns:
203
+ torch.Tensor: The advantage alignment credits.
204
+ """
205
+
206
+ assert a1.dim() == a2.dim() == 2, "Advantages must be of shape (B, S)"
207
+ if a1_alternative is not None:
208
+ assert (
209
+ a1_alternative.dim() == 3
210
+ ), "Alternative advantages must be of shape (B, S, A)"
211
+ B, T, A = a1_alternative.shape
212
+ else:
213
+ B, T = a1.shape
214
+ assert a1.shape == a2.shape, "Not the same shape"
215
+
216
+ sub_tensors = {}
217
+
218
+ if use_old_ad_align:
219
+ ad_align_weights = get_advantage_alignment_weights(
220
+ advantages=a1,
221
+ exclude_k_equals_t=exclude_k_equals_t,
222
+ gamma=gamma,
223
+ discount_t=discount_t,
224
+ )
225
+ sub_tensors["ad_align_weights_prev"] = ad_align_weights
226
+ if exclude_k_equals_t:
227
+ ad_align_weights = gamma * ad_align_weights
228
+ else:
229
+ assert a1_alternative is not None, "Alternative advantages must be provided"
230
+ if rloo_branch:
231
+ a1_alternative = torch.cat([a1.unsqueeze(2), a1_alternative], dim=2)
232
+ a1_alternative = a1_alternative.mean(dim=2)
233
+ a1, baseline = get_rloo_credits(a1)
234
+ if reuse_baseline:
235
+ a1_alternative = a1_alternative - baseline
236
+ else:
237
+ a1_alternative, _ = get_rloo_credits(a1_alternative)
238
+ assert a1.shape == a1_alternative.shape, "Not the same shape"
239
+ ad_align_weights = get_advantage_alignment_weights(
240
+ advantages=a1_alternative,
241
+ exclude_k_equals_t=exclude_k_equals_t,
242
+ gamma=gamma,
243
+ )
244
+ sub_tensors["ad_align_weights"] = ad_align_weights
245
+
246
+ # Use sign
247
+ if use_sign:
248
+ assert beta == 1.0, "beta should be 1.0 when using sign"
249
+ positive_signs = ad_align_weights > 0
250
+ negative_signs = ad_align_weights < 0
251
+ ad_align_weights[positive_signs] = 1
252
+ ad_align_weights[negative_signs] = -1
253
+ sub_tensors["ad_align_weights_sign"] = ad_align_weights
254
+ # (rest are 0)
255
+
256
+ ###################
257
+ # Process weights
258
+ ###################
259
+
260
+ # Use clipping
261
+ if clipping not in [0.0, None]:
262
+ upper_mask = ad_align_weights > 1
263
+ lower_mask = ad_align_weights < -1
264
+
265
+ ad_align_weights = torch.clip(
266
+ ad_align_weights,
267
+ -clipping,
268
+ clipping,
269
+ )
270
+ clipping_ratio = (
271
+ torch.sum(upper_mask) + torch.sum(lower_mask)
272
+ ) / upper_mask.size
273
+ sub_tensors["clipped_ad_align_weights"] = ad_align_weights
274
+
275
+ # 1/1+t Regularization
276
+ if use_time_regularization:
277
+ t_values = torch.arange(1, T + 1).to(ad_align_weights.device)
278
+ ad_align_weights = ad_align_weights / t_values
279
+ sub_tensors["time_regularized_ad_align_weights"] = ad_align_weights
280
+
281
+ # Use coop on t=0
282
+ if force_coop_first_step:
283
+ ad_align_weights[:, 0] = 1
284
+ sub_tensors["coop_first_step_ad_align_weights"] = ad_align_weights
285
+
286
+ ####################################
287
+ # Compose elements together
288
+ ####################################
289
+
290
+ opp_shaping_terms = beta * ad_align_weights * a2
291
+ sub_tensors["ad_align_opp_shaping_terms"] = opp_shaping_terms
292
+
293
+ credits = a1 + opp_shaping_terms
294
+ if mean_normalize_ad_align:
295
+ credits = credits - credits.mean(dim=0)
296
+ sub_tensors["mean_normalized_ad_align_credits"] = credits
297
+ if whiten_adalign_advantages:
298
+ credits = (credits - credits.mean()) / (credits.std() + 1e-9)
299
+ sub_tensors["whitened_ad_align_credits"] = credits
300
+ if whiten_adalign_advantages_time_step_wise:
301
+ credits = (credits - credits.mean(dim=0, keepdim=True)) / (
302
+ credits.std(dim=0, keepdim=True) + 1e-9
303
+ )
304
+ sub_tensors["whitened_ad_align_credits_time_step_wise"] = credits
305
+ sub_tensors["final_ad_align_credits"] = credits
306
+
307
+ return credits, sub_tensors
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/resource_context.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/resource_context.py
3
+ Summary: Tracks system resource usage via a context manager.
4
+ """
5
+
6
+ import logging
7
+ import time
8
+ from contextlib import contextmanager
9
+
10
+ import torch
11
+
12
+
13
+ def vram_usage():
14
+ output = ""
15
+ for i in range(torch.cuda.device_count()):
16
+ gpu_memory_allocated = torch.cuda.memory_allocated(i) / (
17
+ 1024**3
18
+ ) # Convert bytes to GB
19
+ gpu_memory_reserved = torch.cuda.memory_reserved(i) / (
20
+ 1024**3
21
+ ) # Convert bytes to GB
22
+ output += f"GPU {i}: Memory Allocated: {gpu_memory_allocated:.2f} GB, Memory Reserved: {gpu_memory_reserved:.2f} GB"
23
+ return output
24
+
25
+
26
+ def ram_usage():
27
+ import psutil
28
+
29
+ process = psutil.Process()
30
+ memory_info = process.memory_info()
31
+ ram_used = memory_info.rss / (1024**3) # Convert bytes to GB
32
+ return f"RAM Usage: {ram_used:.2f} GB"
33
+
34
+
35
+ @contextmanager
36
+ def resource_logger_context(logger: logging.Logger, task_description: str):
37
+ """
38
+ Context manager to log the resource usage of the current task.
39
+ Args:
40
+ logger: The logger to use to log the resource usage.
41
+ task_description: The description of the task to log.
42
+ Returns:
43
+ None
44
+ """
45
+ try:
46
+ initial_time = time.time()
47
+ # Assume CUDA is available and use device 0 only
48
+ total_mem_bytes = torch.cuda.get_device_properties(0).total_memory
49
+ initial_total_bytes = torch.cuda.memory_allocated(
50
+ 0
51
+ ) + torch.cuda.memory_reserved(0)
52
+ torch.cuda.reset_peak_memory_stats(0)
53
+ yield None
54
+ finally:
55
+ final_time = time.time()
56
+ # Ensure kernels within the block are accounted for
57
+ torch.cuda.synchronize()
58
+
59
+ # Compute metrics
60
+ final_allocated_bytes = torch.cuda.memory_allocated(0)
61
+ final_reserved_bytes = torch.cuda.memory_reserved(0)
62
+ final_total_bytes = final_allocated_bytes + final_reserved_bytes
63
+
64
+ delta_vram_percent_total = (
65
+ 100 * (final_total_bytes - initial_total_bytes) / total_mem_bytes
66
+ if total_mem_bytes
67
+ else 0.0
68
+ )
69
+ current_percent_vram_taken = (
70
+ 100 * final_total_bytes / total_mem_bytes if total_mem_bytes else 0.0
71
+ )
72
+ block_peak_percent = (
73
+ 100 * torch.cuda.max_memory_allocated(0) / total_mem_bytes
74
+ if total_mem_bytes
75
+ else 0.0
76
+ )
77
+ delta_time_str = time.strftime(
78
+ "%H:%M:%S", time.gmtime(final_time - initial_time)
79
+ )
80
+
81
+ logger.info(
82
+ f"For task: {task_description}, ΔVRAM % (total): {delta_vram_percent_total:.2f}%, Current % of VRAM taken: {current_percent_vram_taken:.2f}%, Block Peak % of device VRAM: {block_peak_percent:.2f}%, ΔTime: {delta_time_str}"
83
+ )
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)