Muqeeth commited on
Commit
6334f07
·
verified ·
1 Parent(s): f2667d6

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .hydra/config.yaml +183 -0
  2. .hydra/hydra.yaml +154 -0
  3. .hydra/overrides.yaml +1 -0
  4. seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/README.md +207 -0
  5. seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/agent_adapter/adapter_config.json +46 -0
  6. seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/critic_adapter/adapter_config.json +46 -0
  7. seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/fixed_ad_align_adapter/adapter_config.json +46 -0
  8. src_code_for_reproducibility/__init__.py +4 -0
  9. src_code_for_reproducibility/chat_utils/__pycache__/apply_template.cpython-312.pyc +0 -0
  10. src_code_for_reproducibility/chat_utils/__pycache__/chat_turn.cpython-312.pyc +0 -0
  11. src_code_for_reproducibility/chat_utils/__pycache__/template_specific.cpython-312.pyc +0 -0
  12. src_code_for_reproducibility/markov_games/__pycache__/__init__.cpython-312.pyc +0 -0
  13. src_code_for_reproducibility/markov_games/__pycache__/agent.cpython-312.pyc +0 -0
  14. src_code_for_reproducibility/markov_games/__pycache__/alternative_actions_runner.cpython-312.pyc +0 -0
  15. src_code_for_reproducibility/markov_games/__pycache__/group_timesteps.cpython-312.pyc +0 -0
  16. src_code_for_reproducibility/markov_games/__pycache__/linear_runner.cpython-312.pyc +0 -0
  17. src_code_for_reproducibility/markov_games/__pycache__/markov_game.cpython-312.pyc +0 -0
  18. src_code_for_reproducibility/markov_games/__pycache__/mg_utils.cpython-312.pyc +0 -0
  19. src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc +0 -0
  20. src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc +0 -0
  21. src_code_for_reproducibility/markov_games/__pycache__/simulation.cpython-312.pyc +0 -0
  22. src_code_for_reproducibility/markov_games/ipd/Ipd_hard_coded_agents.py +76 -0
  23. src_code_for_reproducibility/markov_games/ipd/__init__.py +11 -0
  24. src_code_for_reproducibility/markov_games/ipd/__pycache__/Ipd_hard_coded_agents.cpython-312.pyc +0 -0
  25. src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc +0 -0
  26. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_agent.cpython-312.pyc +0 -0
  27. src_code_for_reproducibility/markov_games/ipd/__pycache__/ipd_simulation.cpython-312.pyc +0 -0
  28. src_code_for_reproducibility/markov_games/ipd/ipd_agent.py +120 -0
  29. src_code_for_reproducibility/markov_games/ipd/ipd_simulation.py +167 -0
  30. src_code_for_reproducibility/markov_games/ipd/ipd_statistics.py +24 -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/dond_agent.py +75 -0
  42. src_code_for_reproducibility/markov_games/negotiation/dond_simulation.py +176 -0
  43. src_code_for_reproducibility/markov_games/negotiation/nego_simulation.py +252 -0
  44. src_code_for_reproducibility/markov_games/negotiation/no_press_nego_simulation.py +182 -0
  45. src_code_for_reproducibility/markov_games/negotiation/tas_agent.py +118 -0
  46. src_code_for_reproducibility/models/__pycache__/human_policy.cpython-312.pyc +0 -0
  47. src_code_for_reproducibility/models/__pycache__/inference_backend.cpython-312.pyc +0 -0
  48. src_code_for_reproducibility/models/__pycache__/large_language_model_api.cpython-312.pyc +0 -0
  49. src_code_for_reproducibility/utils/resource_context.py +83 -0
  50. src_code_for_reproducibility/utils/rollout_tree_gather_utils.py +314 -0
