Muqeeth commited on
Commit
6a6ad9b
·
verified ·
1 Parent(s): d2db893

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .hydra/config.yaml +178 -0
  2. .hydra/hydra.yaml +154 -0
  3. .hydra/overrides.yaml +1 -0
  4. seed_42/Qwen/Qwen2.5-7B-Instruct/adapters/README.md +207 -0
  5. seed_42/Qwen/Qwen2.5-7B-Instruct/adapters/agent_adapter/adapter_config.json +46 -0
  6. seed_42/Qwen/Qwen2.5-7B-Instruct/adapters/critic_adapter/adapter_config.json +46 -0
  7. src_code_for_reproducibility/__init__.py +4 -0
  8. src_code_for_reproducibility/chat_utils/__pycache__/apply_template.cpython-312.pyc +0 -0
  9. src_code_for_reproducibility/chat_utils/__pycache__/chat_turn.cpython-312.pyc +0 -0
  10. src_code_for_reproducibility/chat_utils/__pycache__/template_specific.cpython-312.pyc +0 -0
  11. src_code_for_reproducibility/markov_games/__pycache__/__init__.cpython-312.pyc +0 -0
  12. src_code_for_reproducibility/markov_games/__pycache__/agent.cpython-312.pyc +0 -0
  13. src_code_for_reproducibility/markov_games/__pycache__/alternative_actions_runner.cpython-312.pyc +0 -0
  14. src_code_for_reproducibility/markov_games/__pycache__/group_timesteps.cpython-312.pyc +0 -0
  15. src_code_for_reproducibility/markov_games/__pycache__/markov_game.cpython-312.pyc +0 -0
  16. src_code_for_reproducibility/markov_games/__pycache__/mg_utils.cpython-312.pyc +0 -0
  17. src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc +0 -0
  18. src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc +0 -0
  19. src_code_for_reproducibility/markov_games/__pycache__/simulation.cpython-312.pyc +0 -0
  20. src_code_for_reproducibility/markov_games/ipd/Ipd_hard_coded_agents.py +76 -0
  21. src_code_for_reproducibility/markov_games/ipd/__init__.py +11 -0
  22. src_code_for_reproducibility/markov_games/ipd/__pycache__/Ipd_hard_coded_agents.cpython-312.pyc +0 -0
  23. src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc +0 -0
  24. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_agent.cpython-312.pyc +0 -0
  25. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_simulation.cpython-312.pyc +0 -0
  26. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_statistics.cpython-312.pyc +0 -0
  27. src_code_for_reproducibility/markov_games/ipd/ipd_agent.py +120 -0
  28. src_code_for_reproducibility/markov_games/ipd/ipd_simulation.py +167 -0
  29. src_code_for_reproducibility/markov_games/ipd/ipd_statistics.py +24 -0
  30. src_code_for_reproducibility/markov_games/negotiation/README.md +27 -0
  31. src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_agent.cpython-312.pyc +0 -0
  32. src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_simulation.cpython-312.pyc +0 -0
  33. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_agent.cpython-312.pyc +0 -0
  34. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_hard_coded_policies.cpython-312.pyc +0 -0
  35. src_code_for_reproducibility/markov_games/negotiation/__pycache__/nego_simulation.cpython-312.pyc +0 -0
  36. src_code_for_reproducibility/markov_games/negotiation/__pycache__/negotiation_statistics.cpython-312.pyc +0 -0
  37. src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_agent.cpython-312.pyc +0 -0
  38. src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_simulation.cpython-312.pyc +0 -0
  39. src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_agent.cpython-312.pyc +0 -0
  40. src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_simulation.cpython-312.pyc +0 -0
  41. src_code_for_reproducibility/markov_games/negotiation/nego_hard_coded_policies.py +70 -0
  42. src_code_for_reproducibility/markov_games/negotiation/tas_agent.py +118 -0
  43. src_code_for_reproducibility/training/trainer_common.py +1032 -0
  44. src_code_for_reproducibility/utils/get_coagent_id.py +10 -0
  45. src_code_for_reproducibility/utils/get_stochastic_game_lengths.py +33 -0
  46. src_code_for_reproducibility/utils/resource_context.py +83 -0
  47. src_code_for_reproducibility/utils/rollout_tree_chat_htmls.py +1597 -0
  48. src_code_for_reproducibility/utils/stat_pack.py +117 -0
  49. src_code_for_reproducibility/utils/update_start_epoch.py +17 -0
  50. src_code_for_reproducibility/utils/wandb_utils.py +170 -0