.hydra/config.yaml ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: 0
10
+ seed_group_size: 8
11
+ train: true
12
+ stat_methods_for_live_wandb: mllm.markov_games.negotiation.negotiation_statistics
13
+ name: tas_rps_adv_margin_vs_fixed_ad_align
14
+ agent_buffer: false
15
+ keep_agent_buffer_count: ${lora_count}
16
+ agent_buffer_recent_k: -1
17
+ use_buffer: false
18
+ logging:
19
+ wandb:
20
+ enabled: false
21
+ project: llm-negotiation
22
+ entity: null
23
+ mode: online
24
+ name: null
25
+ group: null
26
+ tags: []
27
+ notes: null
28
+ temperature: 1.0
29
+ markov_games:
30
+ runner_method_name: LinearRunner
31
+ runner_kwargs: {}
32
+ group_by_round: true
33
+ simulation_class_name: TrustAndSplitRPSSimulation
34
+ simulation_init_args:
35
+ nb_of_rounds: 10
36
+ quota_messages_per_agent_per_round: 1
37
+ alternating_hands: false
38
+ agents:
39
+ 0:
40
+ agent_id: ${agent_0_id}
41
+ agent_name: Alice
42
+ agent_class_name: TrustAndSplitRPSAgent
43
+ policy_id: base_llm/agent_adapter
44
+ init_kwargs:
45
+ goal: Maximize your total points over the whole game.
46
+ num_message_chars: 500
47
+ message_start_end_format: true
48
+ proposal_start_end_format: true
49
+ 1:
50
+ agent_id: ${agent_1_id}
51
+ agent_name: Bob
52
+ agent_class_name: TrustAndSplitRPSAgent
53
+ policy_id: base_llm/fixed_ad_align_adapter
54
+ init_kwargs:
55
+ goal: Maximize your total points over the whole game.
56
+ num_message_chars: 500
57
+ message_start_end_format: true
58
+ proposal_start_end_format: true
59
+ models:
60
+ base_llm:
61
+ class: LeanLocalLLM
62
+ init_args:
63
+ llm_id: base_llm
64
+ model_name: Qwen/Qwen2.5-7B-Instruct
65
+ inference_backend: vllm
66
+ hf_kwargs:
67
+ device_map: auto
68
+ torch_dtype: bfloat16
69
+ max_memory:
70
+ 0: 20GiB
71
+ attn_implementation: flash_attention_2
72
+ inference_backend_init_kwargs:
73
+ enable_lora: true
74
+ seed: ${experiment.base_seed}
75
+ enable_prefix_caching: true
76
+ max_model_len: 10000.0
77
+ gpu_memory_utilization: 0.5
78
+ dtype: bfloat16
79
+ trust_remote_code: true
80
+ max_lora_rank: 32
81
+ enforce_eager: false
82
+ max_loras: ${lora_count}
83
+ max_cpu_loras: ${lora_count}
84
+ enable_sleep_mode: true
85
+ inference_backend_sampling_params:
86
+ temperature: ${temperature}
87
+ top_p: 1.0
88
+ max_tokens: 400
89
+ top_k: -1
90
+ logprobs: 0
91
+ adapter_configs:
92
+ agent_adapter:
93
+ task_type: CAUSAL_LM
94
+ r: 32
95
+ lora_alpha: 64
96
+ lora_dropout: 0.0
97
+ target_modules: all-linear
98
+ critic_adapter:
99
+ task_type: CAUSAL_LM
100
+ r: 32
101
+ lora_alpha: 64
102
+ lora_dropout: 0.0
103
+ target_modules: all-linear
104
+ fixed_ad_align_adapter:
105
+ task_type: CAUSAL_LM
106
+ r: 32
107
+ lora_alpha: 64
108
+ lora_dropout: 0.0
109
+ target_modules: all-linear
110
+ enable_thinking: null
111
+ regex_max_attempts: 3
112
+ initial_adapter_paths:
113
+ fixed_ad_align_adapter: ${fixed_ad_align_adapter_path}
114
+ critics:
115
+ agent_critic:
116
+ module_pointer:
117
+ - base_llm
118
+ - critic_adapter
119
+ optimizers:
120
+ agent_optimizer:
121
+ module_pointer:
122
+ - base_llm
123
+ - agent_adapter
124
+ optimizer_class_name: torch.optim.Adam
125
+ init_args:
126
+ lr: 3.0e-06
127
+ weight_decay: 0.0
128
+ critic_optimizer: null
129
+ trainers:
130
+ agent_trainer:
131
+ class: TrainerNaive
132
+ module_pointers:
133
+ policy:
134
+ - base_llm
135
+ - agent_adapter
136
+ policy_optimizer: agent_optimizer
137
+ critic: agent_critic
138
+ critic_optimizer: critic_optimizer
139
+ kwargs:
140
+ entropy_coeff: 0.0
141
+ entropy_topk: null
142
+ entropy_mask_regex: null
143
+ kl_coeff: 0.001
144
+ gradient_clipping: 1.0
145
+ restrict_tokens: null
146
+ mini_batch_size: 1
147
+ use_gradient_checkpointing: true
148
+ temperature: ${temperature}
149
+ device: cuda:0
150
+ use_gae: false
151
+ whiten_advantages: false
152
+ whiten_advantages_time_step_wise: false
153
+ skip_discounted_state_visitation: true
154
+ use_gae_lambda_annealing: false
155
+ gae_lambda_annealing_method: None
156
+ gae_lambda_annealing_method_params: None
157
+ gae_lambda_annealing_limit: 0.95
158
+ discount_factor: 0.96
159
+ use_rloo: true
160
+ enable_tokenwise_logging: false
161
+ pg_loss_normalization: nb_tokens
162
+ truncated_importance_sampling_ratio_cap: 2.0
163
+ reward_normalizing_constant: 100.0
164
+ reward_agent_id: Alice
165
+ reward_scale: 1.0
166
+ reward_peer_agent_id: Bob
167
+ reward_peer_scale: -1.0
168
+ train_on_which_data:
169
+ agent_trainer:
170
+ - Alice
171
+ lora_count: 30
172
+ common_agent_kwargs:
173
+ goal: Maximize your total points over the whole game.
174
+ num_message_chars: 500
175
+ message_start_end_format: true
176
+ proposal_start_end_format: true
177
+ agent_0_id: Alice
178
+ agent_1_id: Bob
179
+ agent_ids:
180
+ - Alice
181
+ - Bob
182
+ hf_checkpoints_root: ${oc.env:SCRATCH}/llm_negotiation/HF_checkpoints
183
+ fixed_ad_align_adapter_path: ${hf_checkpoints_root}/tas_rps_vanilla_ad_align/seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/agent_adapter
.hydra/hydra.yaml ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ hydra:
2
+ run:
3
+ dir: ${oc.env:SCRATCH}/llm_negotiation/${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: tas_rps_adv_margin_vs_fixed_ad_align.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: /scratch/muqeeth/AdAlignLLM
133
+ config_sources:
134
+ - path: hydra.conf
135
+ schema: pkg
136
+ provider: hydra
137
+ - path: /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/tas_rps_adv_margin_vs_fixed_ad_align
144
+ choices:
145
+ hydra/env: default
146
+ hydra/callbacks: null
147
+ hydra/job_logging: default
148
+ hydra/hydra_logging: default
149
+ hydra/hydra_help: default
150
+ hydra/help: default
151
+ hydra/sweeper: basic
152
+ hydra/launcher: basic
153
+ hydra/output: default
154
+ verbose: false
.hydra/overrides.yaml ADDED
@@ -0,0 +1 @@
 
 
1
+ []
seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/README.md ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: Qwen/Qwen2.5-7B-Instruct
3
+ library_name: peft
4
+ pipeline_tag: text-generation
5
+ tags:
6
+ - base_model:adapter:Qwen/Qwen2.5-7B-Instruct
7
+ - lora
8
+ - transformers
9
+ ---
10
+
11
+ # Model Card for Model ID
12
+
13
+ <!-- Provide a quick summary of what the model is/does. -->
14
+
15
+
16
+
17
+ ## Model Details
18
+
19
+ ### Model Description
20
+
21
+ <!-- Provide a longer summary of what this model is. -->
22
+
23
+
24
+
25
+ - **Developed by:** [More Information Needed]
26
+ - **Funded by [optional]:** [More Information Needed]
27
+ - **Shared by [optional]:** [More Information Needed]
28
+ - **Model type:** [More Information Needed]
29
+ - **Language(s) (NLP):** [More Information Needed]
30
+ - **License:** [More Information Needed]
31
+ - **Finetuned from model [optional]:** [More Information Needed]
32
+
33
+ ### Model Sources [optional]
34
+
35
+ <!-- Provide the basic links for the model. -->
36
+
37
+ - **Repository:** [More Information Needed]
38
+ - **Paper [optional]:** [More Information Needed]
39
+ - **Demo [optional]:** [More Information Needed]
40
+
41
+ ## Uses
42
+
43
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
44
+
45
+ ### Direct Use
46
+
47
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
48
+
49
+ [More Information Needed]
50
+
51
+ ### Downstream Use [optional]
52
+
53
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
54
+
55
+ [More Information Needed]
56
+
57
+ ### Out-of-Scope Use
58
+
59
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
60
+
61
+ [More Information Needed]
62
+
63
+ ## Bias, Risks, and Limitations
64
+
65
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
66
+
67
+ [More Information Needed]
68
+
69
+ ### Recommendations
70
+
71
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
72
+
73
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
74
+
75
+ ## How to Get Started with the Model
76
+
77
+ Use the code below to get started with the model.
78
+
79
+ [More Information Needed]
80
+
81
+ ## Training Details
82
+
83
+ ### Training Data
84
+
85
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
86
+
87
+ [More Information Needed]
88
+
89
+ ### Training Procedure
90
+
91
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
92
+
93
+ #### Preprocessing [optional]
94
+
95
+ [More Information Needed]
96
+
97
+
98
+ #### Training Hyperparameters
99
+
100
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
101
+
102
+ #### Speeds, Sizes, Times [optional]
103
+
104
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
105
+
106
+ [More Information Needed]
107
+
108
+ ## Evaluation
109
+
110
+ <!-- This section describes the evaluation protocols and provides the results. -->
111
+
112
+ ### Testing Data, Factors & Metrics
113
+
114
+ #### Testing Data
115
+
116
+ <!-- This should link to a Dataset Card if possible. -->
117
+
118
+ [More Information Needed]
119
+
120
+ #### Factors
121
+
122
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
123
+
124
+ [More Information Needed]
125
+
126
+ #### Metrics
127
+
128
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
129
+
130
+ [More Information Needed]
131
+
132
+ ### Results
133
+
134
+ [More Information Needed]
135
+
136
+ #### Summary
137
+
138
+
139
+
140
+ ## Model Examination [optional]
141
+
142
+ <!-- Relevant interpretability work for the model goes here -->
143
+
144
+ [More Information Needed]
145
+
146
+ ## Environmental Impact
147
+
148
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
149
+
150
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
151
+
152
+ - **Hardware Type:** [More Information Needed]
153
+ - **Hours used:** [More Information Needed]
154
+ - **Cloud Provider:** [More Information Needed]
155
+ - **Compute Region:** [More Information Needed]
156
+ - **Carbon Emitted:** [More Information Needed]
157
+
158
+ ## Technical Specifications [optional]
159
+
160
+ ### Model Architecture and Objective
161
+
162
+ [More Information Needed]
163
+
164
+ ### Compute Infrastructure
165
+
166
+ [More Information Needed]
167
+
168
+ #### Hardware
169
+
170
+ [More Information Needed]
171
+
172
+ #### Software
173
+
174
+ [More Information Needed]
175
+
176
+ ## Citation [optional]
177
+
178
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
179
+
180
+ **BibTeX:**
181
+
182
+ [More Information Needed]
183
+
184
+ **APA:**
185
+
186
+ [More Information Needed]
187
+
188
+ ## Glossary [optional]
189
+
190
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
191
+
192
+ [More Information Needed]
193
+
194
+ ## More Information [optional]
195
+
196
+ [More Information Needed]
197
+
198
+ ## Model Card Authors [optional]
199
+
200
+ [More Information Needed]
201
+
202
+ ## Model Card Contact
203
+
204
+ [More Information Needed]
205
+ ### Framework versions
206
+
207
+ - PEFT 0.18.1
seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/agent_adapter/adapter_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alora_invocation_tokens": null,
3
+ "alpha_pattern": {},
4
+ "arrow_config": null,
5
+ "auto_mapping": null,
6
+ "base_model_name_or_path": "Qwen/Qwen2.5-7B-Instruct",
7
+ "bias": "none",
8
+ "corda_config": null,
9
+ "ensure_weight_tying": false,
10
+ "eva_config": null,
11
+ "exclude_modules": null,
12
+ "fan_in_fan_out": false,
13
+ "inference_mode": true,
14
+ "init_lora_weights": true,
15
+ "layer_replication": null,
16
+ "layers_pattern": null,
17
+ "layers_to_transform": null,
18
+ "loftq_config": {},
19
+ "lora_alpha": 64,
20
+ "lora_bias": false,
21
+ "lora_dropout": 0.0,
22
+ "megatron_config": null,
23
+ "megatron_core": "megatron.core",
24
+ "modules_to_save": null,
25
+ "peft_type": "LORA",
26
+ "peft_version": "0.18.1",
27
+ "qalora_group_size": 16,
28
+ "r": 32,
29
+ "rank_pattern": {},
30
+ "revision": null,
31
+ "target_modules": [
32
+ "o_proj",
33
+ "v_proj",
34
+ "k_proj",
35
+ "down_proj",
36
+ "up_proj",
37
+ "gate_proj",
38
+ "q_proj"
39
+ ],
40
+ "target_parameters": null,
41
+ "task_type": "CAUSAL_LM",
42
+ "trainable_token_indices": null,
43
+ "use_dora": false,
44
+ "use_qalora": false,
45
+ "use_rslora": false
46
+ }
seed_0/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
+ "o_proj",
33
+ "v_proj",
34
+ "k_proj",
35
+ "down_proj",
36
+ "up_proj",
37
+ "gate_proj",
38
+ "q_proj"
39
+ ],
40
+ "target_parameters": null,
41
+ "task_type": "CAUSAL_LM",
42
+ "trainable_token_indices": null,
43
+ "use_dora": false,
44
+ "use_qalora": false,
45
+ "use_rslora": false
46
+ }
seed_0/Qwen/Qwen2.5-7B-Instruct/adapters/fixed_ad_align_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
+ "o_proj",
33
+ "v_proj",
34
+ "k_proj",
35
+ "down_proj",
36
+ "up_proj",
37
+ "gate_proj",
38
+ "q_proj"
39
+ ],
40
+ "target_parameters": null,
41
+ "task_type": "CAUSAL_LM",
42
+ "trainable_token_indices": null,
43
+ "use_dora": false,
44
+ "use_qalora": false,
45
+ "use_rslora": false
46
+ }
src_code_for_reproducibility/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ File: mllm/__init__.py
3
+ Summary: Initializes the multi-agent large language model package namespace.
4
+ """
src_code_for_reproducibility/chat_utils/__pycache__/apply_template.cpython-312.pyc ADDED
Binary file (4.12 kB). View file
 
src_code_for_reproducibility/chat_utils/__pycache__/chat_turn.cpython-312.pyc ADDED
Binary file (1.45 kB). View file
 
src_code_for_reproducibility/chat_utils/__pycache__/template_specific.cpython-312.pyc ADDED
Binary file (4.39 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (288 Bytes). View file
 
src_code_for_reproducibility/markov_games/__pycache__/agent.cpython-312.pyc ADDED
Binary file (3.15 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/alternative_actions_runner.cpython-312.pyc ADDED
Binary file (5.42 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/group_timesteps.cpython-312.pyc ADDED
Binary file (6.22 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/linear_runner.cpython-312.pyc ADDED
Binary file (1.63 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.06 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/rollout_tree.cpython-312.pyc ADDED
Binary file (3.96 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/run_markov_games.cpython-312.pyc ADDED
Binary file (2.65 kB). View file
 
src_code_for_reproducibility/markov_games/__pycache__/simulation.cpython-312.pyc ADDED
Binary file (4.24 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.04 kB). View file
 
src_code_for_reproducibility/markov_games/ipd/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (426 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.86 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/__pycache__/dond_agent.cpython-312.pyc ADDED
Binary file (4.65 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/dond_simulation.cpython-312.pyc ADDED
Binary file (10.6 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.38 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.2 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_agent.cpython-312.pyc ADDED
Binary file (6.1 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/no_press_nego_simulation.cpython-312.pyc ADDED
Binary file (9.71 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_agent.cpython-312.pyc ADDED
Binary file (6.04 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/__pycache__/tas_rps_simulation.cpython-312.pyc ADDED
Binary file (11.7 kB). View file
 
src_code_for_reproducibility/markov_games/negotiation/dond_agent.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/dond_agent.py
3
+ Summary: Agent implementation for Deal-or-No-Deal style negotiations.
4
+ """
5
+
6
+ import copy
7
+ import re
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass
10
+ from typing import Any, Dict, List, Tuple
11
+
12
+ from mllm.markov_games.agent import Agent
13
+ from mllm.markov_games.negotiation.dond_simulation import DealNoDealObs
14
+ from mllm.markov_games.negotiation.nego_agent import (
15
+ NegotiationAgent,
16
+ NegotiationAgentState,
17
+ )
18
+ from mllm.markov_games.negotiation.nego_simulation import Split
19
+ from mllm.markov_games.rollout_tree import AgentActLog, ChatTurn
20
+
21
+
22
+ class DealNoDealAgent(NegotiationAgent):
23
+ """NegotiationAgent tailored to the Deal-or-No-Deal stock/value revelation rules."""
24
+
25
+ def __init__(
26
+ self,
27
+ *args,
28
+ **kwargs,
29
+ ):
30
+ super().__init__(*args, **kwargs)
31
+ self.intro_prompt = (
32
+ "You are {agent_id}. You are playing an iterated game. "
33
+ "At each round, you and other agent will try to distribute among yourselves items of types {item_types}. "
34
+ "You only know how much you value each item type, but not the other agent's values. "
35
+ "You can communicate with the other agent by sending up to {quota_messages_per_agent_per_round} short messages per round. "
36
+ "Each round, after exchanging messages, you and the other agent will submit a private proposal. "
37
+ "A deal is accepted only if both proposals match exactly and are within stock; otherwise no deal (0 points for both at that round). "
38
+ "The values of the items of the other agent at the previous round are revealed to you after each round. "
39
+ "Your goal is: {goal}."
40
+ )
41
+ self.new_round_prompt = (
42
+ "New round {round_nb}. Items: {stock}. Your values: {values}. "
43
+ )
44
+ self.last_round_prompt = (
45
+ "Last round, other agent's values: {previous_values_coagent}. "
46
+ )
47
+ self.send_split_prompt = "Respond with <split>...</split> where you propose how many items of each type you want to keep."
48
+
49
+ def get_message_regex(self, observation: DealNoDealObs) -> str:
50
+ """Allow short XML messages (<400 chars) between proposal phases."""
51
+ return r"<message>[\s\S]{0,400}</message>"
52
+
53
+ def get_split_regex(self, observation: DealNoDealObs) -> str:
54
+ """Constrain split proposals to per-item XML tags bounded by the current stock."""
55
+ parts = []
56
+ for t in observation.item_types:
57
+ s = int(observation.quantities.get(t, 0))
58
+ allowed = "|".join(str(k) for k in range(0, s + 1))
59
+ rng = f"({allowed})"
60
+ parts.append(rf"<{t}>{rng}</{t}>")
61
+ items_block = "".join(parts)
62
+ return rf"(<split>{items_block}</split>)"
63
+
64
+ def get_split_action(self, policy_output: str, observation: DealNoDealObs) -> Split:
65
+ """Convert the XML proposal into a Split dataclass understood by the simulator."""
66
+ import re as _re
67
+
68
+ allocations: Dict[str, int] = {}
69
+ for t in observation.item_types:
70
+ m = _re.search(rf"<{t}>([0-9]+)</{t}>", policy_output)
71
+ if m:
72
+ allocations[t] = int(m.group(1))
73
+ else:
74
+ allocations[t] = 0
75
+ return Split(items_given_to_self=allocations)
src_code_for_reproducibility/markov_games/negotiation/dond_simulation.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/dond_simulation.py
3
+ Summary: Simulates Deal-or-No-Deal negotiation games and logs rollouts.
4
+ """
5
+
6
+ import copy
7
+ from dataclasses import dataclass
8
+ from typing import Any, Dict, List, Tuple
9
+
10
+ from numpy.random import default_rng
11
+
12
+ from mllm.markov_games.negotiation.nego_simulation import (
13
+ NegotiationObs,
14
+ NegotiationSimulation,
15
+ NegotiationState,
16
+ Split,
17
+ )
18
+ from mllm.markov_games.rollout_tree import SimulationStepLog
19
+ from mllm.utils.get_coagent_id import get_coagent_id
20
+
21
+ AgentId = str
22
+
23
+
24
+ @dataclass
25
+ class DealNoDealState(NegotiationState):
26
+ """NegotiationState with per-agent value tables and item taxonomy."""
27
+
28
+ item_types: List[str]
29
+ values: Dict[AgentId, Dict[str, int]]
30
+
31
+
32
+ @dataclass
33
+ class DealNoDealObs(NegotiationObs):
34
+ """Observation that reveals own values and (lagged) opponent values."""
35
+
36
+ my_values: Dict[str, int]
37
+ item_types: List[str]
38
+ previous_values_coagent: Dict[str, int] | None
39
+
40
+
41
+ def random_partition_integer(rng, total: int, parts: int) -> List[int]:
42
+ """Sample non-negative integers summing to ``total`` across ``parts`` buckets."""
43
+ if parts <= 0:
44
+ return []
45
+ if total <= 0:
46
+ return [0 for _ in range(parts)]
47
+ cuts = sorted(rng.integers(0, total + 1, size=parts - 1).tolist())
48
+ vals = []
49
+ prev = 0
50
+ for c in cuts + [total]:
51
+ vals.append(c - prev)
52
+ prev = c
53
+ return vals
54
+
55
+
56
+ class DealNoDealSimulation(NegotiationSimulation):
57
+ """NegotiationSimulation variant implementing the Rubinstein-style Deal-or-No-Deal."""
58
+
59
+ def __init__(
60
+ self,
61
+ item_types: List[str] = ["books", "hats", "balls"],
62
+ *args,
63
+ **kwargs,
64
+ ):
65
+ super().__init__(item_types=item_types, *args, **kwargs)
66
+ self.reset()
67
+
68
+ def _other(self, agent_id: AgentId) -> AgentId:
69
+ return get_coagent_id(self.agent_ids, agent_id)
70
+
71
+ def _sample_stock(self) -> Dict[str, int]:
72
+ # total items between 5 and 7
73
+ total_items = int(self.rng.integers(5, 8))
74
+ # nonnegative per-type counts summing to total_items
75
+ parts = random_partition_integer(self.rng, total_items, len(self.item_types))
76
+ # allow zeros per type
77
+ return {t: int(c) for t, c in zip(self.item_types, parts)}
78
+
79
+ def _sample_values_pair(self) -> Dict[AgentId, Dict[str, int]]:
80
+ # Each agent has integer non-negative values that sum to 10
81
+ # Each item type valued by at least one agent
82
+ # Some item type valued by both agents
83
+ while True:
84
+ vals_a = random_partition_integer(self.rng, 10, len(self.item_types))
85
+ vals_b = random_partition_integer(self.rng, 10, len(self.item_types))
86
+ a = {t: int(v) for t, v in zip(self.item_types, vals_a)}
87
+ b = {t: int(v) for t, v in zip(self.item_types, vals_b)}
88
+ # each item valued by at least one
89
+ ok1 = all((a[t] > 0) or (b[t] > 0) for t in self.item_types)
90
+ # some item valued by both
91
+ ok2 = any((a[t] > 0) and (b[t] > 0) for t in self.item_types)
92
+ if ok1 and ok2:
93
+ return {self.agent_ids[0]: a, self.agent_ids[1]: b}
94
+
95
+ def _is_valid_allocation(
96
+ self, allocation: Dict[str, int], stock: Dict[str, int]
97
+ ) -> bool:
98
+ for t in self.item_types:
99
+ v = allocation.get(t)
100
+ if v is None:
101
+ return False
102
+ if not isinstance(v, int):
103
+ return False
104
+ if v < 0 or v > int(stock.get(t, 0)):
105
+ return False
106
+ return True
107
+
108
+ def set_new_round_of_variant(self):
109
+ # Keep same values, resample stock
110
+ self.state.quantities = self._sample_stock()
111
+
112
+ def get_info_of_variant(
113
+ self, state: NegotiationState, actions: Dict[AgentId, Any]
114
+ ) -> Dict[str, Any]:
115
+ return {
116
+ "quantities": copy.deepcopy(state.quantities),
117
+ "values": copy.deepcopy(state.values),
118
+ "splits": copy.deepcopy(state.splits),
119
+ }
120
+
121
+ def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
122
+ """
123
+ Returns the rewards for each agent.
124
+ """
125
+ split_a = splits[self.agent_ids[0]].items_given_to_self
126
+ split_b = splits[self.agent_ids[1]].items_given_to_self
127
+ rewards = {self.agent_ids[0]: 0, self.agent_ids[1]: 0}
128
+ for t in self.item_types:
129
+ # If not complementary, return 0!
130
+ if not split_a[t] + split_b[t] == self.state.quantities[t]:
131
+ return {self.agent_ids[0]: 0, self.agent_ids[1]: 0}
132
+ rewards[self.agent_ids[0]] += (
133
+ split_a[t] * self.state.values[self.agent_ids[0]][t]
134
+ )
135
+ rewards[self.agent_ids[1]] += (
136
+ split_b[t] * self.state.values[self.agent_ids[1]][t]
137
+ )
138
+ return rewards
139
+
140
+ def get_obs(self):
141
+ return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
142
+
143
+ def get_obs_agent(self, agent_id):
144
+ other_id = self._other(agent_id)
145
+ obs = DealNoDealObs(
146
+ round_nb=self.state.round_nb,
147
+ last_message=self.state.last_message,
148
+ current_agent=self.state.current_agent,
149
+ quantities=copy.deepcopy(self.state.quantities),
150
+ value=0.0, # unused in DOND
151
+ other_agent_split=None, # not meaningful until split
152
+ split_phase=self.state.split_phase,
153
+ quota_messages_per_agent_per_round=self.quota_messages_per_agent_per_round,
154
+ my_values=copy.deepcopy(self.state.values[agent_id]),
155
+ item_types=list(self.item_types),
156
+ previous_values_coagent=copy.deepcopy(self.state.values.get(other_id, {})),
157
+ )
158
+ return obs
159
+
160
+ def reset(self):
161
+ start_agent = self.agent_ids[self._starting_agent_index]
162
+ stock = self._sample_stock()
163
+ values = self._sample_values_pair()
164
+ self.state = DealNoDealState(
165
+ round_nb=0,
166
+ last_message="",
167
+ current_agent=start_agent,
168
+ quantities=stock,
169
+ values=values,
170
+ previous_values=None,
171
+ splits={aid: None for aid in self.agent_ids},
172
+ nb_messages_sent={aid: 0 for aid in self.agent_ids},
173
+ split_phase=False,
174
+ item_types=list(self.item_types),
175
+ )
176
+ return self.get_obs()
src_code_for_reproducibility/markov_games/negotiation/nego_simulation.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/nego_simulation.py
3
+ Summary: Simulation harness for general negotiation environments.
4
+ """
5
+
6
+ import copy
7
+ from abc import abstractmethod
8
+ from dataclasses import dataclass
9
+ from typing import Any, Dict, List, Tuple
10
+
11
+ from numpy.random import default_rng
12
+
13
+ from mllm.markov_games.rollout_tree import SimulationStepLog
14
+ from mllm.markov_games.simulation import Simulation
15
+ from mllm.utils.get_coagent_id import get_coagent_id
16
+
17
+ AgentId = str
18
+
19
+
20
+ @dataclass
21
+ class Split:
22
+ """Structured proposal describing how many units of each item an agent keeps."""
23
+
24
+ items_given_to_self: Dict[str, int]
25
+
26
+
27
+ @dataclass
28
+ class Message:
29
+ """Single chat utterance exchanged during the negotiation phase."""
30
+
31
+ message: str
32
+
33
+
34
+ @dataclass # gets extended by variants
35
+ class NegotiationState:
36
+ """Full simulator state snapshot shared by all negotiation variants."""
37
+
38
+ round_nb: int
39
+ last_message: str
40
+ current_agent: AgentId
41
+ quantities: Dict[str, int]
42
+ values: Dict[AgentId, Dict[str, float]]
43
+ splits: Dict[AgentId, Split | None]
44
+ nb_messages_sent: Dict[AgentId, int]
45
+ previous_values: Dict[AgentId, Dict[str, float]] | None
46
+ previous_splits: Dict[AgentId, Dict[str, int] | None] | None
47
+ previous_points: Dict[AgentId, float] | None
48
+ previous_quantities: Dict[str, int] | None
49
+ split_phase: bool
50
+
51
+
52
+ @dataclass # gets extended by variants
53
+ class NegotiationObs:
54
+ """Observation presented to agents each turn (base fields; variants extend)."""
55
+
56
+ round_nb: int
57
+ last_message: str
58
+ quota_messages_per_agent_per_round: int
59
+ current_agent: AgentId
60
+ other_agent: str
61
+ quantities: Dict[str, int]
62
+ item_types: List[str]
63
+ value: Dict[str, int]
64
+ split_phase: bool
65
+ last_split_agent: Dict[str, int] | None
66
+ last_value_agent: Dict[str, int] | None
67
+ last_points_agent: float | None
68
+ last_split_coagent: Dict[str, int] | None
69
+ last_value_coagent: Dict[str, int] | None
70
+ last_points_coagent: float | None
71
+ last_quantities: Dict[str, int] | None
72
+
73
+
74
+ def compute_tas_style_rewards(
75
+ agent_ids: List[AgentId],
76
+ values: Dict[AgentId, float],
77
+ splits: Dict[AgentId, Split],
78
+ quantities: Dict[str, int],
79
+ ) -> Dict[AgentId, float]:
80
+ """
81
+ TAS-like reward computation: if sum of proposed coins exceeds max_coins,
82
+ allocate proportionally. Otherwise, use proposed amounts directly.
83
+ Rewards are quantity_kept * per-coin value for each agent.
84
+ """
85
+ a0, a1 = agent_ids[0], agent_ids[1]
86
+ r0, r1 = 0.0, 0.0
87
+
88
+ for item in quantities:
89
+ max_item = quantities[item]
90
+ item_to_self_0 = int(
91
+ (splits[a0].items_given_to_self.get(item, 0))
92
+ if splits[a0] is not None
93
+ else 0
94
+ )
95
+ item_to_self_1 = int(
96
+ (splits[a1].items_given_to_self.get(item, 0))
97
+ if splits[a1] is not None
98
+ else 0
99
+ )
100
+ denom = max(int(max_item), item_to_self_0 + item_to_self_1)
101
+ q0 = float(max_item) * float(item_to_self_0) / float(denom)
102
+ q1 = float(max_item) * float(item_to_self_1) / float(denom)
103
+ if type(values[a0]) is not dict:
104
+ r0 += q0 * float(values[a0])
105
+ r1 += q1 * float(values[a1])
106
+ else:
107
+ r0 += q0 * float(values[a0][item])
108
+ r1 += q1 * float(values[a1][item])
109
+ return {a0: r0, a1: r1}
110
+
111
+
112
+ class NegotiationSimulation(Simulation):
113
+ def __init__(
114
+ self,
115
+ agent_ids: List[AgentId],
116
+ agent_names: List[str],
117
+ seed: int,
118
+ nb_of_rounds: int,
119
+ quota_messages_per_agent_per_round: int,
120
+ item_types: List[str] | None = None,
121
+ ):
122
+ self.seed = seed
123
+ self.rng = default_rng(self.seed)
124
+ self.agent_ids = list(agent_ids)
125
+ self.agent_names = agent_names
126
+ self.agent_id_to_name = {
127
+ agent_id: agent_name for agent_id, agent_name in zip(agent_ids, agent_names)
128
+ }
129
+ self.nb_of_rounds = int(nb_of_rounds)
130
+ self.quota_messages_per_agent_per_round = int(
131
+ quota_messages_per_agent_per_round
132
+ )
133
+ if item_types is not None:
134
+ self.item_types = [item.lower() for item in item_types]
135
+ else:
136
+ self.item_types = ["coins"]
137
+ self.state: NegotiationState | None = None
138
+ self._starting_agent_index = self.rng.choice([0, 1])
139
+ self.reset()
140
+
141
+ def _other(self, agent_id: AgentId) -> AgentId:
142
+ return get_coagent_id(self.agent_ids, agent_id)
143
+
144
+ @abstractmethod
145
+ def set_new_round_of_variant(self):
146
+ """Variant hook: sample new private values / stock before each round."""
147
+ pass
148
+
149
+ @abstractmethod
150
+ def get_info_of_variant(
151
+ self, state: NegotiationState, actions: Dict[AgentId, Any]
152
+ ) -> Dict[str, Any]:
153
+ """Variant hook: populate SimulationStepLog.info with custom diagnostics."""
154
+ pass
155
+
156
+ def step(self, actions: Any) -> Tuple[bool, SimulationStepLog]:
157
+ """
158
+ Returns terminated, step_log
159
+ """
160
+ assert self.state is not None
161
+ current_agent = self.state.current_agent
162
+ a0, a1 = self.agent_ids[0], self.agent_ids[1]
163
+ action = actions.get(current_agent)
164
+
165
+ # Split phase: require both splits in the same timestep
166
+ if self.state.split_phase:
167
+ action_a0 = actions.get(a0)
168
+ action_a1 = actions.get(a1)
169
+ have_both_splits = isinstance(action_a0, Split) and isinstance(
170
+ action_a1, Split
171
+ )
172
+ if not have_both_splits:
173
+ rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
174
+ return False, SimulationStepLog(
175
+ rewards=rewards, info={"type": "waiting_for_splits"}
176
+ )
177
+
178
+ # Record splits
179
+ self.state.splits[a0] = action_a0
180
+ self.state.splits[a1] = action_a1
181
+
182
+ # Compute rewards and end round
183
+ rewards = self.get_rewards(self.state.splits)
184
+
185
+ # Info
186
+ info = self.get_info_of_variant(self.state, actions)
187
+
188
+ # Prepare next round
189
+ # Alternate starting agent
190
+ self.state.round_nb += 1
191
+ self._starting_agent_index = 1 - self._starting_agent_index
192
+ self.state.current_agent = self.agent_ids[self._starting_agent_index]
193
+ self.state.previous_values = copy.deepcopy(self.state.values)
194
+ self.state.previous_splits = copy.deepcopy(self.state.splits)
195
+ self.state.previous_quantities = copy.deepcopy(self.state.quantities)
196
+ self.state.previous_points = copy.deepcopy(rewards)
197
+ self.state.last_message = ""
198
+ self.set_new_round_of_variant() # variant specific
199
+ self.state.splits = {agent_id: None for agent_id in self.agent_ids}
200
+ self.state.nb_messages_sent = {agent_id: 0 for agent_id in self.agent_ids}
201
+ is_last_timestep_in_round = True
202
+ done = self.state.round_nb >= self.nb_of_rounds
203
+
204
+ # Message phase: roll the conversation forward a single turn.
205
+ elif isinstance(action, Message):
206
+ self.state.last_message = action.message
207
+ self.state.nb_messages_sent[current_agent] += 1
208
+
209
+ # Move turn to other agent
210
+ self.state.current_agent = self._other(current_agent)
211
+
212
+ # If both agents have reached their message quota, enter split phase
213
+ if all(
214
+ self.state.nb_messages_sent[agent_id]
215
+ >= self.quota_messages_per_agent_per_round
216
+ for agent_id in self.agent_ids
217
+ ):
218
+ self.state.split_phase = True
219
+ is_last_timestep_in_round = False
220
+ done = False
221
+ rewards = {agent_id: 0.0 for agent_id in self.agent_ids}
222
+ info = {"type": "message"}
223
+
224
+ info[
225
+ "is_last_timestep_in_round"
226
+ ] = is_last_timestep_in_round # Used later to group round timesteps if needed
227
+ return done, SimulationStepLog(rewards=rewards, info=info)
228
+
229
+ def get_obs(self):
230
+ """Returns all agent observations in dict"""
231
+ return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
232
+
233
+ @abstractmethod
234
+ def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
235
+ pass
236
+
237
+ @abstractmethod
238
+ def get_obs_agent(self, agent_id):
239
+ pass
240
+
241
+ def get_state(self):
242
+ return self.state
243
+
244
+ def get_safe_copy(self):
245
+ """Return a safe copy of the simulation."""
246
+ simulation_copy = copy.copy(self)
247
+ simulation_copy.state = copy.deepcopy(self.state)
248
+ return simulation_copy
249
+
250
+ @abstractmethod
251
+ def reset(self) -> dict[AgentId, NegotiationObs]:
252
+ pass
src_code_for_reproducibility/markov_games/negotiation/no_press_nego_simulation.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/no_press_nego_simulation.py
3
+ Summary: Simulation driver for no-press negotiation scenarios.
4
+ """
5
+
6
+ import copy
7
+ from collections import defaultdict
8
+ from dataclasses import dataclass
9
+ from typing import Any, Dict, List, Literal, Tuple
10
+
11
+ from mllm.markov_games.negotiation.nego_simulation import (
12
+ NegotiationObs,
13
+ NegotiationSimulation,
14
+ NegotiationState,
15
+ Split,
16
+ compute_tas_style_rewards,
17
+ )
18
+
19
+ AgentId = str
20
+
21
+
22
+ @dataclass
23
+ class NoPressState(NegotiationState):
24
+ """NegotiationState alias used to clarify we run in always-split phase."""
25
+
26
+ pass
27
+
28
+
29
+ @dataclass
30
+ class NoPressObs(NegotiationObs):
31
+ """Observation that includes both agents' values (since there is no messaging)."""
32
+
33
+ other_value: Dict[str, float]
34
+
35
+
36
+ class NoPressSimulation(NegotiationSimulation):
37
+ def __init__(
38
+ self,
39
+ game_type: Literal["10-1-exclusive", "10-1-ties", "1-to-20"] = "1-to-20",
40
+ same_round_value: bool = True,
41
+ atleast_one_conflict: bool = False,
42
+ *args,
43
+ **kwargs,
44
+ ):
45
+ self.game_type = game_type
46
+ self.same_round_value = same_round_value
47
+ self.atleast_one_conflict = atleast_one_conflict
48
+ super().__init__(*args, **kwargs)
49
+
50
+ def _sample_values(self) -> Dict[AgentId, dict]:
51
+ """Sample per-item valuations according to the configured template."""
52
+ values = defaultdict(dict)
53
+ if self.state is None:
54
+ item_types = self.item_types
55
+ else:
56
+ item_types = list(self.state.quantities.keys())
57
+ while True:
58
+ for item in item_types:
59
+ if self.game_type == "10-1-exclusive":
60
+ v = int(self.rng.choice([1, 10]))
61
+ values[self.agent_ids[0]][item] = v
62
+ values[self.agent_ids[1]][item] = 10 if v == 1 else 1
63
+ elif self.game_type == "10-1-ties":
64
+ for aid in self.agent_ids:
65
+ values[aid][item] = int(self.rng.choice([1, 10]))
66
+ elif self.game_type == "1-to-20":
67
+ for aid in self.agent_ids:
68
+ values[aid][item] = int(self.rng.integers(1, 21))
69
+ if self.atleast_one_conflict:
70
+ has_conflict = False
71
+ for item in item_types:
72
+ agent_values_for_item = [
73
+ values[aid][item] for aid in self.agent_ids
74
+ ]
75
+ if len(set(agent_values_for_item)) > 1:
76
+ has_conflict = True
77
+ break
78
+ if not has_conflict:
79
+ continue
80
+ agent_values = [sum(v.values()) for v in values.values()]
81
+ if len(set(agent_values)) == 1 or not self.same_round_value:
82
+ break
83
+ return values
84
+
85
+ def _sample_quantities(self) -> Dict[str, int]:
86
+ """No-press setups use symmetric 10-unit stocks for every item."""
87
+ return {item.lower(): 10 for item in self.item_types}
88
+
89
+ def set_new_round_of_variant(self):
90
+ """Refresh quantities/values and jump directly into the simultaneous split."""
91
+ self.state.quantities = self._sample_quantities()
92
+ self.state.values = self._sample_values()
93
+ self.state.split_phase = True
94
+
95
+ def get_info_of_variant(
96
+ self, state: NegotiationState, actions: Dict[AgentId, Any]
97
+ ) -> Dict[str, Any]:
98
+ """Surface quantities/values/splits so statistics modules can read them."""
99
+ return {
100
+ "quantities": copy.deepcopy(state.quantities),
101
+ "values": copy.deepcopy(state.values),
102
+ "splits": copy.deepcopy(state.splits),
103
+ }
104
+
105
+ def get_rewards(self, splits: Dict[AgentId, Split]) -> Dict[AgentId, float]:
106
+ """Reuse TAS reward logic because the split arbitration is identical."""
107
+ return compute_tas_style_rewards(
108
+ self.agent_ids, self.state.values, splits, self.state.quantities
109
+ )
110
+
111
+ def get_obs(self):
112
+ return {agent_id: self.get_obs_agent(agent_id) for agent_id in self.agent_ids}
113
+
114
+ def get_obs_agent(self, agent_id):
115
+ other_id = self._other(agent_id)
116
+ last_value_coagent = (
117
+ None
118
+ if self.state.previous_values is None
119
+ else self.state.previous_values.get(other_id)
120
+ )
121
+ last_points_coagent = (
122
+ None
123
+ if self.state.previous_points is None
124
+ else round(self.state.previous_points.get(other_id), 1)
125
+ )
126
+ last_value_agent = (
127
+ None
128
+ if self.state.previous_values is None
129
+ else self.state.previous_values.get(agent_id)
130
+ )
131
+ last_points_agent = (
132
+ None
133
+ if self.state.previous_points is None
134
+ else round(self.state.previous_points.get(agent_id), 1)
135
+ )
136
+ last_split_coagent = None
137
+ last_split_agent = None
138
+ if self.state.previous_splits is not None:
139
+ last_split_coagent = self.state.previous_splits[
140
+ other_id
141
+ ].items_given_to_self
142
+ last_split_agent = self.state.previous_splits[agent_id].items_given_to_self
143
+ obs = NoPressObs(
144
+ round_nb=self.state.round_nb,
145
+ last_message="",
146
+ quota_messages_per_agent_per_round=self.quota_messages_per_agent_per_round,
147
+ current_agent=self.state.current_agent,
148
+ other_agent=self.agent_id_to_name[other_id],
149
+ quantities=self.state.quantities,
150
+ item_types=self.item_types,
151
+ value=self.state.values[agent_id],
152
+ split_phase=self.state.split_phase,
153
+ last_split_agent=last_split_agent,
154
+ last_value_agent=last_value_agent,
155
+ last_points_agent=last_points_agent,
156
+ last_split_coagent=last_split_coagent,
157
+ last_value_coagent=last_value_coagent,
158
+ last_points_coagent=last_points_coagent,
159
+ other_value=self.state.values[other_id],
160
+ last_quantities=self.state.previous_quantities,
161
+ )
162
+ return obs
163
+
164
+ def reset(self):
165
+ start_agent = self.agent_ids[self._starting_agent_index]
166
+ quantities = self._sample_quantities()
167
+ values = self._sample_values()
168
+ self.state = NoPressState(
169
+ round_nb=0,
170
+ last_message="",
171
+ current_agent=start_agent,
172
+ quantities=quantities,
173
+ values=values,
174
+ previous_values=None,
175
+ splits={aid: None for aid in self.agent_ids},
176
+ nb_messages_sent={aid: 0 for aid in self.agent_ids},
177
+ split_phase=True,
178
+ previous_splits=None,
179
+ previous_points=None,
180
+ previous_quantities=None,
181
+ )
182
+ return self.get_obs()
src_code_for_reproducibility/markov_games/negotiation/tas_agent.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/negotiation/tas_agent.py
3
+ Summary: Agent implementation for Take-and-Split negotiations.
4
+ """
5
+
6
+ from mllm.markov_games.negotiation.nego_agent import NegotiationAgent
7
+ from mllm.markov_games.negotiation.nego_simulation import Split
8
+ from mllm.markov_games.negotiation.tas_simulation import TrustAndSplitObs
9
+
10
+
11
+ class TrustAndSplitAgent(NegotiationAgent):
12
+ """Prompt/template wrapper for the classic multi-item Take-and-Split benchmark."""
13
+
14
+ def __init__(self, num_message_chars, *args, **kwargs):
15
+ self.num_message_chars = num_message_chars
16
+ super().__init__(*args, **kwargs)
17
+ self.intro_prompt = (
18
+ "Welcome to an iterated game. You are {agent}. The other agent is {other_agent}.\n"
19
+ "Setup:\n"
20
+ "1. The game has multiple independent rounds.\n"
21
+ "2. In each round, there are multiple items to split between the two agents.\n"
22
+ "3. Both agents are assigned a per-item value between 1 and 20 (inclusive) in each round.\n"
23
+ "4. You can only observe your own per-item values.\n"
24
+ "5. Because assignments are random, both agents are equally likely to have same expected per-item value.\n"
25
+ "\n"
26
+ "Protocol:\n"
27
+ "1. At the start of the round, one agent begins the conversation. The starting role alternates each round.\n"
28
+ "2. Agents exchange a short chat ({quota_messages_per_agent_per_round} messages per round per agent) to negotiate how to split the item.\n"
29
+ " - Use this chat to communicate your private per-item value to make informed proposals.\n"
30
+ "3. After the chat, both agents simultaneously propose the amount of each item they will keep.\n"
31
+ "4. If the total sum of proposals is less than or equal to the item quantity, both agents receive their proposed amounts.\n"
32
+ "5. If the total sum of proposals exceeds the item quantity, they are allocated proportionally.\n"
33
+ "6. Your points for the round = (amount you receive per item) x (your per-item value for that round), added across all items.\n"
34
+ "7. Points are accumulated across rounds.\n"
35
+ "Your goal: {goal}\n"
36
+ )
37
+ self.new_round_prompt = (
38
+ "A New Round Begins\n"
39
+ "The items to split are {quantities}.\n"
40
+ "Your per-item values are {value}."
41
+ )
42
+ self.last_round_prompt = (
43
+ "Last Round Summary:\n"
44
+ " - Items to split: {last_quantities}\n"
45
+ " - Your per-item values: {last_value_agent}\n"
46
+ " - {other_agent}'s per-item values: {last_value_coagent}\n"
47
+ " - You proposed: {last_split_agent}\n"
48
+ " - You earned: {last_points_agent} points\n"
49
+ " - {other_agent} proposed: {last_split_coagent}\n"
50
+ " - {other_agent} earned: {last_points_coagent} points\n"
51
+ " - Round Complete.\n"
52
+ )
53
+ self.send_split_prompt = (
54
+ "Message quota is finished for this round.\n"
55
+ "{other_agent} has finalized their proposal.\n"
56
+ "Submit your finalization now\n"
57
+ "Respond with {proposal_style2}"
58
+ )
59
+ # self.wait_for_message_prompt = "Wait for {other_agent} to send a message..."
60
+ self.wait_for_message_prompt = ""
61
+ self.last_message_prompt = "{other_agent} said: {last_message}"
62
+ # self.send_message_prompt = (
63
+ # f"Send your message now (max {self.num_message_chars} chars)."
64
+ # )
65
+ self.send_message_prompt = f"Send your message now in <message>...</message> (<={self.num_message_chars} chars)."
66
+
67
+ def get_message_regex(self, observation: TrustAndSplitObs) -> str:
68
+ """Constrain chat to bounded XML tags for stable parsing."""
69
+ return rf"<message>[\s\S]{{0,{self.num_message_chars}}}</message>"
70
+
71
+ # def get_message_regex(self, observation: TrustAndSplitObs) -> str:
72
+ # return rf"(?s).{{0,{self.num_message_chars}}}"
73
+
74
+ def get_split_regex(self, observation: TrustAndSplitObs) -> str:
75
+ """Allow natural-language item names while still returning machine-parsable XML."""
76
+ items = list(observation.quantities.keys())
77
+ # Accept both singular and plural forms
78
+ item_pattern = "|".join(
79
+ [f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?" for item in items]
80
+ )
81
+ regex = rf"(?i)<items_to_self> ?((?:\s*(?P<num>(10|[0-9]))\s*(?P<item>{item_pattern})\s*,?)+) ?</items_to_self>"
82
+ return regex
83
+
84
+ def get_split_action(
85
+ self, policy_output: str, observation: TrustAndSplitObs
86
+ ) -> Split:
87
+ """Convert human-readable allocation text back into canonical item IDs."""
88
+ items = list(observation.quantities.keys())
89
+ import re as _re
90
+
91
+ split_regex = self.get_split_regex(observation)
92
+ items_given_to_self = {item: 0 for item in items}
93
+ m = _re.match(split_regex, policy_output.strip())
94
+ if m:
95
+ # Find all (number, item) pairs
96
+ item_pattern = "|".join(
97
+ [
98
+ f"{item[:-1]}s?" if item.endswith("s") else f"{item}s?"
99
+ for item in items
100
+ ]
101
+ )
102
+ inner_regex = rf"(?i)(10|[0-9])\s*({item_pattern})"
103
+
104
+ def normalize_item_name(item_str):
105
+ for orig in items:
106
+ if item_str.lower() == orig.lower():
107
+ return orig
108
+ if orig.endswith("s") and item_str.lower() == orig[:-1].lower():
109
+ return orig
110
+ if (
111
+ not orig.endswith("s")
112
+ and item_str.lower() == orig.lower() + "s"
113
+ ):
114
+ return orig
115
+
116
+ for num, item in _re.findall(inner_regex, m.group(1)):
117
+ items_given_to_self[normalize_item_name(item)] = int(num)
118
+ return Split(items_given_to_self=items_given_to_self)
src_code_for_reproducibility/models/__pycache__/human_policy.cpython-312.pyc ADDED
Binary file (12.1 kB). View file
 
src_code_for_reproducibility/models/__pycache__/inference_backend.cpython-312.pyc ADDED
Binary file (2.37 kB). View file
 
src_code_for_reproducibility/models/__pycache__/large_language_model_api.cpython-312.pyc ADDED
Binary file (7.43 kB). View file
 
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_gather_utils.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/utils/rollout_tree_gather_utils.py
3
+ Summary: Utilities for gathering rollout tree files and metadata.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import csv
9
+ import os
10
+ import pickle
11
+ import re
12
+ from collections import defaultdict
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
16
+
17
+ from mllm.markov_games.rollout_tree import *
18
+
19
+
20
+ def load_rollout_tree(path: Path) -> RolloutTreeRootNode:
21
+ """Load a rollout tree from a PKL file containing a dict."""
22
+ with open(path, "rb") as f:
23
+ data = pickle.load(f)
24
+ return RolloutTreeRootNode.model_validate(data)
25
+
26
+
27
+ @dataclass
28
+ class RolloutNodeList:
29
+ id: str
30
+ nodes: List[RolloutTreeNode]
31
+
32
+
33
+ def get_rollout_tree_paths(
34
+ root: RolloutTreeRootNode, mgid: Optional[str] = None
35
+ ) -> Tuple[RolloutNodeList, List[RolloutNodeList]]:
36
+ """
37
+ Returns:
38
+ main_path: The main path from the root to the end of the tree.
39
+ branch_paths: A list of all branch paths from the root to the end of the tree.
40
+ Each branch path contains a list of nodes that are part of the branch, including the nodes from the main path before the branch was taken.
41
+ """
42
+ branch_paths = []
43
+
44
+ def collect_path_nodes(current) -> List[RolloutTreeNode]:
45
+ """Recursively collect all nodes in a path starting from current node."""
46
+ if current is None:
47
+ return []
48
+
49
+ if isinstance(current, RolloutTreeNode):
50
+ return [current] + collect_path_nodes(current.child)
51
+
52
+ elif isinstance(current, RolloutTreeBranchNode):
53
+ # For branch nodes, we only follow the main_child for path collection
54
+ if current.main_child:
55
+ return [current.main_child] + collect_path_nodes(
56
+ current.main_child.child
57
+ )
58
+ else:
59
+ return []
60
+
61
+ def traverse_for_branches(
62
+ current,
63
+ main_path_prefix: List[RolloutTreeNode],
64
+ path_id: str,
65
+ current_time_step: Optional[int] = 0,
66
+ ):
67
+ """Traverse tree to collect all branch paths."""
68
+ if current is None:
69
+ return
70
+
71
+ if isinstance(current, RolloutTreeNode):
72
+ # Continue traversing with this node added to the main path prefix
73
+ new_prefix = main_path_prefix + [current]
74
+ traverse_for_branches(current.child, new_prefix, path_id, current.time_step)
75
+
76
+ elif isinstance(current, RolloutTreeBranchNode):
77
+ # Collect all branch paths
78
+ if current.branches:
79
+ for agent_id, branch_node_list in current.branches.items():
80
+ if branch_node_list:
81
+ # Start with the main path prefix, then recursively collect all nodes in this branch
82
+ branch_path_nodes = main_path_prefix.copy()
83
+ for branch_node in branch_node_list:
84
+ branch_path_nodes.extend(collect_path_nodes(branch_node))
85
+
86
+ # Create proper branch path ID with mgid, agent_id, and time_step
87
+ mgid_str = mgid or str(root.id)
88
+ branch_path_id = f"mgid:{mgid_str}_type:branch_agent:{agent_id}_time_step:{current_time_step}"
89
+ branch_paths.append(
90
+ RolloutNodeList(id=branch_path_id, nodes=branch_path_nodes)
91
+ )
92
+
93
+ # Process the main child and add to prefix
94
+ new_prefix = main_path_prefix
95
+ if current.main_child:
96
+ new_prefix = main_path_prefix + [current.main_child]
97
+
98
+ # Continue traversing the main path
99
+ if current.main_child:
100
+ traverse_for_branches(
101
+ current.main_child.child,
102
+ new_prefix,
103
+ path_id,
104
+ current.main_child.time_step,
105
+ )
106
+
107
+ # Collect the main path nodes
108
+ main_path_nodes = collect_path_nodes(root.child)
109
+
110
+ # Traverse to collect all branch paths
111
+ traverse_for_branches(root.child, [], "")
112
+
113
+ # Create the main path with proper mgid format
114
+ mgid_str = mgid or str(root.id)
115
+ main_path = RolloutNodeList(id=f"mgid:{mgid_str}_type:main", nodes=main_path_nodes)
116
+
117
+ return main_path, branch_paths
118
+
119
+
120
+ class ChatTurnLog(BaseModel):
121
+ time_step: int
122
+ agent_id: str
123
+ role: str
124
+ content: str
125
+ reasoning_content: Optional[str] = None
126
+ is_state_end: bool
127
+ reward: float
128
+
129
+
130
+ def gather_agent_chat_turns_for_path(
131
+ agent_id: str, path: RolloutNodeList
132
+ ) -> List[ChatTurnLog]:
133
+ """Iterate through all chat turns for a specific agent in a path sorted by time step."""
134
+ turns = []
135
+ for node in path.nodes:
136
+ action_log = node.step_log.action_logs.get(agent_id, [])
137
+ if action_log:
138
+ for chat_turn in action_log.chat_turns or []:
139
+ turns.append(
140
+ ChatTurnLog(
141
+ time_step=node.time_step,
142
+ agent_id=agent_id,
143
+ role=chat_turn.role,
144
+ content=chat_turn.content,
145
+ reasoning_content=getattr(chat_turn, "reasoning_content", None),
146
+ is_state_end=chat_turn.is_state_end,
147
+ reward=node.step_log.simulation_step_log.rewards.get(
148
+ agent_id, 0
149
+ ),
150
+ )
151
+ )
152
+ return turns
153
+
154
+
155
+ def gather_all_chat_turns_for_path(path: RolloutNodeList) -> List[ChatTurnLog]:
156
+ """Iterate through all chat turns for all agents in a path sorted by time step."""
157
+ turns = []
158
+
159
+ # Collect turns from all agents, but interleave them per timestep by (user, assistant) pairs
160
+ for node in path.nodes:
161
+ # Build (user[, assistant]) pairs for each agent at this timestep
162
+ agent_ids = sorted(list(node.step_log.action_logs.keys()))
163
+ per_agent_pairs: Dict[str, List[List[ChatTurnLog]]] = {}
164
+
165
+ for agent_id in agent_ids:
166
+ action_log = node.step_log.action_logs.get(agent_id)
167
+ pairs: List[List[ChatTurnLog]] = []
168
+ current_pair: List[ChatTurnLog] = []
169
+
170
+ if action_log and action_log.chat_turns:
171
+ for chat_turn in action_log.chat_turns:
172
+ turn_log = ChatTurnLog(
173
+ time_step=node.time_step,
174
+ agent_id=agent_id,
175
+ role=chat_turn.role,
176
+ content=chat_turn.content,
177
+ reasoning_content=getattr(chat_turn, "reasoning_content", None),
178
+ is_state_end=chat_turn.is_state_end,
179
+ reward=node.step_log.simulation_step_log.rewards.get(
180
+ agent_id, 0
181
+ ),
182
+ )
183
+
184
+ if chat_turn.role == "user":
185
+ # If a previous pair is open, close it and start a new one
186
+ if current_pair:
187
+ pairs.append(current_pair)
188
+ current_pair = []
189
+ current_pair = [turn_log]
190
+ else:
191
+ # assistant: attach to an open user message if present; otherwise stand alone
192
+ if (
193
+ current_pair
194
+ and len(current_pair) == 1
195
+ and current_pair[0].role == "user"
196
+ ):
197
+ current_pair.append(turn_log)
198
+ pairs.append(current_pair)
199
+ current_pair = []
200
+ else:
201
+ # No preceding user or already paired; treat as its own unit
202
+ pairs.append([turn_log])
203
+
204
+ if current_pair:
205
+ # Unpaired trailing user message
206
+ pairs.append(current_pair)
207
+
208
+ per_agent_pairs[agent_id] = pairs
209
+
210
+ # Interleave pairs across agents: A1, B1, A2, B2, ...
211
+ index = 0
212
+ while True:
213
+ added_any = False
214
+ for agent_id in agent_ids:
215
+ agent_pairs = per_agent_pairs.get(agent_id, [])
216
+ if index < len(agent_pairs):
217
+ for tl in agent_pairs[index]:
218
+ turns.append(tl)
219
+ added_any = True
220
+ if not added_any:
221
+ break
222
+ index += 1
223
+
224
+ return turns
225
+
226
+
227
+ def chat_turns_to_dict(chat_turns: Iterator[ChatTurnLog]) -> Iterator[Dict[str, Any]]:
228
+ """Render all chat turns for a path as structured data for JSON."""
229
+ for chat_turn in chat_turns:
230
+ yield chat_turn.model_dump()
231
+
232
+
233
+ def get_all_agents(root: RolloutTreeRootNode) -> List[str]:
234
+ """list of all agent IDs that appear in the tree."""
235
+ if root.child is None:
236
+ return []
237
+
238
+ # Get the first node to extract all agent IDs
239
+ first_node = root.child
240
+ if isinstance(first_node, RolloutTreeBranchNode):
241
+ first_node = first_node.main_child
242
+
243
+ if first_node is None:
244
+ return []
245
+
246
+ # All agents should be present in the first node
247
+ agents = set(first_node.step_log.action_logs.keys())
248
+ agents.update(first_node.step_log.simulation_step_log.rewards.keys())
249
+
250
+ return sorted(list(agents))
251
+
252
+
253
+ def gather_agent_main_rewards(agent_id: str, path: RolloutNodeList) -> List[float]:
254
+ """Gather main rewards for a specific agent in a path."""
255
+ rewards = []
256
+ for node in path.nodes:
257
+ reward = node.step_log.simulation_step_log.rewards[agent_id]
258
+ rewards.append(reward)
259
+ return rewards
260
+
261
+
262
+ def gather_all_rewards(path: RolloutNodeList) -> List[Dict[AgentId, float]]:
263
+ """Gather main rewards from main trajectory in a path."""
264
+ rewards = []
265
+ for node in path.nodes:
266
+ rewards.append(node.step_log.simulation_step_log.rewards.copy())
267
+ return rewards
268
+
269
+
270
+ def gather_simulation_stats(
271
+ path: RolloutNodeList,
272
+ filter: Callable[[SimulationStepLog], bool],
273
+ stat_func: Callable[[SimulationStepLog], Any],
274
+ ) -> List[Any]:
275
+ """Gather stats from main trajectory in a path."""
276
+ stats = []
277
+ for node in path.nodes:
278
+ sl = node.step_log.simulation_step_log
279
+ if filter(sl):
280
+ stats.append(stat_func(sl))
281
+ return stats
282
+
283
+
284
+ def gather_simulation_step_logs(path: RolloutNodeList) -> List[SimulationStepLog]:
285
+ """Gather simulation information from main trajectory in a path."""
286
+ infos = []
287
+ for node in path.nodes:
288
+ infos.append(node.step_log.simulation_step_log)
289
+ return infos
290
+
291
+
292
+ def export_chat_logs(path: Path, outdir: Path):
293
+ """Process a rollout tree PKL file and generate a JSONL of chat turns as dicts.
294
+ Each line contains an object with path_id and chat_turns for a single path.
295
+ """
296
+ import json
297
+
298
+ root = load_rollout_tree(path)
299
+ mgid = root.id
300
+
301
+ main_path, branch_paths = get_rollout_tree_paths(root)
302
+ all_paths = [main_path] + branch_paths
303
+
304
+ outdir.mkdir(parents=True, exist_ok=True)
305
+ output_file = outdir / f"mgid:{mgid}_plucked_chats.render.jsonl"
306
+
307
+ with open(output_file, "w", encoding="utf-8") as f:
308
+ for path_obj in all_paths:
309
+ chat_turns = gather_all_chat_turns_for_path(path_obj)
310
+ output_obj = {
311
+ "path_id": str(path_obj.id),
312
+ "chat_turns": list(chat_turns_to_dict(iter(chat_turns))),
313
+ }
314
+ f.write(json.dumps(output_obj, ensure_ascii=False) + "\n")