.hydra/config.yaml ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ experiment:
2
+ wandb_enabled: true
3
+ nb_epochs: 3000
4
+ nb_matches_per_iteration: 64
5
+ reinit_matches_each_it: true
6
+ checkpoint_every_n_iterations: 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_vanilla_ad_align_no_agent_buffer_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: TrainerAdAlign
127
+ module_pointers:
128
+ policy:
129
+ - base_llm
130
+ - agent_adapter
131
+ policy_optimizer: agent_optimizer
132
+ critic: agent_critic
133
+ critic_optimizer: critic_optimizer
134
+ kwargs:
135
+ entropy_coeff: 0.0
136
+ entropy_topk: null
137
+ entropy_mask_regex: null
138
+ kl_coeff: 0.001
139
+ gradient_clipping: 1.0
140
+ restrict_tokens: null
141
+ mini_batch_size: 1
142
+ use_gradient_checkpointing: false
143
+ temperature: ${temperature}
144
+ device: cuda:0
145
+ use_gae: false
146
+ whiten_advantages: false
147
+ whiten_advantages_time_step_wise: false
148
+ skip_discounted_state_visitation: true
149
+ use_gae_lambda_annealing: false
150
+ gae_lambda_annealing_method: None
151
+ gae_lambda_annealing_method_params: None
152
+ gae_lambda_annealing_limit: 0.95
153
+ discount_factor: 0.9
154
+ use_rloo: true
155
+ enable_tokenwise_logging: false
156
+ pg_loss_normalization: nb_tokens
157
+ truncated_importance_sampling_ratio_cap: 2.0
158
+ reward_normalizing_constant: 100.0
159
+ ad_align_force_coop_first_step: false
160
+ ad_align_clipping: null
161
+ ad_align_gamma: 0.9
162
+ ad_align_exclude_k_equals_t: true
163
+ ad_align_use_sign: false
164
+ ad_align_beta: 1.0
165
+ use_old_ad_align: true
166
+ use_time_regularization: false
167
+ rloo_branch: false
168
+ reuse_baseline: false
169
+ train_on_which_data:
170
+ agent_trainer: ${agent_ids}
171
+ lora_count: 30
172
+ common_agent_kwargs:
173
+ goal: Maximize your total points over the whole game.
174
+ agent_0_id: Alice
175
+ agent_1_id: Bob
176
+ agent_ids:
177
+ - Alice
178
+ - Bob
.hydra/hydra.yaml ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ hydra:
2
+ run:
3
+ dir: ${oc.env:SCRATCH}/llm_negotiation/${now:%Y_%m}/${experiment.name}
4
+ sweep:
5
+ dir: multirun/${now:%Y-%m-%d}/${now:%H-%M-%S}
6
+ subdir: ${hydra.job.num}
7
+ launcher:
8
+ _target_: hydra._internal.core_plugins.basic_launcher.BasicLauncher
9
+ sweeper:
10
+ _target_: hydra._internal.core_plugins.basic_sweeper.BasicSweeper
11
+ max_batch_size: null
12
+ params: null
13
+ help:
14
+ app_name: ${hydra.job.name}
15
+ header: '${hydra.help.app_name} is powered by Hydra.
16
+
17
+ '
18
+ footer: 'Powered by Hydra (https://hydra.cc)
19
+
20
+ Use --hydra-help to view Hydra specific help
21
+
22
+ '
23
+ template: '${hydra.help.header}
24
+
25
+ == Configuration groups ==
26
+
27
+ Compose your configuration from those groups (group=option)
28
+
29
+
30
+ $APP_CONFIG_GROUPS
31
+
32
+
33
+ == Config ==
34
+
35
+ Override anything in the config (foo.bar=value)
36
+
37
+
38
+ $CONFIG
39
+
40
+
41
+ ${hydra.help.footer}
42
+
43
+ '
44
+ hydra_help:
45
+ template: 'Hydra (${hydra.runtime.version})
46
+
47
+ See https://hydra.cc for more info.
48
+
49
+
50
+ == Flags ==
51
+
52
+ $FLAGS_HELP
53
+
54
+
55
+ == Configuration groups ==
56
+
57
+ Compose your configuration from those groups (For example, append hydra/job_logging=disabled
58
+ to command line)
59
+
60
+
61
+ $HYDRA_CONFIG_GROUPS
62
+
63
+
64
+ Use ''--cfg hydra'' to Show the Hydra config.
65
+
66
+ '
67
+ hydra_help: ???
68
+ hydra_logging:
69
+ version: 1
70
+ formatters:
71
+ simple:
72
+ format: '[%(asctime)s][HYDRA] %(message)s'
73
+ handlers:
74
+ console:
75
+ class: logging.StreamHandler
76
+ formatter: simple
77
+ stream: ext://sys.stdout
78
+ root:
79
+ level: INFO
80
+ handlers:
81
+ - console
82
+ loggers:
83
+ logging_example:
84
+ level: DEBUG
85
+ disable_existing_loggers: false
86
+ job_logging:
87
+ version: 1
88
+ formatters:
89
+ simple:
90
+ format: '[%(asctime)s][%(name)s][%(levelname)s] - %(message)s'
91
+ handlers:
92
+ console:
93
+ class: logging.StreamHandler
94
+ formatter: simple
95
+ stream: ext://sys.stdout
96
+ file:
97
+ class: logging.FileHandler
98
+ formatter: simple
99
+ filename: ${hydra.runtime.output_dir}/${hydra.job.name}.log
100
+ root:
101
+ level: INFO
102
+ handlers:
103
+ - console
104
+ - file
105
+ disable_existing_loggers: false
106
+ env: {}
107
+ mode: RUN
108
+ searchpath: []
109
+ callbacks: {}
110
+ output_subdir: .hydra
111
+ overrides:
112
+ hydra:
113
+ - hydra.mode=RUN
114
+ task: []
115
+ job:
116
+ name: run
117
+ chdir: false
118
+ override_dirname: ''
119
+ id: ???
120
+ num: ???
121
+ config_name: split_no_comm_vanilla_ad_align_no_agent_buffer_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_vanilla_ad_align_no_agent_buffer_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/README.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: Qwen/Qwen2.5-7B-Instruct
3
+ library_name: peft
4
+ pipeline_tag: text-generation
5
+ tags:
6
+ - base_model:adapter:Qwen/Qwen2.5-7B-Instruct
7
+ - lora
8
+ - transformers
9
+ ---
10
+
11
+ # Model Card for Model ID
12
+
13
+ <!-- Provide a quick summary of what the model is/does. -->
14
+
15
+
16
+
17
+ ## Model Details
18
+
19
+ ### Model Description
20
+
21
+ <!-- Provide a longer summary of what this model is. -->
22
+
23
+
24
+
25
+ - **Developed by:** [More Information Needed]
26
+ - **Funded by [optional]:** [More Information Needed]
27
+ - **Shared by [optional]:** [More Information Needed]
28
+ - **Model type:** [More Information Needed]
29
+ - **Language(s) (NLP):** [More Information Needed]
30
+ - **License:** [More Information Needed]
31
+ - **Finetuned from model [optional]:** [More Information Needed]
32
+
33
+ ### Model Sources [optional]
34
+
35
+ <!-- Provide the basic links for the model. -->
36
+
37
+ - **Repository:** [More Information Needed]
38
+ - **Paper [optional]:** [More Information Needed]
39
+ - **Demo [optional]:** [More Information Needed]
40
+
41
+ ## Uses
42
+
43
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
44
+
45
+ ### Direct Use
46
+
47
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
48
+
49
+ [More Information Needed]
50
+
51
+ ### Downstream Use [optional]
52
+
53
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
54
+
55
+ [More Information Needed]
56
+
57
+ ### Out-of-Scope Use
58
+
59
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
60
+
61
+ [More Information Needed]
62
+
63
+ ## Bias, Risks, and Limitations
64
+
65
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
66
+
67
+ [More Information Needed]
68
+
69
+ ### Recommendations
70
+
71
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
72
+
73
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
74
+
75
+ ## How to Get Started with the Model
76
+
77
+ Use the code below to get started with the model.
78
+
79
+ [More Information Needed]
80
+
81
+ ## Training Details
82
+
83
+ ### Training Data
84
+
85
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
86
+
87
+ [More Information Needed]
88
+
89
+ ### Training Procedure
90
+
91
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
92
+
93
+ #### Preprocessing [optional]
94
+
95
+ [More Information Needed]
96
+
97
+
98
+ #### Training Hyperparameters
99
+
100
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
101
+
102
+ #### Speeds, Sizes, Times [optional]
103
+
104
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
105
+
106
+ [More Information Needed]
107
+
108
+ ## Evaluation
109
+
110
+ <!-- This section describes the evaluation protocols and provides the results. -->
111
+
112
+ ### Testing Data, Factors & Metrics
113
+
114
+ #### Testing Data
115
+
116
+ <!-- This should link to a Dataset Card if possible. -->
117
+
118
+ [More Information Needed]
119
+
120
+ #### Factors
121
+
122
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
123
+
124
+ [More Information Needed]
125
+
126
+ #### Metrics
127
+
128
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
129
+
130
+ [More Information Needed]
131
+
132
+ ### Results
133
+
134
+ [More Information Needed]
135
+
136
+ #### Summary
137
+
138
+
139
+
140
+ ## Model Examination [optional]
141
+
142
+ <!-- Relevant interpretability work for the model goes here -->
143
+
144
+ [More Information Needed]
145
+
146
+ ## Environmental Impact
147
+
148
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
149
+
150
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
151
+
152
+ - **Hardware Type:** [More Information Needed]
153
+ - **Hours used:** [More Information Needed]
154
+ - **Cloud Provider:** [More Information Needed]
155
+ - **Compute Region:** [More Information Needed]
156
+ - **Carbon Emitted:** [More Information Needed]
157
+
158
+ ## Technical Specifications [optional]
159
+
160
+ ### Model Architecture and Objective
161
+
162
+ [More Information Needed]
163
+
164
+ ### Compute Infrastructure
165
+
166
+ [More Information Needed]
167
+
168
+ #### Hardware
169
+
170
+ [More Information Needed]
171
+
172
+ #### Software
173
+
174
+ [More Information Needed]
175
+
176
+ ## Citation [optional]
177
+
178
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
179
+
180
+ **BibTeX:**
181
+
182
+ [More Information Needed]
183
+
184
+ **APA:**
185
+
186
+ [More Information Needed]
187
+
188
+ ## Glossary [optional]
189
+
190
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
191
+
192
+ [More Information Needed]
193
+
194
+ ## More Information [optional]
195
+
196
+ [More Information Needed]
197
+
198
+ ## Model Card Authors [optional]
199
+
200
+ [More Information Needed]
201
+
202
+ ## Model Card Contact
203
+
204
+ [More Information Needed]
205
+ ### Framework versions
206
+
207
+ - PEFT 0.18.1
seed_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
+ "up_proj",
33
+ "v_proj",
34
+ "o_proj",
35
+ "down_proj",
36
+ "q_proj",
37
+ "gate_proj",
38
+ "k_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
+ "up_proj",
33
+ "v_proj",
34
+ "o_proj",
35
+ "down_proj",
36
+ "q_proj",
37
+ "gate_proj",
38
+ "k_proj"
39
+ ],
40
+ "target_parameters": null,
41
+ "task_type": "CAUSAL_LM",
42
+ "trainable_token_indices": null,
43
+ "use_dora": false,
44
+ "use_qalora": false,
45
+ "use_rslora": false
46
+ }
src_code_for_reproducibility/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ File: mllm/__init__.py
3
+ Summary: Initializes the multi-agent large language model package namespace.
4
+ """
src_code_for_reproducibility/chat_utils/__pycache__/apply_template.cpython-312.pyc ADDED
Binary file (4.13 kB). View file
 
src_code_for_reproducibility/chat_utils/__pycache__/chat_turn.cpython-312.pyc ADDED
Binary file (1.46 kB). View file
 
src_code_for_reproducibility/chat_utils/__pycache__/template_specific.cpython-312.pyc ADDED
Binary file (4.4 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (297 Bytes). View file
 
src_code_for_reproducibility/markov_games/__pycache__/agent.cpython-312.pyc ADDED
Binary file (3.16 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/alternative_actions_runner.cpython-312.pyc ADDED
Binary file (5.43 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/group_timesteps.cpython-312.pyc ADDED
Binary file (6.23 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/markov_game.cpython-312.pyc ADDED
Binary file (10.2 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/mg_utils.cpython-312.pyc ADDED
Binary file (4.07 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc ADDED
Binary file (3.97 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc ADDED
Binary file (1.53 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/simulation.cpython-312.pyc ADDED
Binary file (4.25 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_hard_coded_policies.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/nego_hard_coded_policies.py
3
+ Summary: Provides deterministic negotiation policies for testing and baselines.
4
+ """
5
+
6
+ import asyncio
7
+ from typing import Any, Optional, Tuple
8
+
9
+ from mllm.markov_games.negotiation.nego_agent import NegotiationAgent
10
+ from mllm.markov_games.negotiation.nego_simulation import Split
11
+ from mllm.markov_games.negotiation.no_press_nego_agent import NoPressAgent
12
+ from mllm.markov_games.negotiation.no_press_nego_simulation import NoPressObs
13
+ from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
14
+
15
+
16
+ class HardCodedNegoWelfareMaximizingPolicy(NoPressAgent):
17
+ async def act(self, observation: NoPressObs) -> Tuple[Any, AgentActLog]:
18
+ """
19
+ Policy that gives all of the items to the agent who values them more.
20
+ If the items are equally valued, give them to the agent who values them more.
21
+ """
22
+ quantities = observation.quantities
23
+ my_values = observation.value
24
+ other_values = observation.other_value
25
+
26
+ items_given_to_self = {}
27
+ for item, qty in quantities.items():
28
+ my_v = float(my_values.get(item, 0))
29
+ other_v = float(other_values.get(item, 0))
30
+ if my_v == other_v:
31
+ items_given_to_self[item] = int(qty) / 2
32
+ else:
33
+ items_given_to_self[item] = int(qty if my_v > other_v else 0)
34
+
35
+ action = Split(items_given_to_self=items_given_to_self)
36
+ act_log = AgentActLog(
37
+ chat_turns=[
38
+ ChatTurn(
39
+ agent_id=self.agent_id,
40
+ role="assistant",
41
+ content="Using welfare-maximizing split (all to higher-value agent).",
42
+ is_state_end=True,
43
+ )
44
+ ],
45
+ info=None,
46
+ )
47
+ return action, act_log
48
+
49
+
50
+ class HardCodedNegoGreedyPolicy(NoPressAgent):
51
+ async def act(self, observation: NoPressObs) -> Tuple[Any, AgentActLog]:
52
+ """
53
+ Always gives itself all of the items.
54
+ """
55
+ quantities = observation.quantities
56
+ items_given_to_self = {item: int(qty) for item, qty in quantities.items()}
57
+
58
+ action = Split(items_given_to_self=items_given_to_self)
59
+ act_log = AgentActLog(
60
+ chat_turns=[
61
+ ChatTurn(
62
+ agent_id=self.agent_id,
63
+ role="assistant",
64
+ content="Using greedy split (keep all items).",
65
+ is_state_end=True,
66
+ )
67
+ ],
68
+ info=None,
69
+ )
70
+ return action, act_log
src_code_for_reproducibility/markov_games/negotiation/tas_agent.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/tas_agent.py
3
+ Summary: Agent implementation for Take-and-Split negotiations.
4
+ """
5
+
6
+ from mllm.markov_games.negotiation.nego_agent import NegotiationAgent
7
+ from mllm.markov_games.negotiation.nego_simulation import Split
8
+ from mllm.markov_games.negotiation.tas_simulation import TrustAndSplitObs
9
+
10
+
11
+ class TrustAndSplitAgent(NegotiationAgent):
12
+ """Prompt/template wrapper for the classic multi-item Take-and-Split benchmark."""
13
+
14
+ def __init__(self, num_message_chars, *args, **kwargs):
15
+ self.num_message_chars = num_message_chars
16
+ super().__init__(*args, **kwargs)
17
+ self.intro_prompt = (
18
+ "Welcome to an iterated game. You are {agent}. The other agent is {other_agent}.\n"
19
+ "Setup:\n"
20
+ "1. The game has multiple independent rounds.\n"
21
+ "2. In each round, there are multiple items to split between the two agents.\n"
22
+ "3. Both agents are assigned a per-item value between 1 and 20 (inclusive) in each round.\n"
23
+ "4. You can only observe your own per-item values.\n"
24
+ "5. Because assignments are random, both agents are equally likely to have same expected per-item value.\n"
25
+ "\n"
26
+ "Protocol:\n"
27
+ "1. At the start of the round, one agent begins the conversation. The starting role alternates each round.\n"
28
+ "2. Agents exchange a short chat ({quota_messages_per_agent_per_round} messages per round per agent) to negotiate how to split the item.\n"
29
+ " - Use this chat to communicate your private per-item value to make informed proposals.\n"
30
+ "3. After the chat, both agents simultaneously propose the amount of each item they will keep.\n"
31
+ "4. If the total sum of proposals is less than or equal to the item quantity, both agents receive their proposed amounts.\n"
32
+ "5. If the total sum of proposals exceeds the item quantity, they are allocated proportionally.\n"
33
+ "6. Your points for the round = (amount you receive per item) x (your per-item value for that round), added across all items.\n"
34
+ "7. Points are accumulated across rounds.\n"
35
+ "Your goal: {goal}\n"
36
+ )
37
+ self.new_round_prompt = (
38
+ "A New Round Begins\n"
39
+ "The items to split are {quantities}.\n"
40
+ "Your per-item values are {value}."
41
+ )
42
+ self.last_round_prompt = (
43
+ "Last Round Summary:\n"
44
+ " - Items to split: {last_quantities}\n"
45
+ " - Your per-item values: {last_value_agent}\n"
46
+ " - {other_agent}'s per-item values: {last_value_coagent}\n"
47
+ " - You proposed: {last_split_agent}\n"
48
+ " - You earned: {last_points_agent} points\n"
49
+ " - {other_agent} proposed: {last_split_coagent}\n"
50
+ " - {other_agent} earned: {last_points_coagent} points\n"
51
+ " - Round Complete.\n"
52
+ )
53
+ self.send_split_prompt = (
54
+ "Message quota is finished for this round.\n"
55
+ "{other_agent} has finalized their proposal.\n"
56
+ "Submit your finalization now\n"
57
+ "Respond with {proposal_style2}"
58
+ )
59
+ # self.wait_for_message_prompt = "Wait for {other_agent} to send a message..."
60
+ self.wait_for_message_prompt = ""
61
+ self.last_message_prompt = "{other_agent} said: {last_message}"
62
+ # self.send_message_prompt = (
63
+ # f"Send your message now (max {self.num_message_chars} chars)."
64
+ # )
65
+ self.send_message_prompt = f"Send your message now in <message>...</message> (<={self.num_message_chars} chars)."
66
+
67
+ def get_message_regex(self, observation: TrustAndSplitObs) -> str:
68
+ """Constrain chat to bounded XML tags for stable parsing."""
69
+ return rf"<message>[\s\S]{{0,{self.num_message_chars}}}</message>"
70
+
71
+ # def get_message_regex(self, observation: TrustAndSplitObs) -> str:
72
+ # return rf"(?s).{{0,{self.num_message_chars}}}"
73
+
74
+ def get_split_regex(self, observation: TrustAndSplitObs) -> str:
75
+ """Allow natural-language item names while still returning machine-parsable XML."""
76
+ items = list(observation.quantities.keys())
77
+ # Accept both singular and plural forms
78
+ item_pattern = "|".join(
79
+ [f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?" for item in items]
80
+ )
81
+ regex = rf"(?i)<items_to_self> ?((?:\s*(?P<num>(10|[0-9]))\s*(?P<item>{item_pattern})\s*,?)+) ?</items_to_self>"
82
+ return regex
83
+
84
+ def get_split_action(
85
+ self, policy_output: str, observation: TrustAndSplitObs
86
+ ) -> Split:
87
+ """Convert human-readable allocation text back into canonical item IDs."""
88
+ items = list(observation.quantities.keys())
89
+ import re as _re
90
+
91
+ split_regex = self.get_split_regex(observation)
92
+ items_given_to_self = {item: 0 for item in items}
93
+ m = _re.match(split_regex, policy_output.strip())
94
+ if m:
95
+ # Find all (number, item) pairs
96
+ item_pattern = "|".join(
97
+ [
98
+ f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?"
99
+ for item in items
100
+ ]
101
+ )
102
+ inner_regex = rf"(?i)(10|[0-9])\s*({item_pattern})"
103
+
104
+ def normalize_item_name(item_str):
105
+ for orig in items:
106
+ if item_str.lower() == orig.lower():
107
+ return orig
108
+ if orig.endswith("s") and item_str.lower() == orig[:-1].lower():
109
+ return orig
110
+ if (
111
+ not orig.endswith("s")
112
+ and item_str.lower() == orig.lower() + "s"
113
+ ):
114
+ return orig
115
+
116
+ for num, item in _re.findall(inner_regex, m.group(1)):
117
+ items_given_to_self[normalize_item_name(item)] = int(num)
118
+ return Split(items_given_to_self=items_given_to_self)
src_code_for_reproducibility/training/trainer_common.py ADDED
@@ -0,0 +1,1032 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/trainer_common.py
3
+ Summary: Shared trainer utilities, base classes, and gradient helpers.
4
+ """
5
+
6
+ import logging
7
+ import os
8
+ import pickle
9
+ import sys
10
+ from abc import ABC, abstractmethod
11
+ from typing import Callable, Literal, Union
12
+
13
+ import numpy as np
14
+ import torch
15
+ import torch.nn.functional as F
16
+ from accelerate import Accelerator
17
+ from pandas._libs.tslibs.offsets import CBMonthBegin
18
+ from peft import LoraConfig
19
+ from torch.nn.utils.rnn import pad_sequence
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer
21
+
22
+ from mllm.markov_games.rollout_tree import *
23
+ from mllm.markov_games.rollout_tree import RolloutTreeRootNode
24
+ from mllm.training.annealing_methods import sigmoid_annealing
25
+ from mllm.training.credit_methods import (
26
+ get_discounted_returns,
27
+ get_generalized_advantage_estimates,
28
+ get_rloo_credits,
29
+ whiten_advantages,
30
+ whiten_advantages_time_step_wise,
31
+ )
32
+ from mllm.training.tally_metrics import Tally
33
+ from mllm.training.tally_rollout import RolloutTally, RolloutTallyItem
34
+ from mllm.training.tally_tokenwise import ContextualizedTokenwiseTally
35
+ from mllm.training.tokenize_chats import *
36
+ from mllm.training.tokenize_chats import process_training_chat
37
+ from mllm.training.training_data_utils import *
38
+ from mllm.training.training_data_utils import (
39
+ TrainingBatch,
40
+ TrajectoryBatch,
41
+ get_tokenwise_credits,
42
+ )
43
+ from mllm.utils.resource_context import resource_logger_context
44
+
45
+ logger = logging.getLogger(__name__)
46
+ logger.addHandler(logging.StreamHandler(sys.stdout))
47
+
48
+
49
+ @dataclass
50
+ class TrainerAnnealingState:
51
+ annealing_step_counter: int = 0
52
+
53
+
54
+ class BaseTrainer(ABC):
55
+ """
56
+ Shared scaffolding for policy-gradient trainers (optimizer wiring, logging, etc.).
57
+
58
+ Subclasses implement `set_agent_trajectory_data` / `share_advantage_data`
59
+ to plug in algorithm-specific behavior.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ policy: AutoModelForCausalLM,
65
+ policy_optimizer: torch.optim.Optimizer,
66
+ critic: Union[AutoModelForCausalLM, None],
67
+ critic_optimizer: Union[torch.optim.Optimizer, None],
68
+ tokenizer: AutoTokenizer,
69
+ lr_scheduler: torch.optim.lr_scheduler.LRScheduler,
70
+ critic_lr_scheduler: Union[torch.optim.lr_scheduler.LRScheduler, None],
71
+ ######################################################################
72
+ entropy_coeff: float,
73
+ entropy_topk: int,
74
+ entropy_mask_regex: Union[str, None],
75
+ kl_coeff: float,
76
+ gradient_clipping: Union[float, None],
77
+ restrict_tokens: Union[list[str], None],
78
+ mini_batch_size: int,
79
+ use_gradient_checkpointing: bool,
80
+ temperature: float,
81
+ device: str,
82
+ whiten_advantages: bool,
83
+ whiten_advantages_time_step_wise: bool,
84
+ use_gae: bool,
85
+ use_gae_lambda_annealing: bool,
86
+ gae_lambda_annealing_limit: float,
87
+ gae_lambda_annealing_method: Literal["sigmoid_annealing"],
88
+ gae_lambda_annealing_method_params: dict,
89
+ pg_loss_normalization: Literal["batch", "nb_tokens"],
90
+ use_rloo: bool,
91
+ skip_discounted_state_visitation: bool,
92
+ discount_factor: float,
93
+ enable_tokenwise_logging: bool,
94
+ save_path: str,
95
+ reward_normalizing_constant: float = 1.0,
96
+ critic_loss_type: Literal["mse", "huber"] = "huber",
97
+ exploration_prompts_to_remove: list[str] = [],
98
+ filter_higher_refprob_tokens_kl: bool = False,
99
+ truncated_importance_sampling_ratio_cap: float = 0.0,
100
+ importance_sampling_strategy: Literal[
101
+ "per_token", "per_sequence"
102
+ ] = "per_token",
103
+ no_rloo_grouping: bool = False,
104
+ ):
105
+ """
106
+ Initialize the REINFORCE trainer with reward shaping for multi-agent or single-agent training.
107
+
108
+ Args:
109
+ model (AutoModelForCausalLM): The main policy model.
110
+ tokenizer (AutoTokenizer): Tokenizer for the model.
111
+ optimizer (torch.optim.Optimizer): Optimizer for the policy model.
112
+ lr_scheduler (torch.optim.lr_scheduler.LRScheduler): Learning rate scheduler for the policy model.
113
+ critic (AutoModelForCausalLM or None): Critic model for value estimation (optional).
114
+ critic_optimizer (torch.optim.Optimizer or None): Optimizer for the critic model (optional).
115
+ critic_lr_scheduler (torch.optim.lr_scheduler.LRScheduler or None): LR scheduler for the critic (optional).
116
+ config (RtConfig): Configuration object for training.
117
+ """
118
+ self.tokenizer = tokenizer
119
+ # self.tokenizer.padding_side = "left" # needed for flash attention
120
+ if self.tokenizer.pad_token_id is None:
121
+ self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
122
+ self.lr_scheduler = lr_scheduler
123
+ self.accelerator = Accelerator()
124
+ (
125
+ self.policy,
126
+ self.policy_optimizer,
127
+ self.critic,
128
+ self.critic_optimizer,
129
+ ) = self.accelerator.prepare(policy, policy_optimizer, critic, critic_optimizer)
130
+
131
+ self.critic_lr_scheduler = critic_lr_scheduler
132
+ self.tally = Tally()
133
+
134
+ if use_gradient_checkpointing == True:
135
+ self.policy.gradient_checkpointing_enable(dict(use_reentrant=False))
136
+ if critic is not None:
137
+ self.critic.gradient_checkpointing_enable(dict(use_reentrant=False))
138
+
139
+ self.save_path = save_path
140
+
141
+ # Load trainer state if it exists
142
+ self.trainer_annealing_state_path = os.path.join(
143
+ self.save_path, "trainer_annealing_state.pkl"
144
+ )
145
+ if os.path.exists(self.trainer_annealing_state_path):
146
+ logger.info(
147
+ f"Loading trainer state from {self.trainer_annealing_state_path}"
148
+ )
149
+ self.trainer_annealing_state = pickle.load(
150
+ open(self.trainer_annealing_state_path, "rb")
151
+ )
152
+ else:
153
+ self.trainer_annealing_state = TrainerAnnealingState()
154
+
155
+ # Load policy optimizer state if it exists
156
+ self.policy_optimizer_path = os.path.join(
157
+ self.save_path, "policy_optimizer_state.pt"
158
+ )
159
+ if os.path.exists(self.policy_optimizer_path):
160
+ logger.info(
161
+ f"Loading policy optimizer state from {self.policy_optimizer_path}"
162
+ )
163
+ self.policy_optimizer.load_state_dict(
164
+ torch.load(self.policy_optimizer_path)
165
+ )
166
+
167
+ # Load critic optimizer state if it exists
168
+ self.critic_optimizer_path = os.path.join(
169
+ self.save_path, "critic_optimizer_state.pt"
170
+ )
171
+ if (
172
+ os.path.exists(self.critic_optimizer_path)
173
+ and self.critic_optimizer is not None
174
+ ):
175
+ logger.info(
176
+ f"Loading critic optimizer state from {self.critic_optimizer_path}"
177
+ )
178
+ self.critic_optimizer.load_state_dict(
179
+ torch.load(self.critic_optimizer_path)
180
+ )
181
+ self.device = self.accelerator.device
182
+ self.entropy_coeff = entropy_coeff
183
+ self.entropy_topk = entropy_topk
184
+ self.entropy_mask_regex = entropy_mask_regex
185
+ self.kl_coeff = kl_coeff
186
+ self.gradient_clipping = gradient_clipping
187
+ self.restrict_tokens = restrict_tokens
188
+ self.mini_batch_size = mini_batch_size
189
+ self.use_gradient_checkpointing = use_gradient_checkpointing
190
+ self.temperature = temperature
191
+ self.use_gae = use_gae
192
+ self.whiten_advantages = whiten_advantages
193
+ self.whiten_advantages_time_step_wise = whiten_advantages_time_step_wise
194
+ self.use_rloo = use_rloo
195
+ self.skip_discounted_state_visitation = skip_discounted_state_visitation
196
+ self.use_gae_lambda_annealing = use_gae_lambda_annealing
197
+ self.gae_lambda_annealing_limit = gae_lambda_annealing_limit
198
+ if use_gae_lambda_annealing:
199
+ self.gae_lambda_annealing_method: Callable[
200
+ [int], float
201
+ ] = lambda step: eval(gae_lambda_annealing_method)(
202
+ step=step, **gae_lambda_annealing_method_params
203
+ )
204
+ self.discount_factor = discount_factor
205
+ self.enable_tokenwise_logging = enable_tokenwise_logging
206
+ self.reward_normalizing_constant = reward_normalizing_constant
207
+ self.pg_loss_normalization = pg_loss_normalization
208
+ self.critic_loss_type = critic_loss_type
209
+ self.exploration_prompts_to_remove = exploration_prompts_to_remove
210
+ # Common containers used by all trainers
211
+ self.training_data: dict = {}
212
+ self.debug_path_list: list[str] = []
213
+ self.policy_gradient_data = None
214
+ self.tally = Tally()
215
+ self.rollout_tally = RolloutTally()
216
+ self.tokenwise_tally: Union[ContextualizedTokenwiseTally, None] = None
217
+ self.filter_higher_refprob_tokens_kl = filter_higher_refprob_tokens_kl
218
+ self.truncated_importance_sampling_ratio_cap = (
219
+ truncated_importance_sampling_ratio_cap
220
+ )
221
+ self.importance_sampling_strategy = importance_sampling_strategy
222
+ self.no_rloo_grouping = no_rloo_grouping
223
+
224
+ def mask_non_restricted_token_logits(self, logits: torch.Tensor) -> torch.Tensor:
225
+ """
226
+ Masks logits so that only allowed tokens (as specified in config.restrict_tokens)
227
+ and the EOS token are active.
228
+ All other logits are set to -inf, effectively removing them from the softmax.
229
+
230
+ Args:
231
+ logits (torch.Tensor): The logits tensor of shape (B, S, V).
232
+
233
+ Returns:
234
+ torch.Tensor: The masked logits tensor.
235
+ """
236
+ # Gradients flow only through the kept logits; masking is recomputed per batch for clarity.
237
+
238
+ if self.restrict_tokens is not None:
239
+ allowed_token_ids = []
240
+ for token in self.restrict_tokens:
241
+ token_ids = self.tokenizer(token, add_special_tokens=False)["input_ids"]
242
+ allowed_token_ids.append(token_ids[0])
243
+ allowed_token_ids.append(
244
+ self.tokenizer.eos_token_id
245
+ ) # This token should always be active
246
+ allowed_token_ids = torch.tensor(allowed_token_ids, device=logits.device)
247
+ # Mask log_probs and probs to only allowed tokens
248
+ mask = torch.zeros_like(logits).bool() # (B, S, V)
249
+ mask[..., allowed_token_ids] = True
250
+ logits = torch.where(
251
+ mask,
252
+ logits,
253
+ torch.tensor(-float("inf"), device=logits.device),
254
+ )
255
+
256
+ return logits
257
+
258
+ def apply_reinforce_step(
259
+ self,
260
+ training_batch: TrainingBatch,
261
+ ) -> None:
262
+ """
263
+ Applies a single REINFORCE policy gradient step using the provided batch of rollouts.
264
+ Handles batching, loss computation (including entropy and KL regularization), gradient accumulation, and optimizer step.
265
+ Optionally logs various metrics and statistics.
266
+
267
+ Args:
268
+ paths (list[str]): List of game complete file paths for each rollout.
269
+ contexts (list[torch.Tensor]): List of context tensors for each rollout.
270
+ credits (list[torch.Tensor]): List of credit tensors (rewards/advantages) for each rollout.
271
+ action_masks (list[torch.Tensor]): List of action mask tensors for each rollout.
272
+ """
273
+ with resource_logger_context(logger, "Apply reinforce step"):
274
+ self.policy.train()
275
+ mb_size = self.mini_batch_size
276
+ nb_rollouts = len(training_batch)
277
+
278
+ # Initialize running mean logs
279
+ running_mean_logs = {
280
+ "rl_objective": 0.0,
281
+ "policy_gradient_loss": 0.0,
282
+ "policy_gradient_norm": 0.0,
283
+ "log_probs": 0.0,
284
+ "credits": 0.0,
285
+ "entropy": 0.0,
286
+ "engine_log_probs_diff_clampfrac": 0.0,
287
+ "tis_imp_ratio": 0.0,
288
+ "ref_log_probs_diff_clampfrac": 0.0,
289
+ "higher_refprob_frac": 0.0,
290
+ "tis_imp_ratio_clampfrac": 0.0,
291
+ }
292
+ if self.entropy_coeff != 0.0:
293
+ running_mean_logs["entropy"] = 0.0
294
+ if self.kl_coeff != 0.0:
295
+ running_mean_logs["kl_divergence"] = 0.0
296
+
297
+ # Get total number of tokens generated
298
+ total_tokens_generated = 0
299
+ for att_mask in training_batch.batch_action_mask:
300
+ total_tokens_generated += att_mask.sum()
301
+
302
+ # Obtain loss normalization
303
+ if self.pg_loss_normalization == "nb_tokens":
304
+ normalization_factor = total_tokens_generated
305
+ elif self.pg_loss_normalization == "batch":
306
+ normalization_factor = np.ceil(nb_rollouts / mb_size).astype(int)
307
+ else:
308
+ raise ValueError(
309
+ f"Invalid pg_loss_normalization: {self.pg_loss_normalization}"
310
+ )
311
+
312
+ # Gradient accumulation for each mini-batch
313
+ for mb in range(0, nb_rollouts, mb_size):
314
+ logger.info(f"Processing mini-batch {mb} of {nb_rollouts}")
315
+ loss = 0.0
316
+ training_mb = training_batch[mb : mb + mb_size]
317
+ training_mb = training_mb.get_padded_tensors()
318
+ training_mb.to(self.device)
319
+ (
320
+ tokens_mb,
321
+ action_mask_mb,
322
+ entropy_mask_mb,
323
+ credits_mb,
324
+ engine_log_probs_mb,
325
+ timesteps_mb,
326
+ ) = (
327
+ training_mb.batch_input_ids,
328
+ training_mb.batch_action_mask,
329
+ training_mb.batch_entropy_mask,
330
+ training_mb.batch_credits,
331
+ training_mb.batch_engine_log_probs,
332
+ training_mb.batch_timesteps,
333
+ )
334
+
335
+ # Next token prediction
336
+ contexts_mb = tokens_mb[:, :-1]
337
+ shifted_contexts_mb = tokens_mb[:, 1:]
338
+ action_mask_mb = action_mask_mb[:, 1:]
339
+ entropy_mask_mb = entropy_mask_mb[:, 1:]
340
+ credits_mb = credits_mb[:, 1:]
341
+ engine_log_probs_mb = engine_log_probs_mb[:, 1:]
342
+ timesteps_mb = timesteps_mb[:, 1:]
343
+
344
+ if self.enable_tokenwise_logging:
345
+ self.tokenwise_tally.set_action_mask(action_mask=action_mask_mb)
346
+ self.tokenwise_tally.set_range(range=(mb, mb + mb_size))
347
+ self.tokenwise_tally.add_contexts(contexts=contexts_mb)
348
+ self.tokenwise_tally.add_data(
349
+ metric_id="next_token",
350
+ metrics=shifted_contexts_mb,
351
+ to_tids=True,
352
+ )
353
+ self.tokenwise_tally.add_data(
354
+ metric_id="entropy_mask",
355
+ metrics=entropy_mask_mb,
356
+ )
357
+
358
+ if self.enable_tokenwise_logging:
359
+ self.tokenwise_tally.add_data(
360
+ metric_id="next_token_credit", metrics=credits_mb
361
+ )
362
+
363
+ # Forward pass + cast to FP-32 for higher prec. Causal LM attention masks are implicit;
364
+ # wire up a custom mask here only if the policy deviates from standard autoregressive behavior.
365
+ logits = self.policy(input_ids=contexts_mb)[0] # (B, S, V)
366
+
367
+ # Mask non-restricted tokens
368
+ if self.restrict_tokens is not None:
369
+ logits = self.mask_non_restricted_token_logits(logits)
370
+
371
+ logits /= self.temperature # (B, S, V)
372
+
373
+ # Compute new log probabilities
374
+ log_probs = F.log_softmax(logits, dim=-1) # (B, S, V)
375
+
376
+ # Get log probabilities of actions taken during rollouts
377
+ action_log_probs = log_probs.gather(
378
+ dim=-1, index=shifted_contexts_mb.unsqueeze(-1)
379
+ ).squeeze(
380
+ -1
381
+ ) # (B, S)
382
+ if self.pg_loss_normalization == "batch":
383
+ den_running_mean = action_mask_mb.sum() * normalization_factor
384
+ else:
385
+ den_running_mean = normalization_factor
386
+ running_mean_logs["log_probs"] += (
387
+ action_log_probs * action_mask_mb
388
+ ).sum().item() / den_running_mean
389
+ running_mean_logs["credits"] += (
390
+ credits_mb * action_mask_mb
391
+ ).sum().item() / den_running_mean
392
+
393
+ if self.enable_tokenwise_logging:
394
+ self.tokenwise_tally.add_data(
395
+ metric_id="next_token_log_prob",
396
+ metrics=action_log_probs,
397
+ )
398
+ self.tokenwise_tally.add_data(
399
+ metric_id="engine_next_token_log_prob",
400
+ metrics=engine_log_probs_mb,
401
+ )
402
+ self.tokenwise_tally.add_data(
403
+ metric_id="next_token_prob",
404
+ metrics=torch.exp(action_log_probs),
405
+ )
406
+ top_k_indices = torch.topk(logits, k=5, dim=-1).indices
407
+ self.tokenwise_tally.add_data(
408
+ metric_id=f"top_{5}_tids",
409
+ metrics=top_k_indices,
410
+ to_tids=True,
411
+ )
412
+ self.tokenwise_tally.add_data(
413
+ metric_id=f"top_{5}_probs",
414
+ metrics=torch.exp(log_probs).gather(
415
+ dim=-1, index=top_k_indices
416
+ ),
417
+ )
418
+
419
+ rewarded_action_log_probs = (
420
+ action_mask_mb * credits_mb * action_log_probs
421
+ )
422
+ # (B, S)
423
+ INVALID_LOGPROB = 1.0
424
+ CLAMP_VALUE = 40.0
425
+ masked_action_log_probs = torch.masked_fill(
426
+ action_log_probs, ~action_mask_mb, INVALID_LOGPROB
427
+ )
428
+ masked_engine_log_probs = torch.masked_fill(
429
+ engine_log_probs_mb, ~action_mask_mb, INVALID_LOGPROB
430
+ )
431
+ with torch.no_grad():
432
+ action_engine_log_probs_diff = (
433
+ masked_action_log_probs - masked_engine_log_probs
434
+ ).clamp(-CLAMP_VALUE, CLAMP_VALUE)
435
+ running_mean_logs["engine_log_probs_diff_clampfrac"] += (
436
+ action_engine_log_probs_diff.abs()
437
+ .eq(CLAMP_VALUE)
438
+ .float()
439
+ .sum()
440
+ .item()
441
+ / den_running_mean
442
+ )
443
+ if self.importance_sampling_strategy == "per_sequence":
444
+ tis_imp_ratio = torch.zeros_like(action_engine_log_probs_diff)
445
+ for mb_idx in range(action_engine_log_probs_diff.shape[0]):
446
+ valid_token_mask = action_mask_mb[mb_idx]
447
+ timestep_ids = timesteps_mb[mb_idx][valid_token_mask]
448
+ timestep_logprob_diffs = action_engine_log_probs_diff[mb_idx][
449
+ valid_token_mask
450
+ ]
451
+ max_timestep = int(timestep_ids.max().item()) + 1
452
+ timestep_sums = torch.zeros(
453
+ max_timestep,
454
+ device=action_engine_log_probs_diff.device,
455
+ dtype=action_engine_log_probs_diff.dtype,
456
+ )
457
+ timestep_sums.scatter_add_(
458
+ 0, timestep_ids, timestep_logprob_diffs
459
+ )
460
+ timestep_ratios = torch.exp(timestep_sums)
461
+ tis_imp_ratio[
462
+ mb_idx, valid_token_mask
463
+ ] = timestep_ratios.gather(0, timestep_ids)
464
+ else:
465
+ tis_imp_ratio = torch.exp(action_engine_log_probs_diff)
466
+ running_mean_logs["tis_imp_ratio"] += (
467
+ tis_imp_ratio * action_mask_mb
468
+ ).sum().item() / den_running_mean
469
+ if self.truncated_importance_sampling_ratio_cap > 0.0:
470
+ tis_imp_ratio = torch.clamp(
471
+ tis_imp_ratio, max=self.truncated_importance_sampling_ratio_cap
472
+ )
473
+ running_mean_logs["tis_imp_ratio_clampfrac"] += (
474
+ tis_imp_ratio.eq(self.truncated_importance_sampling_ratio_cap)
475
+ .float()
476
+ .sum()
477
+ .item()
478
+ ) / den_running_mean
479
+ rewarded_action_log_probs = (
480
+ rewarded_action_log_probs * tis_imp_ratio
481
+ )
482
+
483
+ if self.enable_tokenwise_logging:
484
+ self.tokenwise_tally.add_data(
485
+ metric_id="next_token_clogπ",
486
+ metrics=rewarded_action_log_probs,
487
+ )
488
+
489
+ # Add value term to loss
490
+ if self.pg_loss_normalization == "batch":
491
+ nb_act_tokens = action_mask_mb.sum()
492
+ mb_value = -rewarded_action_log_probs.sum() / nb_act_tokens
493
+ else:
494
+ mb_value = -rewarded_action_log_probs.sum()
495
+
496
+ loss += mb_value
497
+ running_mean_logs["rl_objective"] += mb_value.item() / den_running_mean
498
+
499
+ # -------------------------------------------------
500
+ # Entropy Regularization
501
+ # -------------------------------------------------
502
+ # Only apply entropy on distribution defined over most probable tokens
503
+ if self.entropy_topk is not None:
504
+ top_k_indices = torch.topk(
505
+ logits, k=self.entropy_topk, dim=-1
506
+ ).indices
507
+ entropy_logits = logits.gather(dim=-1, index=top_k_indices)
508
+ else:
509
+ entropy_logits = logits
510
+
511
+ token_entropy_terms = -F.softmax(
512
+ entropy_logits, dim=-1
513
+ ) * F.log_softmax(
514
+ entropy_logits, dim=-1
515
+ ) # (B, S, T)
516
+ token_entropy_terms *= (
517
+ action_mask_mb[:, :, None] * entropy_mask_mb[:, :, None]
518
+ ) # only get loss on specific action tokens
519
+
520
+ mb_entropy = token_entropy_terms.sum(dim=-1)
521
+
522
+ if self.enable_tokenwise_logging:
523
+ self.tokenwise_tally.add_data(
524
+ metric_id="entropy",
525
+ metrics=mb_entropy,
526
+ )
527
+ if self.pg_loss_normalization == "batch":
528
+ nb_act_tokens = action_mask_mb.sum()
529
+ mb_entropy = -mb_entropy.sum() / nb_act_tokens
530
+ else:
531
+ mb_entropy = -mb_entropy.sum()
532
+ running_mean_logs["entropy"] += -mb_entropy.item() / den_running_mean
533
+ if self.entropy_coeff != 0.0:
534
+ mb_entropy *= self.entropy_coeff
535
+ loss += mb_entropy
536
+
537
+ # -------------------------------------------------
538
+ # KL-DIVERGENCE
539
+ # -------------------------------------------------
540
+ if self.kl_coeff != 0.0:
541
+ ref_model_logits = self.policy.get_base_model_logits(contexts_mb)
542
+ ref_model_logits = ref_model_logits / self.temperature
543
+ # (B, S, V)
544
+ ref_model_logits = self.mask_non_restricted_token_logits(
545
+ logits=ref_model_logits
546
+ )
547
+ # (B, S, V)
548
+ ref_model_log_probs = F.log_softmax(ref_model_logits, dim=-1)
549
+ # (B, S, V)
550
+ ref_model_action_log_probs = ref_model_log_probs.gather(
551
+ dim=-1, index=shifted_contexts_mb.unsqueeze(-1)
552
+ ).squeeze(
553
+ -1
554
+ ) # (B,S)
555
+ # Approximating KL Divergence (see refs in docstring)
556
+ # Ref 1: http://joschu.net/blog/kl-approx.html
557
+ # Ref 2: https://github.dev/huggingface/trl/blob/main/trl/trainer/grpo_trainer.py#L1332
558
+ masked_ref_model_action_log_probs = torch.masked_fill(
559
+ ref_model_action_log_probs, ~action_mask_mb, INVALID_LOGPROB
560
+ )
561
+ action_log_probs_diff = (
562
+ masked_ref_model_action_log_probs - masked_action_log_probs
563
+ ).clamp(-CLAMP_VALUE, CLAMP_VALUE)
564
+ running_mean_logs["ref_log_probs_diff_clampfrac"] += (
565
+ action_log_probs_diff.abs().eq(CLAMP_VALUE).float().sum().item()
566
+ / den_running_mean
567
+ )
568
+ if self.filter_higher_refprob_tokens_kl:
569
+ higher_refprob_tokens_mask = action_log_probs_diff > 0.0
570
+ running_mean_logs["higher_refprob_frac"] += (
571
+ higher_refprob_tokens_mask.sum().item() / den_running_mean
572
+ )
573
+ action_log_probs_diff = action_log_probs_diff * (
574
+ ~higher_refprob_tokens_mask
575
+ )
576
+ kl_div = torch.expm1(action_log_probs_diff) - action_log_probs_diff
577
+ kl_div *= action_mask_mb # We only care about KLD of action tokens
578
+ if self.truncated_importance_sampling_ratio_cap > 0.0:
579
+ kl_div = kl_div * tis_imp_ratio
580
+ kl_div *= self.kl_coeff
581
+ if self.enable_tokenwise_logging:
582
+ self.tokenwise_tally.add_data(
583
+ metric_id="ref_model_next_token_log_prob",
584
+ metrics=ref_model_action_log_probs,
585
+ )
586
+ self.tokenwise_tally.add_data(
587
+ metric_id="kl_divergence",
588
+ metrics=kl_div,
589
+ )
590
+
591
+ if self.pg_loss_normalization == "batch":
592
+ nb_act_tokens = action_mask_mb.sum()
593
+ mb_kl = kl_div.sum() / nb_act_tokens
594
+ else:
595
+ mb_kl = kl_div.sum()
596
+ running_mean_logs["kl_divergence"] += (
597
+ mb_kl.item() / den_running_mean
598
+ )
599
+ loss += mb_kl
600
+
601
+ # Accumulate gradient
602
+ running_mean_logs["policy_gradient_loss"] += (
603
+ loss.item() / den_running_mean
604
+ )
605
+ loss /= normalization_factor
606
+ self.accelerator.backward(loss)
607
+
608
+ # ensure gpu memory is freed
609
+ del training_mb
610
+ del log_probs
611
+ del logits
612
+ del loss
613
+ del action_log_probs
614
+ del rewarded_action_log_probs
615
+
616
+ logger.info(
617
+ f"Accumulated the policy gradient loss for {total_tokens_generated} tokens."
618
+ )
619
+
620
+ # Clip gradients and take step
621
+ if self.gradient_clipping is not None:
622
+ grad_norm = self.accelerator.clip_grad_norm_(
623
+ self.policy.parameters(), self.gradient_clipping
624
+ )
625
+ running_mean_logs["policy_gradient_norm"] += grad_norm.item()
626
+
627
+ # Take step
628
+ self.policy_optimizer.step()
629
+ self.policy_optimizer.zero_grad()
630
+
631
+ # Store logs
632
+ for key, value in running_mean_logs.items():
633
+ self.tally.add_metric(path=key, metric=value)
634
+
635
+ # Clear accelerator state so we do not accumulate references between optimizer steps.
636
+ self.accelerator.clear(self.policy, self.policy_optimizer)
637
+ import gc
638
+
639
+ gc.collect()
640
+ torch.cuda.empty_cache()
641
+ return running_mean_logs
642
+
643
+ def get_advantages_with_critic_gradient_accumulation(
644
+ self, trajectories: TrajectoryBatch, critic_loss_scaling_factor: float = 2.0
645
+ ) -> torch.FloatTensor:
646
+ """
647
+ Compute (and optionally whiten) advantages while training the critic in mini-batches.
648
+ Uses GAE if enabled, otherwise uses Monte Carlo returns.
649
+ Optionally trains the critic if GAE is used.
650
+ Returns:
651
+ advantages: NestedFloatTensors
652
+ """
653
+
654
+ mb_size = self.mini_batch_size
655
+ batch_size = trajectories.rollout_ids.shape[0]
656
+ agent_id = trajectories.agent_ids[0]
657
+ batch_rewards = trajectories.batch_rewards
658
+
659
+ ######################################
660
+ # use critic for advantage estimation
661
+ ######################################
662
+ if self.use_gae:
663
+ if "buffer" in agent_id:
664
+ self.critic.eval()
665
+ training = False
666
+ else:
667
+ self.critic.train()
668
+ training = True
669
+ advantages = []
670
+ # critic_loss_scaling_factor comes learning single critic for two agents
671
+ normalization_factor = (
672
+ np.ceil(batch_size / mb_size).astype(int) * critic_loss_scaling_factor
673
+ )
674
+ # For each minibatch
675
+ for mb in range(0, batch_size, mb_size):
676
+ trajectory_mb = trajectories[mb : mb + mb_size]
677
+ trajectory_mb.to(self.device)
678
+ rewards_mb = trajectory_mb.batch_rewards
679
+ (
680
+ tokens_mb,
681
+ state_ends_mask_mb,
682
+ timestep_counts,
683
+ ) = trajectory_mb.get_padded_tensors_for_critic()
684
+ # critic causal attention up to end flags
685
+ if training:
686
+ vals_estimate_full = self.critic(tokens_mb)
687
+ else:
688
+ with torch.no_grad():
689
+ vals_estimate_full = self.critic(tokens_mb)
690
+
691
+ # if vals_estimate_full.dim() == 3:
692
+ # vals_estimate_full = vals_estimate_full.squeeze(-1)
693
+
694
+ # Select only positions where states end, per sample → list of (jT,)
695
+ B = tokens_mb.shape[0]
696
+ vals_list = [
697
+ vals_estimate_full[b][state_ends_mask_mb[b]] for b in range(B)
698
+ ]
699
+
700
+ # Pad to (B, max_jT) = (B, S)
701
+ vals_estimate_mb = pad_sequence(
702
+ vals_list, batch_first=True, padding_value=0.0
703
+ )
704
+ dtype = vals_estimate_mb.dtype
705
+ rewards_mb = pad_sequence(
706
+ rewards_mb, batch_first=True, padding_value=0.0
707
+ ).to(
708
+ dtype=dtype
709
+ ) # (B, S)
710
+ self.rollout_tally.add_metric(
711
+ path=["batch_rewards"],
712
+ rollout_tally_item=RolloutTallyItem(
713
+ crn_ids=trajectory_mb.crn_ids,
714
+ rollout_ids=trajectory_mb.rollout_ids,
715
+ agent_ids=trajectory_mb.agent_ids,
716
+ metric_matrix=rewards_mb,
717
+ ),
718
+ )
719
+ if self.reward_normalizing_constant != 1.0:
720
+ rewards_mb /= self.reward_normalizing_constant
721
+
722
+ det_vals_estimate_mb = vals_estimate_mb.detach() # (B, max_jT)
723
+ self.rollout_tally.add_metric(
724
+ path=["mb_value_estimates_critic"],
725
+ rollout_tally_item=RolloutTallyItem(
726
+ crn_ids=trajectory_mb.crn_ids,
727
+ rollout_ids=trajectory_mb.rollout_ids,
728
+ agent_ids=trajectory_mb.agent_ids,
729
+ metric_matrix=det_vals_estimate_mb,
730
+ ),
731
+ )
732
+
733
+ # Append a 0 value to the end of the value estimates
734
+ if det_vals_estimate_mb.shape[1] == rewards_mb.shape[1]:
735
+ Bsize = det_vals_estimate_mb.shape[0]
736
+ device = det_vals_estimate_mb.device
737
+ dtype = det_vals_estimate_mb.dtype
738
+ det_vals_estimate_mb = torch.cat(
739
+ [
740
+ det_vals_estimate_mb,
741
+ torch.zeros((Bsize, 1), device=device, dtype=dtype),
742
+ ],
743
+ dim=1,
744
+ ) # (B, max_jT+1)
745
+ else:
746
+ raise ValueError(
747
+ "Incompatible shapes for value estimates and rewards."
748
+ )
749
+
750
+ # Get annealed lambda
751
+ if self.use_gae_lambda_annealing:
752
+ annealing_constant = self.gae_lambda_annealing_method(
753
+ step=self.trainer_annealing_state.annealing_step_counter
754
+ )
755
+ annealed_lambda = (
756
+ self.gae_lambda_annealing_limit * annealing_constant
757
+ )
758
+ self.tally.add_metric(
759
+ path="annealed_lambda", metric=annealed_lambda
760
+ )
761
+ else:
762
+ annealed_lambda = self.gae_lambda_annealing_limit
763
+
764
+ # Get GAE advantages
765
+ gae_advantages = get_generalized_advantage_estimates(
766
+ rewards=rewards_mb,
767
+ value_estimates=det_vals_estimate_mb,
768
+ discount_factor=self.discount_factor,
769
+ lambda_coef=annealed_lambda,
770
+ ) # (B, max_jT)
771
+ self.rollout_tally.add_metric(
772
+ path=["mb_gae_advantages"],
773
+ rollout_tally_item=RolloutTallyItem(
774
+ crn_ids=trajectory_mb.crn_ids,
775
+ rollout_ids=trajectory_mb.rollout_ids,
776
+ agent_ids=trajectory_mb.agent_ids,
777
+ metric_matrix=gae_advantages,
778
+ ),
779
+ )
780
+ if training:
781
+ targets = (
782
+ gae_advantages.to(dtype=dtype) + det_vals_estimate_mb[:, :-1]
783
+ ) # (B, max_jT) # A(s, a, b) + V(s) = Q(s, a, b)
784
+ self.rollout_tally.add_metric(
785
+ path=["mb_targets_critic"],
786
+ rollout_tally_item=RolloutTallyItem(
787
+ crn_ids=trajectory_mb.crn_ids,
788
+ rollout_ids=trajectory_mb.rollout_ids,
789
+ agent_ids=trajectory_mb.agent_ids,
790
+ metric_matrix=targets,
791
+ ),
792
+ )
793
+ if self.critic_loss_type == "mse":
794
+ loss = F.mse_loss(
795
+ input=vals_estimate_mb,
796
+ target=targets,
797
+ )
798
+ elif self.critic_loss_type == "huber":
799
+ loss = F.huber_loss(
800
+ input=vals_estimate_mb,
801
+ target=targets,
802
+ )
803
+ self.tally.add_metric(path=["mb_critic_loss"], metric=loss.item())
804
+ # Accumulate gradient
805
+ loss /= normalization_factor
806
+ self.accelerator.backward(loss)
807
+ del loss
808
+ del targets
809
+ del vals_estimate_mb
810
+ del trajectory_mb
811
+ del vals_estimate_full
812
+
813
+ # Get jagged back using timestep_counts
814
+ advantages.extend(
815
+ [gae_advantages[i, : timestep_counts[i]] for i in range(B)]
816
+ )
817
+
818
+ ######################################
819
+ # use exclusively Monte Carlo returns & rloo for advantage estimation
820
+ ######################################
821
+ else:
822
+ lengths = [len(c) for c in batch_rewards]
823
+ padded_rewards = pad_sequence(
824
+ batch_rewards, batch_first=True, padding_value=0.0
825
+ )
826
+ self.rollout_tally.add_metric(
827
+ path=["mb_rewards"],
828
+ rollout_tally_item=RolloutTallyItem(
829
+ crn_ids=trajectories.crn_ids,
830
+ rollout_ids=trajectories.rollout_ids,
831
+ agent_ids=trajectories.agent_ids,
832
+ metric_matrix=padded_rewards,
833
+ ),
834
+ )
835
+ if self.reward_normalizing_constant != 1.0:
836
+ padded_rewards /= self.reward_normalizing_constant
837
+ padded_advantages = get_discounted_returns(
838
+ rewards=padded_rewards,
839
+ discount_factor=self.discount_factor,
840
+ ) # no baseline for now
841
+ if self.use_rloo:
842
+ is_grouped_by_rng = (
843
+ trajectories.crn_ids.unique().shape[0]
844
+ != trajectories.crn_ids.shape[0]
845
+ )
846
+ if is_grouped_by_rng and not self.no_rloo_grouping:
847
+ for crn_id in trajectories.crn_ids.unique():
848
+ rng_mask = trajectories.crn_ids == crn_id
849
+ rng_advantages = padded_advantages[rng_mask]
850
+ rng_advantages, _ = get_rloo_credits(credits=rng_advantages)
851
+ padded_advantages[rng_mask] = rng_advantages
852
+ else:
853
+ padded_advantages, _ = get_rloo_credits(credits=padded_advantages)
854
+ self.rollout_tally.add_metric(
855
+ path=["mb_rloo_advantages"],
856
+ rollout_tally_item=RolloutTallyItem(
857
+ crn_ids=trajectories.crn_ids,
858
+ rollout_ids=trajectories.rollout_ids,
859
+ agent_ids=trajectories.agent_ids,
860
+ metric_matrix=padded_advantages,
861
+ ),
862
+ )
863
+ advantages = [
864
+ padded_advantages[i, : lengths[i]]
865
+ for i in range(padded_advantages.shape[0])
866
+ ]
867
+
868
+ if self.whiten_advantages_time_step_wise or self.whiten_advantages:
869
+ lengths = [len(c) for c in advantages]
870
+ padded_advantages = pad_sequence(
871
+ advantages, batch_first=True, padding_value=0.0
872
+ )
873
+ if self.whiten_advantages_time_step_wise:
874
+ whitened_padded_advantages = whiten_advantages_time_step_wise(
875
+ padded_advantages
876
+ )
877
+ path = ["mb_whitened_advantages_time_step_wise"]
878
+ elif self.whiten_advantages:
879
+ whitened_padded_advantages = whiten_advantages(padded_advantages)
880
+ path = ["mb_whitened_advantages"]
881
+ self.rollout_tally.add_metric(
882
+ path=path,
883
+ rollout_tally_item=RolloutTallyItem(
884
+ crn_ids=trajectories.crn_ids,
885
+ rollout_ids=trajectories.rollout_ids,
886
+ agent_ids=trajectories.agent_ids,
887
+ metric_matrix=whitened_padded_advantages,
888
+ ),
889
+ )
890
+ advantages = [
891
+ whitened_padded_advantages[i, : lengths[i]]
892
+ for i in range(whitened_padded_advantages.shape[0])
893
+ ]
894
+
895
+ self.trainer_annealing_state.annealing_step_counter += 1
896
+
897
+ return advantages
898
+
899
+ @abstractmethod
900
+ def set_agent_trajectory_data(
901
+ self, agent_id: str, roots: list[RolloutTreeRootNode]
902
+ ) -> None:
903
+ """
904
+ Populate self.training_data for a single agent using the provided rollout trees.
905
+ """
906
+ pass
907
+
908
+ def set_trajectory_data(
909
+ self, roots: list[RolloutTreeRootNode], agent_ids: list[str]
910
+ ) -> None:
911
+ """
912
+ Convenience wrapper to ingest trajectory data for every training agent.
913
+ """
914
+ for agent_id in agent_ids:
915
+ self.set_agent_trajectory_data(agent_id, roots)
916
+
917
+ @abstractmethod
918
+ def share_advantage_data(self) -> list[AdvantagePacket]:
919
+ pass
920
+
921
+ @abstractmethod
922
+ def receive_advantage_data(self, advantage_packets: list[AdvantagePacket]) -> None:
923
+ pass
924
+
925
+ def set_policy_gradient_data(self, agent_ids: list[str]) -> None:
926
+ """
927
+ Reset and rebuild the policy-gradient minibatches before iterating through agents.
928
+ """
929
+ self.policy_gradient_data = None
930
+ for agent_id in agent_ids:
931
+ assert "buffer" not in agent_id, "Buffer agents do not train policy"
932
+ trajectory_batch = self.training_data[agent_id]
933
+ tokenwise_batch_credits = get_tokenwise_credits(
934
+ batch_timesteps=trajectory_batch.batch_timesteps,
935
+ batch_credits=trajectory_batch.batch_credits,
936
+ )
937
+ policy_gradient_data = TrainingBatch(
938
+ rollout_ids=trajectory_batch.rollout_ids,
939
+ batch_input_ids=trajectory_batch.batch_input_ids,
940
+ batch_action_mask=trajectory_batch.batch_action_mask,
941
+ batch_entropy_mask=trajectory_batch.batch_entropy_mask,
942
+ batch_credits=tokenwise_batch_credits,
943
+ batch_engine_log_probs=trajectory_batch.batch_engine_log_probs,
944
+ batch_timesteps=trajectory_batch.batch_timesteps,
945
+ )
946
+ if self.policy_gradient_data is None:
947
+ self.policy_gradient_data = policy_gradient_data
948
+ else:
949
+ self.policy_gradient_data.append(policy_gradient_data)
950
+
951
+ self.training_data = {}
952
+ self.tokenwise_tally = ContextualizedTokenwiseTally(
953
+ tokenizer=self.tokenizer,
954
+ paths=self.debug_path_list,
955
+ )
956
+
957
+ def train(self) -> None:
958
+ """
959
+ Entry point for policy updates: prepare batches, compute gradients, and update parameters.
960
+ """
961
+ assert self.policy_gradient_data is not None, "Policy gradient data is not set"
962
+ if self.critic_optimizer is not None:
963
+ if self.gradient_clipping is not None:
964
+ grad_norm = self.accelerator.clip_grad_norm_(
965
+ self.critic.parameters(), self.gradient_clipping
966
+ )
967
+ self.tally.add_metric(
968
+ path="gradient_norm_critic", metric=grad_norm.item()
969
+ )
970
+ # Take step
971
+ self.critic_optimizer.step()
972
+ self.critic_optimizer.zero_grad()
973
+ self.accelerator.clear(self.critic, self.critic_optimizer)
974
+ import gc
975
+
976
+ gc.collect()
977
+ torch.cuda.empty_cache()
978
+ running_mean_logs = self.apply_reinforce_step(
979
+ training_batch=self.policy_gradient_data
980
+ )
981
+ return running_mean_logs
982
+
983
+ def export_training_tally(self, identifier: str, folder: str) -> None:
984
+ """
985
+ Saves and resets the collected training metrics using the tally object.
986
+ """
987
+ os.makedirs(folder, exist_ok=True)
988
+ self.tally.save(identifier=identifier, folder=folder)
989
+ self.tokenwise_tally.save(
990
+ path=os.path.join(folder, f"{identifier}_tokenwise.csv")
991
+ )
992
+ self.rollout_tally.save(identifier=identifier, folder=folder)
993
+ self.tally.reset()
994
+ self.tokenwise_tally = None
995
+ self.rollout_tally.reset()
996
+ self.debug_path_list = []
997
+
998
+ def export_optimizer_states(self) -> None:
999
+ """
1000
+ Saves the optimizer states for both the main model and critic (if it exists).
1001
+ """
1002
+ try:
1003
+ os.makedirs(self.save_path, exist_ok=True)
1004
+
1005
+ torch.save(self.policy_optimizer.state_dict(), self.policy_optimizer_path)
1006
+ logger.info(f"Saved main optimizer state to {self.policy_optimizer_path}")
1007
+
1008
+ if self.critic_optimizer is not None:
1009
+ torch.save(
1010
+ self.critic_optimizer.state_dict(), self.critic_optimizer_path
1011
+ )
1012
+ logger.info(
1013
+ f"Saved critic optimizer state to {self.critic_optimizer_path}"
1014
+ )
1015
+ except Exception as e:
1016
+ logger.error(f"Error saving optimizer states: {str(e)}")
1017
+ raise
1018
+
1019
+ def export_trainer_annealing_state(self) -> None:
1020
+ """
1021
+ Saves the trainer state.
1022
+ """
1023
+ with open(self.trainer_annealing_state_path, "wb") as f:
1024
+ pickle.dump(self.trainer_annealing_state, f)
1025
+ logger.info(f"Saved trainer state to {self.trainer_annealing_state_path}")
1026
+
1027
+ def export_trainer_states(self) -> None:
1028
+ """
1029
+ Saves the trainer states.
1030
+ """
1031
+ self.export_optimizer_states()
1032
+ self.export_trainer_annealing_state()
src_code_for_reproducibility/utils/get_coagent_id.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/get_coagent_id.py
3
+ Summary: Helper for deriving co-agent identifiers from rollout metadata.
4
+ """
5
+
6
+
7
+ def get_coagent_id(ids: list[str], agent_id: str) -> str | None:
8
+ for id in ids:
9
+ if id != agent_id:
10
+ return id
src_code_for_reproducibility/utils/get_stochastic_game_lengths.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/get_stochastic_game_lengths.py
3
+ Summary: Computes distributions over stochastic game lengths.
4
+ """
5
+
6
+ import numpy as np
7
+
8
+
9
+ def get_stochastic_game_lengths(
10
+ max_length, nb_games, continuation_prob, same_length_batch=False
11
+ ):
12
+ """
13
+ Generates stochastic game lengths based on a geometric distribution.
14
+
15
+ Args:
16
+ max_length (int): The maximum length a game can have.
17
+ nb_games (int): The number of games to generate lengths for.
18
+ continuation_prob (float): The probability of the game continuing after each round.
19
+ same_length_batch (bool): If True, all games will have the same length.
20
+
21
+ Returns:
22
+ Array: An array of game lengths.
23
+ """
24
+ if continuation_prob == 1:
25
+ return [max_length] * nb_games
26
+ if same_length_batch:
27
+ length = np.random.geometric(1 - continuation_prob, 1)
28
+ game_lengths = np.repeat(length, nb_games)
29
+ else:
30
+ game_lengths = np.random.geometric(1 - continuation_prob, nb_games)
31
+
32
+ game_lengths = np.where(game_lengths > max_length, max_length, game_lengths)
33
+ return game_lengths.tolist()
src_code_for_reproducibility/utils/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/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/update_start_epoch.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/update_start_epoch.py
3
+ Summary: Updates persisted start-epoch metadata when resuming runs.
4
+ """
5
+
6
+ import os
7
+
8
+
9
+ # During run, set hydra.run.dir=./outputs/{folder}
10
+ def update_start_epoch(cfg, output_directory):
11
+ if cfg["experiment"]["resume_experiment"]:
12
+ folders = [
13
+ f for f in os.listdir(output_directory) if f.startswith("iteration_")
14
+ ]
15
+ iterations = [int(f.split("_")[1]) for f in folders] if folders else [0]
16
+ cfg["experiment"]["start_epoch"] = max(iterations)
17
+ return None
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)