Muqeeth commited on
Commit
86bc4e1
·
verified ·
1 Parent(s): f36cdea

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. seed_1/Qwen/Qwen2.5-7B-Instruct/adapters/fixed_ad_align_adapter/adapter_config.json +46 -0
  2. src_code_for_reproducibility/__pycache__/__init__.cpython-312.pyc +0 -0
  3. src_code_for_reproducibility/chat_utils/apply_template.py +89 -0
  4. src_code_for_reproducibility/chat_utils/chat_turn.py +32 -0
  5. src_code_for_reproducibility/chat_utils/template_specific.py +114 -0
  6. src_code_for_reproducibility/markov_games/__init__.py +4 -0
  7. src_code_for_reproducibility/markov_games/agent.py +72 -0
  8. src_code_for_reproducibility/markov_games/alternative_actions_runner.py +146 -0
  9. src_code_for_reproducibility/markov_games/group_timesteps.py +133 -0
  10. src_code_for_reproducibility/markov_games/linear_runner.py +42 -0
  11. src_code_for_reproducibility/markov_games/markov_game.py +217 -0
  12. src_code_for_reproducibility/markov_games/mg_utils.py +97 -0
  13. src_code_for_reproducibility/markov_games/rollout_tree.py +95 -0
  14. src_code_for_reproducibility/markov_games/run_markov_games.py +52 -0
  15. src_code_for_reproducibility/markov_games/simulation.py +94 -0
  16. src_code_for_reproducibility/markov_games/statistics_runner.py +415 -0
  17. src_code_for_reproducibility/models/__init__.py +4 -0
  18. src_code_for_reproducibility/models/__pycache__/human_policy.cpython-312.pyc +0 -0
  19. src_code_for_reproducibility/models/__pycache__/inference_backend_dummy.cpython-312.pyc +0 -0
  20. src_code_for_reproducibility/models/__pycache__/inference_backend_vllm.cpython-312.pyc +0 -0
  21. src_code_for_reproducibility/models/__pycache__/large_language_model_api.cpython-312.pyc +0 -0
  22. src_code_for_reproducibility/models/__pycache__/large_language_model_gemini_api.cpython-312.pyc +0 -0
  23. src_code_for_reproducibility/models/__pycache__/large_language_model_local.cpython-312.pyc +0 -0
  24. src_code_for_reproducibility/models/__pycache__/scalar_critic.cpython-312.pyc +0 -0
  25. src_code_for_reproducibility/models/adapter_training_wrapper.py +104 -0
  26. src_code_for_reproducibility/models/human_policy.py +260 -0
  27. src_code_for_reproducibility/models/inference_backend.py +44 -0
  28. src_code_for_reproducibility/models/inference_backend_dummy.py +59 -0
  29. src_code_for_reproducibility/models/inference_backend_vllm.py +111 -0
  30. src_code_for_reproducibility/models/large_language_model_api.py +184 -0
  31. src_code_for_reproducibility/models/large_language_model_gemini_api.py +197 -0
  32. src_code_for_reproducibility/models/large_language_model_local.py +361 -0
  33. src_code_for_reproducibility/models/scalar_critic.py +59 -0
  34. src_code_for_reproducibility/training/__init__.py +4 -0
  35. src_code_for_reproducibility/training/__pycache__/annealing_methods.cpython-312.pyc +0 -0
  36. src_code_for_reproducibility/training/__pycache__/credit_methods.cpython-312.pyc +0 -0
  37. src_code_for_reproducibility/training/__pycache__/tally_metrics.cpython-312.pyc +0 -0
  38. src_code_for_reproducibility/training/__pycache__/tally_rollout.cpython-312.pyc +0 -0
  39. src_code_for_reproducibility/training/__pycache__/tally_tokenwise.cpython-312.pyc +0 -0
  40. src_code_for_reproducibility/training/__pycache__/trainer_ad_align.cpython-312.pyc +0 -0
  41. src_code_for_reproducibility/training/__pycache__/trainer_common.cpython-312.pyc +0 -0
  42. src_code_for_reproducibility/training/__pycache__/trainer_independent.cpython-312.pyc +0 -0
  43. src_code_for_reproducibility/training/__pycache__/training_data_utils.cpython-312.pyc +0 -0
  44. src_code_for_reproducibility/training/annealing_methods.py +20 -0
  45. src_code_for_reproducibility/training/credit_methods.py +307 -0
  46. src_code_for_reproducibility/training/tally_metrics.py +64 -0
  47. src_code_for_reproducibility/training/tally_rollout.py +116 -0
  48. src_code_for_reproducibility/training/tally_tokenwise.py +278 -0
  49. src_code_for_reproducibility/training/tokenize_chats.py +128 -0
  50. src_code_for_reproducibility/training/trainer_ad_align.py +505 -0
seed_1/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
+ "down_proj",
33
+ "up_proj",
34
+ "gate_proj",
35
+ "o_proj",
36
+ "k_proj",
37
+ "q_proj",
38
+ "v_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/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (259 Bytes). View file
 
src_code_for_reproducibility/chat_utils/apply_template.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/chat_utils/apply_template.py
3
+ Summary: Applies tokenizer-specific chat templates and stitches chat token IDs.
4
+ """
5
+
6
+ import torch
7
+
8
+ from mllm.chat_utils.chat_turn import ChatTurn
9
+ from mllm.chat_utils.template_specific import (
10
+ custom_gemma3_template,
11
+ custom_llama3_template,
12
+ custom_qwen2_template,
13
+ custom_qwen3_template,
14
+ gemma3_assistant_postfix,
15
+ qwen2_assistant_postfix,
16
+ qwen3_assistant_postfix,
17
+ )
18
+
19
+
20
+ def get_custom_chat_template(tokenizer) -> str:
21
+ """
22
+ Get the chat template for the tokenizer.
23
+ """
24
+ if "qwen2" in tokenizer.name_or_path.lower():
25
+ return custom_qwen2_template
26
+ elif "llama" in tokenizer.name_or_path.lower():
27
+ return custom_llama3_template
28
+ elif "qwen3" in tokenizer.name_or_path.lower():
29
+ return custom_qwen3_template
30
+ elif "gemma" in tokenizer.name_or_path.lower():
31
+ return custom_gemma3_template
32
+ else:
33
+ raise ValueError(f"Tokenizer {tokenizer.name_or_path} not supported")
34
+
35
+
36
+ def get_custom_assistant_postfix(tokenizer) -> torch.Tensor:
37
+ """
38
+ Get the custom assistant postfix for the tokenizer.
39
+ """
40
+ if "qwen2" in tokenizer.name_or_path.lower():
41
+ return qwen2_assistant_postfix
42
+ elif "qwen3" in tokenizer.name_or_path.lower():
43
+ return qwen3_assistant_postfix
44
+ elif "gemma" in tokenizer.name_or_path.lower():
45
+ return gemma3_assistant_postfix
46
+ return torch.tensor([], dtype=torch.long)
47
+
48
+
49
+ def tokenize_chats(chats: list[ChatTurn], tokenizer, enable_thinking) -> None:
50
+ """
51
+ Set the chat_template_token_ids for each chat turn.
52
+ We rely on tokenizer-side templates because engine-provided cached tokens are not exposed yet.
53
+ """
54
+ custom_template = get_custom_chat_template(tokenizer)
55
+ custom_assistant_postfix: torch.Tensor = get_custom_assistant_postfix(tokenizer)
56
+ for i, chat in enumerate(chats):
57
+ if chat.chat_template_token_ids is None:
58
+ if chat.role == "user":
59
+ next_chat = chats[i + 1] if i + 1 < len(chats) else None
60
+ add_generation_prompt = True
61
+ if next_chat and next_chat.role == "user":
62
+ add_generation_prompt = False
63
+ encoded_chat = tokenizer.apply_chat_template(
64
+ [chat],
65
+ return_tensors="pt",
66
+ chat_template=custom_template,
67
+ add_generation_prompt=add_generation_prompt,
68
+ add_system_prompt=True if i == 0 else False,
69
+ enable_thinking=enable_thinking,
70
+ ).flatten()
71
+ previous_chat = chats[i - 1] if i > 0 else None
72
+ if previous_chat and previous_chat.role == "assistant":
73
+ encoded_chat = torch.cat([custom_assistant_postfix, encoded_chat])
74
+ elif chat.role == "assistant":
75
+ encoded_chat = chat.out_token_ids
76
+ chat.chat_template_token_ids = encoded_chat
77
+
78
+
79
+ def chat_turns_to_token_ids(
80
+ chats: list[ChatTurn], tokenizer, enable_thinking
81
+ ) -> list[int]:
82
+ """
83
+ Tokenize the chat turns and set the chat_template_token_ids for each chat turn.
84
+ """
85
+ tokenize_chats(chats=chats, tokenizer=tokenizer, enable_thinking=enable_thinking)
86
+ token_ids = []
87
+ for chat in chats:
88
+ token_ids.append(chat.chat_template_token_ids)
89
+ return torch.cat(token_ids)
src_code_for_reproducibility/chat_utils/chat_turn.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/chat_utils/chat_turn.py
3
+ Summary: Defines the ChatTurn schema plus helpers for serialization and validation.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Any, List, Literal, Optional, Tuple
12
+
13
+ import jsonschema
14
+ import torch
15
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
16
+
17
+ AgentId = str
18
+
19
+
20
+ class ChatTurn(BaseModel):
21
+ model_config = ConfigDict(arbitrary_types_allowed=True) # needed for torch tensors
22
+
23
+ role: str = Field(pattern="^(user|assistant)$")
24
+ agent_id: AgentId # ID of the agent with which the chat occured
25
+ content: str
26
+ reasoning_content: str | None = None
27
+ chat_template_token_ids: torch.LongTensor | None = None # Token ids of chat template format. For example, token ids of "<assistant>{content}</assistant>""
28
+ out_token_ids: torch.LongTensor | None = (
29
+ None # tokens generated from inference engine
30
+ )
31
+ log_probs: torch.FloatTensor | None = None
32
+ is_state_end: bool = False # indicates whether this chat turn marks the end of a state in the trajectory
src_code_for_reproducibility/chat_utils/template_specific.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/chat_utils/template_specific.py
3
+ Summary: Stores chat template variants and assistant postfix tensors per tokenizer.
4
+ """
5
+
6
+ import huggingface_hub
7
+ import torch
8
+ from transformers import AutoTokenizer
9
+
10
+ custom_llama3_template = """
11
+ {%- if add_system_prompt %}
12
+ {{- '<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nCutting Knowledge Date: December 2023\nToday Date: 26 Jul 2024\n\n<|eot_id|>' }}
13
+ {%- endif %}
14
+ {%- for message in messages %}
15
+ {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' }}
16
+ {%- endfor %}
17
+
18
+ {%- if add_generation_prompt %}
19
+ {{- '<|start_header_id|>' + 'assistant' + '<|end_header_id|>\n\n' }}
20
+ {%- endif %}
21
+ """
22
+
23
+ qwen2_assistant_postfix = (
24
+ AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
25
+ .encode("\n", return_tensors="pt")
26
+ .flatten()
27
+ )
28
+ qwen3_assistant_postfix = (
29
+ AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
30
+ .encode("\n", return_tensors="pt")
31
+ .flatten()
32
+ )
33
+ gemma3_assistant_postfix = (
34
+ AutoTokenizer.from_pretrained("google/gemma-3-4b-it")
35
+ .encode("\n", return_tensors="pt")
36
+ .flatten()
37
+ )
38
+ custom_qwen2_template = """
39
+ {%- if add_system_prompt %}
40
+ {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
41
+ {%- endif %}
42
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
43
+ {%- for message in messages %}
44
+ {%- if message.content is string %}
45
+ {%- set content = message.content %}
46
+ {%- else %}
47
+ {%- set content = '' %}
48
+ {%- endif %}
49
+ {%- if (message.role == "user") %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
51
+ {%- elif message.role == "assistant" %}
52
+ {%- set reasoning_content = '' %}
53
+ {%- if message.reasoning_content is string %}
54
+ {%- set reasoning_content = message.reasoning_content %}
55
+ {%- else %}
56
+ {%- if '</think>' in content %}
57
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
58
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
59
+ {%- endif %}
60
+ {%- endif %}
61
+ {%- if loop.index0 > ns.last_query_index %}
62
+ {%- if reasoning_content %}
63
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
64
+ {%- else %}
65
+ {{- '<|im_start|>' + message.role + '\n' + content }}
66
+ {%- endif %}
67
+ {%- else %}
68
+ {{- '<|im_start|>' + message.role + '\n' + content }}
69
+ {%- endif %}
70
+ {{- '<|im_end|>\n' }}
71
+ {%- endif %}
72
+ {%- endfor %}
73
+ {%- if add_generation_prompt %}
74
+ {{- '<|im_start|>assistant\n' }}
75
+ {%- endif %}
76
+ """
77
+
78
+ custom_qwen3_template = """
79
+ {%- for message in messages %}
80
+ {%- if message.content is string %}
81
+ {%- set content = message.content %}
82
+ {%- else %}
83
+ {%- set content = '' %}
84
+ {%- endif %}
85
+ {%- if (message.role == "user") %}
86
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
87
+ {%- elif message.role == "assistant" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- endif %}
90
+ {%- endfor %}
91
+ {%- if add_generation_prompt %}
92
+ {{- '<|im_start|>assistant\n' }}
93
+ {%- if enable_thinking is defined and enable_thinking is false %}
94
+ {{- '<think>\n\n</think>\n\n' }}
95
+ {%- endif %}
96
+ {%- endif %}
97
+ """
98
+
99
+ custom_gemma3_template = """
100
+ {%- if add_system_prompt %}
101
+ {{- bos_token -}}
102
+ {%- endif %}
103
+ {%- for message in messages -%}
104
+ {%- if message['role'] == 'assistant' -%}
105
+ {%- set role = 'model' -%}
106
+ {%- else -%}
107
+ {%- set role = message['role'] -%}
108
+ {%- endif -%}
109
+ {{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}
110
+ {%- endfor -%}
111
+ {%- if add_generation_prompt -%}
112
+ {{ '<start_of_turn>model\n' }}
113
+ {%- endif -%}
114
+ """
src_code_for_reproducibility/markov_games/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/__init__.py
3
+ Summary: Makes Markov-game subpackages importable from the top-level namespace.
4
+ """
src_code_for_reproducibility/markov_games/agent.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/agent.py
3
+ Summary: Declares the base Agent interface connecting simulations to policy calls.
4
+ """
5
+
6
+ from abc import ABC, abstractmethod
7
+ from collections.abc import Callable
8
+ from typing import Any, Tuple
9
+
10
+ from numpy.random import default_rng
11
+
12
+ from mllm.markov_games.rollout_tree import AgentActLog
13
+
14
+
15
+ class Agent(ABC):
16
+ """Abstract policy wrapper that bridges simulations with arbitrary backends."""
17
+
18
+ @abstractmethod
19
+ def __init__(
20
+ self,
21
+ seed: int,
22
+ agent_id: str,
23
+ agent_name: str,
24
+ agent_policy: Callable[[list[dict]], str],
25
+ *args,
26
+ **kwargs,
27
+ ):
28
+ """
29
+ Initialize the agent state and seed its RNG.
30
+
31
+ Subclasses typically store extra handles (tokenizers, inference clients, etc.)
32
+ but they should always call ``super().__init__`` so sampling remains reproducible.
33
+ """
34
+ self.seed = seed
35
+ self.agent_id = agent_id
36
+ self.agent_name = agent_name
37
+ self.policy = policy
38
+ self.rng = default_rng(self.seed)
39
+ raise NotImplementedError
40
+
41
+ async def act(self, observation) -> Tuple[Any, AgentActLog]:
42
+ """
43
+ Produce the next action (and associated chat log) given an environment observation.
44
+
45
+ Implementations can iterate with rejection sampling, multi-call deliberation, etc.
46
+ Returns both the chosen action and an `AgentActLog` describing how it was produced.
47
+ """
48
+ raise NotImplementedError
49
+
50
+ def get_safe_copy(self):
51
+ """
52
+ Return a deep copy whose future calls do not mutate the original agent.
53
+
54
+ Needed for branch exploration/reruns with alternative actions.
55
+ """
56
+ raise NotImplementedError
57
+
58
+ def reset(self):
59
+ """Reset any internal state between rollouts."""
60
+ raise NotImplementedError
61
+
62
+ def render(self):
63
+ """Optional human-readable visualization of the agent (CLI/UI)."""
64
+ raise NotImplementedError
65
+
66
+ def close(self):
67
+ """Release any external resources (network sockets, subprocesses, etc.)."""
68
+ raise NotImplementedError
69
+
70
+ def get_agent_info(self):
71
+ """Return diagnostic metadata to embed inside rollout logs."""
72
+ raise NotImplementedError
src_code_for_reproducibility/markov_games/alternative_actions_runner.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/alternative_actions_runner.py
3
+ Summary: Generates rollout branches by replaying trajectories with unilateral action changes.
4
+ """
5
+
6
+ import asyncio
7
+ import copy
8
+ import json
9
+ import os.path
10
+ from typing import Any, Tuple
11
+
12
+ from mllm.markov_games.markov_game import AgentAndActionSafeCopy, MarkovGame
13
+ from mllm.markov_games.rollout_tree import (
14
+ AgentActLog,
15
+ RolloutTreeBranchNode,
16
+ RolloutTreeNode,
17
+ RolloutTreeRootNode,
18
+ StepLog,
19
+ )
20
+
21
+ AgentId = str
22
+
23
+
24
+ async def run_with_unilateral_alt_action(
25
+ markov_game: MarkovGame,
26
+ agent_id: AgentId,
27
+ time_step: int,
28
+ branch_node: RolloutTreeBranchNode,
29
+ max_depth: int,
30
+ ):
31
+ """
32
+ Roll out a counterfactual branch where ``agent_id`` deviates unilaterally.
33
+
34
+ Starting from ``branch_node`` (which already contains the main trajectory),
35
+ we replay the simulation with the deviating agent's action while freezing
36
+ all other agents/actions, then continue for ``max_depth`` steps.
37
+ """
38
+
39
+ # Generate alternative action and take a step
40
+ await markov_game.set_action_of_agent(agent_id)
41
+ terminated: bool = markov_game.take_simulation_step()
42
+ step_log = markov_game.get_step_log()
43
+ first_alternative_node = RolloutTreeNode(
44
+ step_log=step_log,
45
+ time_step=time_step,
46
+ )
47
+
48
+ # Generate rest of trajectory up to max depth
49
+ time_step += 1
50
+ counter = 1
51
+ previous_node = first_alternative_node
52
+ while not terminated and counter <= max_depth:
53
+ terminated, step_log = await markov_game.step()
54
+ current_node = RolloutTreeNode(step_log=step_log, time_step=time_step)
55
+ previous_node.child = current_node
56
+ previous_node = current_node
57
+ counter += 1
58
+ time_step += 1
59
+
60
+ if branch_node.branches == None:
61
+ branch_node.branches = {agent_id: [first_alternative_node]}
62
+ else:
63
+ agent_branches = branch_node.branches.get(agent_id, [])
64
+ agent_branches.append(first_alternative_node)
65
+ branch_node.branches[agent_id] = agent_branches
66
+
67
+
68
+ async def AlternativeActionsRunner(
69
+ markov_game: MarkovGame,
70
+ output_folder: str,
71
+ nb_alternative_actions: int,
72
+ max_depth: int,
73
+ branch_only_on_new_round: bool = False,
74
+ ):
75
+ """
76
+ Generate a rollout tree containing the main path plus unilateral deviation branches.
77
+
78
+ For each timestep we:
79
+ 1. Cache agent actions without side effects.
80
+ 2. Advance the main trajectory.
81
+ 3. Spawn ``nb_alternative_actions`` asynchronous deviations per agent,
82
+ each replaying up to ``max_depth`` steps from the cached pre-action state.
83
+ The resulting branches feed advantage-alignment estimators.
84
+ """
85
+
86
+ tasks = []
87
+ time_step = 0
88
+ terminated = False
89
+ root = RolloutTreeRootNode(id=markov_game.get_id(), crn_id=markov_game.get_crn_id())
90
+ previous_node = root
91
+
92
+ while not terminated:
93
+ mg_before_action = markov_game.get_safe_copy()
94
+
95
+ # Get safe copies for main branch
96
+ agent_action_safe_copies: dict[
97
+ AgentId, AgentAndActionSafeCopy
98
+ ] = await markov_game.get_actions_of_agents_without_side_effects()
99
+
100
+ markov_game.set_actions_of_agents_manually(agent_action_safe_copies)
101
+ terminated = markov_game.take_simulation_step()
102
+ main_node = RolloutTreeNode(
103
+ step_log=markov_game.get_step_log(), time_step=time_step
104
+ )
105
+ branch_node = RolloutTreeBranchNode(main_child=main_node)
106
+ previous_node.child = branch_node
107
+ previous_node = main_node
108
+
109
+ # Get alternative branches by generating new unilateral actions
110
+ for agent_id in markov_game.agent_ids:
111
+ for _ in range(nb_alternative_actions):
112
+ # Get safe copies for branches
113
+ branch_agent_action_safe_copies: dict[
114
+ AgentId, AgentAndActionSafeCopy
115
+ ] = {
116
+ agent_id: AgentAndActionSafeCopy(
117
+ action=copy.deepcopy(agent_action_safe_copy.action),
118
+ action_info=copy.deepcopy(agent_action_safe_copy.action_info),
119
+ agent_after_action=agent_action_safe_copy.agent_after_action.get_safe_copy(),
120
+ )
121
+ for agent_id, agent_action_safe_copy in agent_action_safe_copies.items()
122
+ }
123
+ mg_branch: MarkovGame = mg_before_action.get_safe_copy()
124
+ other_agent_id = [id for id in mg_branch.agent_ids if id != agent_id][0]
125
+ mg_branch.set_action_and_agent_after_action_manually(
126
+ agent_id=other_agent_id,
127
+ agent_action_safe_copy=branch_agent_action_safe_copies[
128
+ other_agent_id
129
+ ],
130
+ )
131
+ task = asyncio.create_task(
132
+ run_with_unilateral_alt_action(
133
+ markov_game=mg_branch,
134
+ time_step=time_step,
135
+ agent_id=agent_id,
136
+ branch_node=branch_node,
137
+ max_depth=max_depth,
138
+ )
139
+ )
140
+ tasks.append(task)
141
+ time_step += 1
142
+
143
+ # wait for all branches to complete
144
+ await asyncio.gather(*tasks)
145
+
146
+ return root
src_code_for_reproducibility/markov_games/group_timesteps.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/group_timesteps.py
3
+ Summary: Provides timestep-grouping utilities for rollout trees and training.
4
+ """
5
+
6
+ import copy
7
+ from typing import Callable
8
+
9
+ from mllm.markov_games.markov_game import MarkovGame
10
+ from mllm.markov_games.rollout_tree import (
11
+ AgentActLog,
12
+ RolloutTreeBranchNode,
13
+ RolloutTreeNode,
14
+ RolloutTreeRootNode,
15
+ StepLog,
16
+ )
17
+ from mllm.markov_games.simulation import SimulationStepLog
18
+
19
+ AgentId = str
20
+
21
+
22
+ def group_time_steps(
23
+ rollout_tree: RolloutTreeRootNode,
24
+ accumulation_stop_condition: Callable[[StepLog], bool],
25
+ ) -> RolloutTreeRootNode:
26
+ """
27
+ During generation, we create rollout trees according to the real time steps.
28
+ However, during training, we might want to treat groups of time steps as a single time step.
29
+ As a concrete example, take Trust-and-Split. At each round, say we have X time steps of communication and then one time step for the split.
30
+ Then the communication actions will not get any reward, and the split action will get the reward. During REINFORCE training, with discounting, this
31
+ can cause training instability. We could instead treat every action in the round as being part of a single action, and give it the reward of the split action.
32
+ This method helps to do this sort of grouping.
33
+ It accumulates actions until the accumulation_stop_condition is met, and then creates a new node with the accumulated actions.
34
+ It then recursively calls itself on the child node.
35
+ Details:
36
+ - The reward for the group is the reward of the last time step in the group.
37
+ - The simulation log for the group is the simulation log of the last time step in the group.
38
+ - The state end for the group becomes the first state end in the group.
39
+ - The agent info for the group is the agent info of the last time step in the group.
40
+ """
41
+
42
+ def group_step_logs(step_logs: list[StepLog]) -> StepLog:
43
+ """
44
+ Concatenate per-agent chat turns across steps; keep only the first is_state_end.
45
+ """
46
+ last_sim_log = step_logs[-1].simulation_step_log
47
+ agent_ids = {aid for s in step_logs for aid in s.action_logs.keys()}
48
+ grouped_logs: dict[AgentId, AgentActLog] = {}
49
+ for aid in agent_ids:
50
+ turns = []
51
+ for s in step_logs:
52
+ act = s.action_logs.get(aid)
53
+ if act and act.chat_turns:
54
+ turns.extend(copy.deepcopy(act.chat_turns))
55
+ disable_is_state_end = False
56
+ # Only the first state_end should be True, the rest should be False
57
+ for t in turns:
58
+ if t.is_state_end:
59
+ if disable_is_state_end:
60
+ t.is_state_end = False
61
+ else:
62
+ disable_is_state_end = True
63
+ continue
64
+ grouped_logs[aid] = AgentActLog(
65
+ chat_turns=turns, info=step_logs[-1].action_logs[aid].info
66
+ )
67
+ return StepLog(action_logs=grouped_logs, simulation_step_log=last_sim_log)
68
+
69
+ def group_time_steps_rec(
70
+ current_node: RolloutTreeNode | RolloutTreeBranchNode,
71
+ group_time_step: int,
72
+ accumulation_step_logs: list[StepLog],
73
+ ) -> RolloutTreeNode | RolloutTreeBranchNode:
74
+ """
75
+ Groups time steps. Recursion is used to handle branches.
76
+ """
77
+ assert isinstance(current_node, RolloutTreeNode) or isinstance(
78
+ current_node, RolloutTreeBranchNode
79
+ ), "Current node must be a tree node or a branch node. Is of type: " + str(
80
+ type(current_node)
81
+ )
82
+ first_group_node = None
83
+ current_group_node = None
84
+ while current_node is not None:
85
+ if isinstance(current_node, RolloutTreeBranchNode):
86
+ raise Exception(
87
+ "Grouping timesteps by round is not supported for branching trajectories yet."
88
+ )
89
+
90
+ # Accumulate
91
+ accumulation_step_logs.append(current_node.step_log)
92
+ if accumulation_stop_condition(current_node.step_log):
93
+ grouped_step_logs = group_step_logs(accumulation_step_logs)
94
+ accumulation_step_logs = []
95
+ new_group_node = RolloutTreeNode(
96
+ step_log=grouped_step_logs, time_step=group_time_step, child=None
97
+ )
98
+ if first_group_node == None:
99
+ first_group_node = new_group_node
100
+ group_time_step += 1
101
+ if current_group_node is not None:
102
+ current_group_node.child = new_group_node
103
+ current_group_node = new_group_node
104
+ current_node = current_node.child
105
+ return first_group_node
106
+
107
+ node = group_time_steps_rec(
108
+ current_node=rollout_tree.child, group_time_step=0, accumulation_step_logs=[]
109
+ )
110
+ return RolloutTreeRootNode(
111
+ id=rollout_tree.id,
112
+ crn_id=rollout_tree.crn_id,
113
+ child=node,
114
+ agent_ids=rollout_tree.agent_ids,
115
+ )
116
+
117
+
118
+ def stop_when_round_ends(step_log: StepLog) -> bool:
119
+ """
120
+ Simplest stop condition. Will return True if step log is the last time step of a round.
121
+ This will throw an error if this information is not available in the simulation info.
122
+ """
123
+ assert (
124
+ "is_last_timestep_in_round" in step_log.simulation_step_log.info.keys()
125
+ ), "To group by round, is_last_timestep_in_round must be set in the info of your simulation step log at each time step."
126
+ return step_log.simulation_step_log.info["is_last_timestep_in_round"]
127
+
128
+
129
+ def group_by_round(rollout_tree: RolloutTreeRootNode) -> RolloutTreeRootNode:
130
+ """
131
+ Groups time steps by round.
132
+ """
133
+ return group_time_steps(rollout_tree, stop_when_round_ends)
src_code_for_reproducibility/markov_games/linear_runner.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/linear_runner.py
3
+ Summary: Simulates a single unbranched Markov-game rollout and records it.
4
+ """
5
+
6
+ import asyncio
7
+ import json
8
+ import os.path
9
+
10
+ from mllm.markov_games.markov_game import MarkovGame
11
+ from mllm.markov_games.rollout_tree import RolloutTreeNode, RolloutTreeRootNode
12
+
13
+
14
+ async def LinearRunner(
15
+ markov_game: MarkovGame, output_folder: str
16
+ ) -> RolloutTreeRootNode:
17
+ """
18
+ Generate a single main-path rollout (no branching) for the provided Markov game.
19
+
20
+ Parameters
21
+ ----------
22
+ markov_game:
23
+ Initialized ``MarkovGame`` with agents + simulation ready to step.
24
+ output_folder:
25
+ Unused placeholder in the legacy API (kept for compatibility).
26
+ """
27
+ time_step = 0
28
+ terminated = False
29
+ root = RolloutTreeRootNode(
30
+ id=markov_game.get_id(),
31
+ crn_id=markov_game.get_crn_id(),
32
+ agent_ids=markov_game.get_agent_ids(),
33
+ )
34
+ previous_node = root
35
+ while not terminated:
36
+ terminated, step_log = await markov_game.step()
37
+ current_node = RolloutTreeNode(step_log=step_log, time_step=time_step)
38
+ previous_node.child = current_node
39
+ previous_node = current_node
40
+ time_step += 1
41
+
42
+ return root
src_code_for_reproducibility/markov_games/markov_game.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/markov_game.py
3
+ Summary: Defines the MarkovGame base class plus shared simulation interfaces.
4
+ """
5
+
6
+ import asyncio
7
+ import copy
8
+ import json
9
+ import os
10
+ from dataclasses import dataclass
11
+ from typing import Any, List, Literal, Optional, Tuple
12
+
13
+ from transformers.models.idefics2 import Idefics2Config
14
+
15
+ from mllm.markov_games.agent import Agent
16
+ from mllm.markov_games.rollout_tree import AgentActLog, StepLog
17
+ from mllm.markov_games.simulation import Simulation
18
+
19
+ AgentId = str
20
+
21
+
22
+ @dataclass
23
+ class AgentAndActionSafeCopy:
24
+ """Snapshot of an agent, its action, and metadata used for branch replay."""
25
+
26
+ action: Any
27
+ action_info: AgentActLog
28
+ agent_after_action: type[Agent]
29
+
30
+
31
+ class MarkovGame(object):
32
+ def __init__(
33
+ self,
34
+ id: int,
35
+ agents: dict[AgentId, type[Agent]],
36
+ simulation: type[Simulation],
37
+ crn_id: int,
38
+ ):
39
+ """
40
+ Initialize the Markov game wrapper.
41
+
42
+ Parameters
43
+ ----------
44
+ id:
45
+ Unique rollout identifier (logged into rollout trees).
46
+ agents:
47
+ Mapping of agent_id -> Agent instance.
48
+ simulation:
49
+ Environment implementing the ``Simulation`` interface (IPD, TAS, etc.).
50
+ crn_id:
51
+ Identifier for the common random number stream used by this rollout.
52
+ """
53
+ self.agents = agents
54
+ self.agent_ids = self.agents.keys()
55
+ self.simulation = simulation
56
+ self.simulation_step_log = None
57
+ self.agent_step_logs = {agent_id: None for agent_id in self.agent_ids}
58
+ self.actions = {}
59
+ self.id = id
60
+ self.crn_id = crn_id
61
+
62
+ def get_id(self) -> str:
63
+ return self.id
64
+
65
+ def get_crn_id(self) -> int:
66
+ return self.crn_id
67
+
68
+ def get_agent_ids(self) -> List[AgentId]:
69
+ return list(self.agent_ids)
70
+
71
+ async def get_action_of_agent_without_side_effects(
72
+ self, agent_id: AgentId
73
+ ) -> Tuple[Any, AgentActLog]:
74
+ """
75
+ Safe function to get an action of an agent without modifying the agent or the simulation.
76
+ """
77
+ agent = self.agents[agent_id]
78
+ agent_before_action = agent.get_safe_copy()
79
+ obs = self.simulation.get_obs_agent(agent_id)
80
+ action, action_info = await agent.act(observation=obs)
81
+ self.agents[agent_id] = agent_before_action
82
+ agent_after_action = agent.get_safe_copy()
83
+ return AgentAndActionSafeCopy(action, action_info, agent_after_action)
84
+
85
+ async def get_actions_of_agents_without_side_effects(
86
+ self,
87
+ ) -> dict[AgentId, AgentAndActionSafeCopy]:
88
+ """
89
+ Safe function to get an action of an agent without modifying the agent or the simulation.
90
+ """
91
+ tasks = []
92
+ for agent_id in self.agent_ids:
93
+ task = asyncio.create_task(
94
+ self.get_action_of_agent_without_side_effects(agent_id)
95
+ )
96
+ tasks.append(task)
97
+ agent_and_action_safe_copies: list[
98
+ AgentAndActionSafeCopy
99
+ ] = await asyncio.gather(*tasks)
100
+ return {
101
+ agent_id: agent_and_action_safe_copy
102
+ for agent_id, agent_and_action_safe_copy in zip(
103
+ self.agent_ids, agent_and_action_safe_copies
104
+ )
105
+ }
106
+
107
+ def set_action_and_agent_after_action_manually(
108
+ self,
109
+ agent_id: AgentId,
110
+ agent_action_safe_copy: AgentAndActionSafeCopy,
111
+ ):
112
+ """
113
+ Set the action and the agent after action manually.
114
+ """
115
+ self.actions[agent_id] = agent_action_safe_copy.action
116
+ self.agent_step_logs[agent_id] = agent_action_safe_copy.action_info
117
+ self.agents[agent_id] = agent_action_safe_copy.agent_after_action
118
+
119
+ def set_actions_of_agents_manually(
120
+ self, actions: dict[AgentId, AgentAndActionSafeCopy]
121
+ ):
122
+ """
123
+ Set the actions of agents manually.
124
+ """
125
+ for agent_id, agent_action_safe_copy in actions.items():
126
+ self.set_action_and_agent_after_action_manually(
127
+ agent_id, agent_action_safe_copy
128
+ )
129
+
130
+ async def set_action_of_agent(self, agent_id: AgentId):
131
+ """
132
+ Query a single agent for its next action and store the result locally.
133
+ """
134
+ agent = self.agents[agent_id]
135
+ obs = self.simulation.get_obs_agent(agent_id)
136
+ action, action_info = await agent.act(observation=obs)
137
+ self.actions[agent_id] = action
138
+ self.agent_step_logs[agent_id] = action_info
139
+
140
+ async def set_actions(self):
141
+ """
142
+ Query every agent concurrently and populate the cached actions/logs.
143
+ """
144
+ # background_tasks = set()
145
+ tasks = []
146
+ for agent_id in self.agent_ids:
147
+ task = asyncio.create_task(self.set_action_of_agent(agent_id))
148
+ tasks.append(task)
149
+ await asyncio.gather(*tasks)
150
+
151
+ def take_simulation_step(self):
152
+ """
153
+ Advance the simulation by one step using the cached actions.
154
+ """
155
+ terminated, self.simulation_step_log = self.simulation.step(self.actions)
156
+ return terminated
157
+
158
+ def get_step_log(self) -> StepLog:
159
+ """
160
+ Package the most recent simulation step and agent logs into a StepLog.
161
+ """
162
+ if self.simulation_step_log is None:
163
+ raise RuntimeError(
164
+ "Simulation step log is empty; call take_simulation_step() first."
165
+ )
166
+ missing_logs = [
167
+ agent_id for agent_id, log in self.agent_step_logs.items() if log is None
168
+ ]
169
+ if missing_logs:
170
+ raise RuntimeError(
171
+ f"Agent action logs missing for: {', '.join(missing_logs)}. "
172
+ "Ensure set_actions() ran before requesting the step log."
173
+ )
174
+ step_log = StepLog(
175
+ simulation_step_log=self.simulation_step_log,
176
+ action_logs=self.agent_step_logs,
177
+ )
178
+ return step_log
179
+
180
+ async def step(self) -> Tuple[bool, StepLog]:
181
+ """
182
+ Convenience step that collects actions, advances the simulation, and returns the log.
183
+ """
184
+ await self.set_actions()
185
+ terminated = self.take_simulation_step()
186
+ step_log = self.get_step_log()
187
+ return terminated, step_log
188
+
189
+ def get_safe_copy(self):
190
+ """
191
+ Create a shallow copy of the game with deep-copied agents/simulation for branching.
192
+ """
193
+
194
+ new_markov_game = copy.copy(self)
195
+ new_simulation = self.simulation.get_safe_copy()
196
+ new_agents = {
197
+ agent_id: agent.get_safe_copy() for agent_id, agent in self.agents.items()
198
+ }
199
+
200
+ # Reassign copied components
201
+ new_markov_game.simulation = new_simulation
202
+ new_markov_game.agents = new_agents
203
+
204
+ # IMPORTANT: ensure agent_ids references the new agents dict, not the original
205
+ new_markov_game.agent_ids = new_markov_game.agents.keys()
206
+
207
+ # Deep-copy step data to avoid correlation
208
+ new_markov_game.simulation_step_log = copy.deepcopy(self.simulation_step_log)
209
+ new_markov_game.actions = copy.deepcopy(self.actions)
210
+ # Rebuild logs to align exactly with new agent ids
211
+ old_agent_step_logs = copy.deepcopy(self.agent_step_logs)
212
+ new_markov_game.agent_step_logs = {
213
+ agent_id: old_agent_step_logs.get(agent_id)
214
+ for agent_id in new_markov_game.agent_ids
215
+ }
216
+
217
+ return new_markov_game
src_code_for_reproducibility/markov_games/mg_utils.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/mg_utils.py
3
+ Summary: Holds miscellaneous helpers shared across Markov-game modules.
4
+ """
5
+
6
+ import asyncio
7
+ import copy
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass
10
+
11
+ from mllm.markov_games.ipd.ipd_agent import IPDAgent
12
+ from mllm.markov_games.ipd.Ipd_hard_coded_agents import (
13
+ AlwaysCooperateIPDAgent,
14
+ AlwaysDefectIPDAgent,
15
+ )
16
+ from mllm.markov_games.ipd.ipd_simulation import IPD
17
+ from mllm.markov_games.markov_game import MarkovGame
18
+ from mllm.markov_games.negotiation.dond_agent import DealNoDealAgent
19
+ from mllm.markov_games.negotiation.dond_simulation import DealNoDealSimulation
20
+ from mllm.markov_games.negotiation.nego_hard_coded_policies import (
21
+ HardCodedNegoGreedyPolicy,
22
+ HardCodedNegoWelfareMaximizingPolicy,
23
+ )
24
+ from mllm.markov_games.negotiation.no_press_nego_agent import NoPressAgent
25
+ from mllm.markov_games.negotiation.no_press_nego_simulation import NoPressSimulation
26
+ from mllm.markov_games.negotiation.tas_rps_agent import TrustAndSplitRPSAgent
27
+ from mllm.markov_games.negotiation.tas_rps_simulation import TrustAndSplitRPSSimulation
28
+ from mllm.markov_games.rollout_tree import (
29
+ AgentActLog,
30
+ RolloutTreeBranchNode,
31
+ RolloutTreeNode,
32
+ RolloutTreeRootNode,
33
+ StepLog,
34
+ )
35
+ from mllm.markov_games.simulation import SimulationStepLog
36
+
37
+ AgentId = str
38
+
39
+
40
+ @dataclass
41
+ class AgentConfig:
42
+ """Configuration blob describing one agent in a Markov game spec."""
43
+
44
+ agent_id: str
45
+ agent_name: str
46
+ agent_class_name: str
47
+ policy_id: str
48
+ init_kwargs: dict
49
+
50
+
51
+ @dataclass
52
+ class MarkovGameConfig:
53
+ """Top-level config that ties together simulation settings and agent configs."""
54
+
55
+ id: int
56
+ seed: int
57
+ simulation_class_name: str
58
+ simulation_init_args: dict
59
+ agent_configs: list[AgentConfig]
60
+
61
+
62
+ def init_markov_game_components(
63
+ config: MarkovGameConfig, policies: dict[str, Callable[[list[dict]], str]]
64
+ ):
65
+ """
66
+ Materialize Agents and the Simulation described by ``config`` and return a MarkovGame.
67
+
68
+ `policies` is a mapping of policy_id -> callable retrieved from the hosting trainer.
69
+ """
70
+ agents = {}
71
+ agent_names = []
72
+ for agent_config in config.agent_configs:
73
+ agent_id = agent_config.agent_id
74
+ agent_name = agent_config.agent_name
75
+ agent_class = eval(agent_config.agent_class_name)
76
+ agent = agent_class(
77
+ seed=config.seed,
78
+ agent_id=agent_id,
79
+ agent_name=agent_name,
80
+ policy=policies[agent_config.policy_id],
81
+ **agent_config.init_kwargs,
82
+ )
83
+ agents[agent_id] = agent
84
+ agent_names.append(agent_name)
85
+ simulation = eval(config.simulation_class_name)(
86
+ seed=config.seed,
87
+ agent_ids=list(agents.keys()),
88
+ agent_names=agent_names,
89
+ **config.simulation_init_args,
90
+ )
91
+ markov_game = MarkovGame(
92
+ id=config.id,
93
+ crn_id=config.seed,
94
+ agents=agents,
95
+ simulation=simulation,
96
+ )
97
+ return markov_game
src_code_for_reproducibility/markov_games/rollout_tree.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/rollout_tree.py
3
+ Summary: Defines rollout tree data structures and serialization helpers.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Any, List, Literal, Optional, Tuple
12
+
13
+ import jsonschema
14
+ from pydantic import BaseModel, Field, model_validator
15
+
16
+ from mllm.chat_utils.chat_turn import ChatTurn
17
+
18
+ AgentId = str
19
+
20
+
21
+ class SimulationStepLog(BaseModel):
22
+ """Minimal snapshot of environment-side rewards and auxiliary info."""
23
+
24
+ rewards: dict[AgentId, float]
25
+ info: Any = None
26
+
27
+
28
+ class AgentActLog(BaseModel):
29
+ """LLM-side provenance for an action (chat turns + metadata)."""
30
+
31
+ chat_turns: list[ChatTurn] | None
32
+ info: Any = None
33
+
34
+ @model_validator(mode="after")
35
+ def _exactly_one_state_end(self):
36
+ """
37
+ This method is used to enforce that for each AgentActLog, there is exactly one ChatTurn which is a state end.
38
+ """
39
+ if self.chat_turns != []:
40
+ n = sum(1 for t in self.chat_turns if t.is_state_end)
41
+ if n != 1:
42
+ raise ValueError(
43
+ f"AgentActLog must have exactly one ChatTurn with is_state_end=True; got {self.chat_turns}."
44
+ )
45
+ return self
46
+ else:
47
+ return self
48
+
49
+
50
+ class StepLog(BaseModel):
51
+ action_logs: dict[AgentId, AgentActLog]
52
+ simulation_step_log: SimulationStepLog
53
+
54
+
55
+ # BranchType = Literal["unilateral_deviation", "common_deviation"] # might not be necessary
56
+ # class BranchNodeInfo(BaseModel):
57
+ # branch_id: str
58
+ # branch_for: AgentId
59
+ # branch_type: BranchType
60
+
61
+
62
+ class RolloutTreeNode(BaseModel):
63
+ """Single timestep of the main trajectory (or a branch) plus linkage."""
64
+
65
+ step_log: StepLog
66
+ time_step: int
67
+ child: RolloutTreeNode | RolloutTreeBranchNode | None = None
68
+
69
+
70
+ class RolloutTreeBranchNode(BaseModel):
71
+ """
72
+ First item of the tuple indicates which agent "called" for an alternative branch.
73
+ """
74
+
75
+ main_child: RolloutTreeNode
76
+ branches: dict[AgentId, list[RolloutTreeNode]] | None = None
77
+
78
+
79
+ class RolloutTreeRootNode(BaseModel):
80
+ """Entry point for serialized rollouts (main path plus optional branches)."""
81
+
82
+ id: int
83
+ crn_id: int # ID of the rng used to generate this rollout tree
84
+ child: RolloutTreeNode | RolloutTreeBranchNode | None = None
85
+ agent_ids: List[AgentId] = Field(min_length=1)
86
+
87
+
88
+ # class RolloutTreeLeafNode(BaseModel):
89
+ # step_log: StepLog
90
+ # time_step: int
91
+
92
+
93
+ # Necessary for self-referential stuff in pydantic
94
+ RolloutTreeBranchNode.model_rebuild()
95
+ RolloutTreeNode.model_rebuild()
src_code_for_reproducibility/markov_games/run_markov_games.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/run_markov_games.py
3
+ Summary: CLI entry point for running configured Markov-game experiments.
4
+ """
5
+
6
+ import asyncio
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+
10
+ from torch._C import ClassType
11
+
12
+ from mllm.markov_games.markov_game import MarkovGame
13
+ from mllm.markov_games.rollout_tree import RolloutTreeRootNode
14
+
15
+
16
+ async def run_markov_games(
17
+ runner: Callable[[MarkovGame], RolloutTreeRootNode],
18
+ runner_kwargs: dict,
19
+ output_folder: str,
20
+ markov_games: list[MarkovGame],
21
+ ) -> list[RolloutTreeRootNode]:
22
+ """
23
+ Kick off multiple Markov game rollouts concurrently and return their trees.
24
+
25
+ Parameters mirror the Hydra configs (runner callable + kwargs) so callers can
26
+ choose ``LinearRunner``, ``AlternativeActionsRunner`` or future variants.
27
+ """
28
+ runner_kwargs = dict(runner_kwargs)
29
+ max_parallel_games = runner_kwargs.pop("max_parallel_games", None)
30
+
31
+ async def run_game(markov_game: MarkovGame) -> RolloutTreeRootNode:
32
+ return await runner(
33
+ markov_game=markov_game,
34
+ output_folder=output_folder,
35
+ **runner_kwargs,
36
+ )
37
+
38
+ if max_parallel_games is not None:
39
+ semaphore = asyncio.Semaphore(max(1, int(max_parallel_games)))
40
+
41
+ async def run_game(markov_game: MarkovGame) -> RolloutTreeRootNode:
42
+ async with semaphore:
43
+ return await runner(
44
+ markov_game=markov_game,
45
+ output_folder=output_folder,
46
+ **runner_kwargs,
47
+ )
48
+
49
+ tasks = []
50
+ for mg in markov_games:
51
+ tasks.append(asyncio.create_task(run_game(mg)))
52
+ return await asyncio.gather(*tasks)
src_code_for_reproducibility/markov_games/simulation.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/simulation.py
3
+ Summary: Core simulation loop utilities and step logging for Markov games.
4
+ """
5
+
6
+ from abc import ABC, abstractmethod
7
+ from typing import Any, Tuple
8
+
9
+ from numpy.random import default_rng
10
+
11
+ from mllm.markov_games.rollout_tree import SimulationStepLog
12
+
13
+
14
+ class Simulation(ABC):
15
+ @abstractmethod
16
+ def __init__(self, seed: int, *args, **kwargs):
17
+ self.seed = seed
18
+ self.rng = default_rng(self.seed)
19
+
20
+ @abstractmethod
21
+ def step(self, actions: Any) -> Tuple[bool, SimulationStepLog]:
22
+ """
23
+ Advance the environment by one logical tick using ``actions``.
24
+
25
+ Returns
26
+ -------
27
+ terminated: bool
28
+ Whether the episode has finished.
29
+ SimulationStepLog
30
+ Reward/info bundle describing this transition.
31
+ """
32
+ raise NotImplementedError
33
+
34
+ def get_obs(self):
35
+ """Return a dict mapping agent_id -> observation for *all* agents."""
36
+ raise NotImplementedError
37
+
38
+ def get_obs_agent(self, agent_id):
39
+ """Return the observation for a single agent."""
40
+ raise NotImplementedError
41
+
42
+ def get_obs_size(self):
43
+ """Describe the observation tensor shape (useful for critic heads)."""
44
+ raise NotImplementedError
45
+
46
+ def get_state(self):
47
+ """Return the privileged simulator state if available."""
48
+ raise NotImplementedError
49
+
50
+ def get_state_size(self):
51
+ """Describe the state tensor shape."""
52
+ raise NotImplementedError
53
+
54
+ def get_avail_actions(self):
55
+ """Return the global action mask/tensor if the space is discrete."""
56
+ raise NotImplementedError
57
+
58
+ def get_avail_agent_actions(self, agent_id):
59
+ """Return the available action mask for a given agent."""
60
+ raise NotImplementedError
61
+
62
+ def get_total_actions(self):
63
+ """Returns the total number of actions an agent could ever take.
64
+
65
+ Implementations currently assume a discrete, one-dimensional action space per agent.
66
+ """
67
+ raise NotImplementedError
68
+
69
+ def get_safe_copy(self):
70
+ """
71
+ Return copy of the simulator that shares no mutable state with the original.
72
+ """
73
+ raise NotImplementedError
74
+
75
+ def reset(self):
76
+ """Reset to the initial state and return the starting observations."""
77
+ raise NotImplementedError
78
+
79
+ def render(self):
80
+ """Optional human-facing visualization."""
81
+ raise NotImplementedError
82
+
83
+ def close(self):
84
+ """Release any owned resources (files, processes, etc.)."""
85
+ raise NotImplementedError
86
+
87
+ # def seed(self):
88
+ # raise NotImplementedError
89
+
90
+ def save_replay(self):
91
+ raise NotImplementedError
92
+
93
+ def get_simulation_info(self):
94
+ raise NotImplementedError
src_code_for_reproducibility/markov_games/statistics_runner.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/markov_games/statistics_runner.py
3
+ Summary: Executes multiple rollouts to compute experiment statistics.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import gc
9
+ import json
10
+ import pickle
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional
14
+
15
+ from basic_render import find_iteration_folders
16
+
17
+ from mllm.markov_games.rollout_tree import (
18
+ RolloutTreeBranchNode,
19
+ RolloutTreeNode,
20
+ RolloutTreeRootNode,
21
+ SimulationStepLog,
22
+ )
23
+
24
+
25
+ def _iterate_main_nodes(root: RolloutTreeRootNode) -> Iterator[RolloutTreeNode]:
26
+ """
27
+ Iterate the main path nodes without materializing full path lists.
28
+ """
29
+ current = root.child
30
+ while current is not None:
31
+ if isinstance(current, RolloutTreeNode):
32
+ yield current
33
+ current = current.child
34
+ elif isinstance(current, RolloutTreeBranchNode):
35
+ # Follow only the main child on the main trajectory
36
+ current = current.main_child
37
+ else:
38
+ break
39
+
40
+
41
+ def iterate_main_simulation_logs(
42
+ root: RolloutTreeRootNode,
43
+ ) -> Iterator[SimulationStepLog]:
44
+ """Yield ``SimulationStepLog`` objects along the main (non-branch) path."""
45
+ for node in _iterate_main_nodes(root):
46
+ yield node.step_log.simulation_step_log
47
+
48
+
49
+ def stream_rollout_files(iteration_folder: Path) -> Iterator[Path]:
50
+ """Iterate over every ``*.rt.pkl`` file under an iteration directory."""
51
+ for p in iteration_folder.rglob("*.rt.pkl"):
52
+ if p.is_file():
53
+ yield p
54
+
55
+
56
+ def load_root(path: Path) -> RolloutTreeRootNode:
57
+ """Load and validate a rollout tree from disk."""
58
+ with open(path, "rb") as f:
59
+ data = pickle.load(f)
60
+ return RolloutTreeRootNode.model_validate(data)
61
+
62
+
63
+ @dataclass
64
+ class StatRecord:
65
+ """Convenience container for serialized stat rows."""
66
+
67
+ mgid: int
68
+ crn_id: Optional[int]
69
+ iteration: str
70
+ values: Dict[str, Any]
71
+
72
+
73
+ class StatComputer:
74
+ """
75
+ Stateful stat computer that consumes SimulationStepLog instances
76
+ and produces final aggregated values for one rollout (mgid).
77
+ """
78
+
79
+ def update(self, sl: SimulationStepLog) -> None: # pragma: no cover - interface
80
+ raise NotImplementedError
81
+
82
+ def finalize(self) -> Dict[str, Any]: # pragma: no cover - interface
83
+ raise NotImplementedError
84
+
85
+
86
+ def run_stats(
87
+ data_root: Path,
88
+ game_name: str,
89
+ make_computers: Callable[[], List[StatComputer]],
90
+ output_filename: Optional[str] = None,
91
+ output_format: str = "json", # "json" (dict of lists) or "jsonl"
92
+ ) -> Path:
93
+ """
94
+ Compute stats across all iteration_* folders under data_root.
95
+ Writes JSONL to data_root/statistics/<output_filename or f"{game_name}.stats.jsonl">.
96
+ """
97
+ data_root = Path(data_root)
98
+ outdir = data_root / "statistics"
99
+ outdir.mkdir(parents=True, exist_ok=True)
100
+ # Choose extension by format
101
+ default_name = (
102
+ f"{game_name}.stats.json"
103
+ if output_format == "json"
104
+ else f"{game_name}.stats.jsonl"
105
+ )
106
+ outfile = outdir / (
107
+ output_filename if output_filename is not None else default_name
108
+ )
109
+
110
+ # Rewrite file each run to keep it clean and small
111
+ if outfile.exists():
112
+ outfile.unlink()
113
+
114
+ iteration_folders = find_iteration_folders(str(data_root))
115
+
116
+ # If writing JSONL, stream directly; otherwise accumulate minimal records
117
+ if output_format == "jsonl":
118
+ with open(outfile, "w", encoding="utf-8") as w:
119
+ for iteration_folder in iteration_folders:
120
+ iteration_name = Path(iteration_folder).name
121
+ for pkl_path in stream_rollout_files(Path(iteration_folder)):
122
+ root = load_root(pkl_path)
123
+
124
+ computers = make_computers()
125
+ for sl in iterate_main_simulation_logs(root):
126
+ for comp in computers:
127
+ try:
128
+ comp.update(sl)
129
+ except Exception:
130
+ continue
131
+
132
+ values: Dict[str, Any] = {}
133
+ for comp in computers:
134
+ try:
135
+ values.update(comp.finalize())
136
+ except Exception:
137
+ continue
138
+
139
+ rec = {
140
+ "mgid": getattr(root, "id", None),
141
+ "crn_id": getattr(root, "crn_id", None),
142
+ "iteration": iteration_name,
143
+ "stats": values,
144
+ }
145
+ w.write(json.dumps(rec, ensure_ascii=False) + "\n")
146
+
147
+ del root
148
+ del computers
149
+ gc.collect()
150
+ else:
151
+ # Aggregate to dict-of-lists for easier plotting
152
+ records: List[Dict[str, Any]] = []
153
+ # Process in deterministic order
154
+ for iteration_folder in iteration_folders:
155
+ iteration_name = Path(iteration_folder).name
156
+ for pkl_path in stream_rollout_files(Path(iteration_folder)):
157
+ root = load_root(pkl_path)
158
+
159
+ computers = make_computers()
160
+ for sl in iterate_main_simulation_logs(root):
161
+ for comp in computers:
162
+ try:
163
+ comp.update(sl)
164
+ except Exception:
165
+ continue
166
+
167
+ values: Dict[str, Any] = {}
168
+ for comp in computers:
169
+ try:
170
+ values.update(comp.finalize())
171
+ except Exception:
172
+ continue
173
+
174
+ records.append(
175
+ {
176
+ "mgid": getattr(root, "id", None),
177
+ "crn_id": getattr(root, "crn_id", None),
178
+ "iteration": iteration_name,
179
+ "stats": values,
180
+ }
181
+ )
182
+
183
+ del root
184
+ del computers
185
+ gc.collect()
186
+
187
+ # Build dict-of-lists with nested stats preserved
188
+ # Collect all stat keys and nested agent keys where needed
189
+ mgids: List[Any] = []
190
+ crn_ids: List[Any] = []
191
+ iterations_out: List[str] = []
192
+ # stats_out is a nested structure mirroring keys but with lists
193
+ stats_out: Dict[str, Any] = {}
194
+
195
+ # First pass to collect union of keys
196
+ stat_keys: set[str] = set()
197
+ nested_agent_keys: Dict[str, set[str]] = {}
198
+ for r in records:
199
+ stats = r.get("stats", {}) or {}
200
+ for k, v in stats.items():
201
+ stat_keys.add(k)
202
+ if isinstance(v, dict):
203
+ nested = nested_agent_keys.setdefault(k, set())
204
+ for ak in v.keys():
205
+ nested.add(str(ak))
206
+
207
+ # Initialize structure
208
+ for k in stat_keys:
209
+ if k in nested_agent_keys:
210
+ stats_out[k] = {ak: [] for ak in sorted(nested_agent_keys[k])}
211
+ else:
212
+ stats_out[k] = []
213
+
214
+ # Fill lists
215
+ for r in records:
216
+ mgids.append(r.get("mgid"))
217
+ crn_ids.append(r.get("crn_id"))
218
+ iterations_out.append(r.get("iteration"))
219
+ stats = r.get("stats", {}) or {}
220
+ for k in stat_keys:
221
+ val = stats.get(k)
222
+ if isinstance(stats_out[k], dict):
223
+ # per-agent dict
224
+ agent_dict = val if isinstance(val, dict) else {}
225
+ for ak in stats_out[k].keys():
226
+ stats_out[k][ak].append(agent_dict.get(ak))
227
+ else:
228
+ stats_out[k].append(val)
229
+
230
+ with open(outfile, "w", encoding="utf-8") as w:
231
+ json.dump(
232
+ {
233
+ "mgid": mgids,
234
+ "crn_id": crn_ids,
235
+ "iteration": iterations_out,
236
+ "stats": stats_out,
237
+ },
238
+ w,
239
+ ensure_ascii=False,
240
+ )
241
+
242
+ return outfile
243
+
244
+
245
+ def run_stats_functional(
246
+ data_root: Path,
247
+ game_name: str,
248
+ metrics: Dict[str, Callable[[SimulationStepLog], Optional[Dict[str, float]]]],
249
+ output_filename: Optional[str] = None,
250
+ output_format: str = "json",
251
+ ) -> Path:
252
+ """
253
+ Functional variant where metrics is a dict of name -> f(SimulationStepLog) -> {agent_id: value}.
254
+ Aggregates per rollout by averaging over steps where a metric produced a value.
255
+ Writes a single consolidated file in data_root/statistics/.
256
+ """
257
+ data_root = Path(data_root)
258
+ outdir = data_root / "statistics"
259
+ outdir.mkdir(parents=True, exist_ok=True)
260
+ default_name = (
261
+ f"{game_name}.stats.json"
262
+ if output_format == "json"
263
+ else f"{game_name}.stats.jsonl"
264
+ )
265
+ outfile = outdir / (
266
+ output_filename if output_filename is not None else default_name
267
+ )
268
+
269
+ if outfile.exists():
270
+ outfile.unlink()
271
+
272
+ iteration_folders = find_iteration_folders(str(data_root))
273
+
274
+ def finalize_rollout(
275
+ agg: Dict[str, Dict[str, List[float]]]
276
+ ) -> Dict[str, Dict[str, float]]:
277
+ # avg per metric per agent
278
+ result: Dict[str, Dict[str, float]] = {}
279
+ for mname, agent_values in agg.items():
280
+ result[mname] = {}
281
+ for aid, vals in agent_values.items():
282
+ if not vals:
283
+ result[mname][aid] = None # keep alignment; could be None
284
+ else:
285
+ result[mname][aid] = sum(vals) / len(vals)
286
+ return result
287
+
288
+ if output_format == "jsonl":
289
+ with open(outfile, "w", encoding="utf-8") as w:
290
+ for iteration_folder in iteration_folders:
291
+ iteration_name = Path(iteration_folder).name
292
+ for pkl_path in stream_rollout_files(Path(iteration_folder)):
293
+ root = load_root(pkl_path)
294
+
295
+ # aggregator structure: metric -> agent_id -> list of values
296
+ agg: Dict[str, Dict[str, List[float]]] = {
297
+ m: {} for m in metrics.keys()
298
+ }
299
+
300
+ for sl in iterate_main_simulation_logs(root):
301
+ for mname, fn in metrics.items():
302
+ try:
303
+ vals = fn(sl)
304
+ except Exception:
305
+ vals = None
306
+ if not vals:
307
+ continue
308
+ for aid, v in vals.items():
309
+ if v is None:
310
+ continue
311
+ lst = agg[mname].setdefault(str(aid), [])
312
+ try:
313
+ lst.append(float(v))
314
+ except Exception:
315
+ continue
316
+
317
+ values = finalize_rollout(agg)
318
+ rec = {
319
+ "mgid": getattr(root, "id", None),
320
+ "crn_id": getattr(root, "crn_id", None),
321
+ "iteration": iteration_name,
322
+ "stats": values,
323
+ }
324
+ w.write(json.dumps(rec, ensure_ascii=False) + "\n")
325
+
326
+ del root
327
+ gc.collect()
328
+ else:
329
+ records: List[Dict[str, Any]] = []
330
+ for iteration_folder in iteration_folders:
331
+ iteration_name = Path(iteration_folder).name
332
+ for pkl_path in stream_rollout_files(Path(iteration_folder)):
333
+ root = load_root(pkl_path)
334
+
335
+ agg: Dict[str, Dict[str, List[float]]] = {m: {} for m in metrics.keys()}
336
+ for sl in iterate_main_simulation_logs(root):
337
+ for mname, fn in metrics.items():
338
+ try:
339
+ vals = fn(sl)
340
+ except Exception:
341
+ vals = None
342
+ if not vals:
343
+ continue
344
+ for aid, v in vals.items():
345
+ if v is None:
346
+ continue
347
+ lst = agg[mname].setdefault(str(aid), [])
348
+ try:
349
+ lst.append(float(v))
350
+ except Exception:
351
+ continue
352
+
353
+ values = finalize_rollout(agg)
354
+ records.append(
355
+ {
356
+ "mgid": getattr(root, "id", None),
357
+ "crn_id": getattr(root, "crn_id", None),
358
+ "iteration": iteration_name,
359
+ "stats": values,
360
+ }
361
+ )
362
+
363
+ del root
364
+ gc.collect()
365
+
366
+ # Build dict-of-lists output
367
+ mgids: List[Any] = []
368
+ crn_ids: List[Any] = []
369
+ iterations_out: List[str] = []
370
+ stats_out: Dict[str, Any] = {}
371
+
372
+ stat_keys: set[str] = set()
373
+ nested_agent_keys: Dict[str, set[str]] = {}
374
+ for r in records:
375
+ stats = r.get("stats", {}) or {}
376
+ for k, v in stats.items():
377
+ stat_keys.add(k)
378
+ if isinstance(v, dict):
379
+ nested = nested_agent_keys.setdefault(k, set())
380
+ for ak in v.keys():
381
+ nested.add(str(ak))
382
+
383
+ for k in stat_keys:
384
+ if k in nested_agent_keys:
385
+ stats_out[k] = {ak: [] for ak in sorted(nested_agent_keys[k])}
386
+ else:
387
+ stats_out[k] = []
388
+
389
+ for r in records:
390
+ mgids.append(r.get("mgid"))
391
+ crn_ids.append(r.get("crn_id"))
392
+ iterations_out.append(r.get("iteration"))
393
+ stats = r.get("stats", {}) or {}
394
+ for k in stat_keys:
395
+ val = stats.get(k)
396
+ if isinstance(stats_out[k], dict):
397
+ agent_dict = val if isinstance(val, dict) else {}
398
+ for ak in stats_out[k].keys():
399
+ stats_out[k][ak].append(agent_dict.get(ak))
400
+ else:
401
+ stats_out[k].append(val)
402
+
403
+ with open(outfile, "w", encoding="utf-8") as w:
404
+ json.dump(
405
+ {
406
+ "mgid": mgids,
407
+ "crn_id": crn_ids,
408
+ "iteration": iterations_out,
409
+ "stats": stats_out,
410
+ },
411
+ w,
412
+ ensure_ascii=False,
413
+ )
414
+
415
+ return outfile
src_code_for_reproducibility/models/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ File: mllm/models/__init__.py
3
+ Summary: Exports model-layer utilities from the models package.
4
+ """
src_code_for_reproducibility/models/__pycache__/human_policy.cpython-312.pyc ADDED
Binary file (12.1 kB). View file
 
src_code_for_reproducibility/models/__pycache__/inference_backend_dummy.cpython-312.pyc ADDED
Binary file (2.48 kB). View file
 
src_code_for_reproducibility/models/__pycache__/inference_backend_vllm.cpython-312.pyc ADDED
Binary file (5.11 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/models/__pycache__/large_language_model_gemini_api.cpython-312.pyc ADDED
Binary file (8.78 kB). View file
 
src_code_for_reproducibility/models/__pycache__/large_language_model_local.cpython-312.pyc ADDED
Binary file (16.5 kB). View file
 
src_code_for_reproducibility/models/__pycache__/scalar_critic.cpython-312.pyc ADDED
Binary file (3.31 kB). View file
 
src_code_for_reproducibility/models/adapter_training_wrapper.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/adapter_training_wrapper.py
3
+ Summary: Wraps a shared LLM with adapter-specific PEFT handling for training.
4
+ """
5
+
6
+ import logging
7
+ from typing import Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from peft import LoraConfig, get_peft_model
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class AdapterWrapper(nn.Module):
17
+ """
18
+ A thin façade that
19
+ • keeps a reference to a *shared* PEFT-wrapped model,
20
+ • ensures `set_adapter(adapter)` is called on every forward,
21
+ • exposes only the parameters that should be trained for that adapter
22
+ (plus whatever extra modules you name).
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ shared_llm: nn.Module,
28
+ adapter_id: str,
29
+ lora_config: dict,
30
+ path: Union[str, None] = None,
31
+ ):
32
+ super().__init__()
33
+ self.shared_llm = shared_llm
34
+ self.adapter_id = adapter_id
35
+ lora_config = LoraConfig(**lora_config)
36
+ # this modifies the shared llm in place, adding a lora adapter inside
37
+ self.shared_llm = get_peft_model(
38
+ model=shared_llm,
39
+ peft_config=lora_config,
40
+ adapter_name=adapter_id,
41
+ )
42
+ self.shared_llm.train()
43
+ # Load external adapter weights if provided
44
+ loaded_from: str | None = None
45
+ if path:
46
+ try:
47
+ # Supports both local filesystem paths and HF Hub repo IDs
48
+ self.shared_llm.load_adapter(
49
+ is_trainable=True,
50
+ model_id=path,
51
+ adapter_name=adapter_id,
52
+ )
53
+ loaded_from = path
54
+ except (
55
+ Exception
56
+ ) as exc: # noqa: BLE001 - want to log any load failure context
57
+ logger.warning(
58
+ f"Adapter '{adapter_id}': failed to load from '{path}': {exc}"
59
+ )
60
+
61
+ if loaded_from:
62
+ logger.info(
63
+ f"Adapter '{adapter_id}': loaded initial weights from '{loaded_from}'."
64
+ )
65
+ else:
66
+ logger.info(
67
+ f"Adapter '{adapter_id}': initialized with fresh weights (no initial weights found)."
68
+ )
69
+
70
+ def parameters(self, recurse: bool = True):
71
+ """
72
+ "recurse" is just for pytorch compatibility
73
+ """
74
+ self.shared_llm.set_adapter(self.adapter_id)
75
+ params = [p for p in self.shared_llm.parameters() if p.requires_grad]
76
+
77
+ return params
78
+
79
+ def get_base_model_logits(self, contexts):
80
+ """
81
+ Run the base model (without adapter) in inference mode, without tracking gradients.
82
+ This is useful to get reference logits for KL-divergence computation.
83
+ """
84
+ with torch.no_grad():
85
+ with self.shared_llm.disable_adapter():
86
+ return self.shared_llm(input_ids=contexts)[0]
87
+
88
+ def forward(self, *args, **kwargs):
89
+ self.shared_llm.set_adapter(self.adapter_id)
90
+ return self.shared_llm(*args, **kwargs)
91
+
92
+ def save_pretrained(self, save_path):
93
+ self.shared_llm.save_pretrained(save_path)
94
+
95
+ def gradient_checkpointing_enable(self, *args, **kwargs):
96
+ self.shared_llm.gradient_checkpointing_enable(*args, **kwargs)
97
+
98
+ @property
99
+ def dtype(self):
100
+ return self.shared_llm.dtype
101
+
102
+ @property
103
+ def device(self):
104
+ return self.shared_llm.device
src_code_for_reproducibility/models/human_policy.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/human_policy.py
3
+ Summary: Implements an interactive human-in-the-loop policy for experiments.
4
+ """
5
+
6
+ import asyncio
7
+ import os
8
+ import re
9
+ import shutil
10
+ import sys
11
+ from typing import Callable, Dict, List, Optional
12
+
13
+ from mllm.markov_games.rollout_tree import ChatTurn
14
+
15
+ try:
16
+ import rstr # For generating example strings from regex
17
+ except Exception: # pragma: no cover
18
+ rstr = None
19
+
20
+
21
+ def _clear_terminal() -> None:
22
+ """
23
+ Clear the terminal screen in a cross-platform manner.
24
+ """
25
+ if sys.stdout.isatty():
26
+ os.system("cls" if os.name == "nt" else "clear")
27
+
28
+
29
+ def _terminal_width(default: int = 100) -> int:
30
+ try:
31
+ return shutil.get_terminal_size().columns
32
+ except Exception:
33
+ return default
34
+
35
+
36
+ def _horizontal_rule(char: str = "─") -> str:
37
+ width = max(20, _terminal_width() - 2)
38
+ return char * width
39
+
40
+
41
+ class _Style:
42
+ # ANSI colors (bright, readable)
43
+ RESET = "\033[0m"
44
+ BOLD = "\033[1m"
45
+ DIM = "\033[2m"
46
+ # Foreground colors
47
+ FG_BLUE = "\033[94m" # user/system headers
48
+ FG_GREEN = "\033[92m" # human response header
49
+ FG_YELLOW = "\033[93m" # notices
50
+ FG_RED = "\033[91m" # errors
51
+ FG_MAGENTA = "\033[95m" # regex
52
+ FG_CYAN = "\033[96m" # tips
53
+
54
+
55
+ def _render_chat(state) -> str:
56
+ """
57
+ Render prior messages in a compact, readable terminal format.
58
+
59
+ Expected message dict keys: {"role": str, "content": str, ...}
60
+ """
61
+ lines: List[str] = []
62
+ lines.append(_horizontal_rule())
63
+ lines.append(f"{_Style.FG_BLUE}{_Style.BOLD} Conversation so far {_Style.RESET}")
64
+ lines.append(_horizontal_rule())
65
+ for chat in state:
66
+ role = chat.role
67
+ content = str(chat.content).strip()
68
+ # Map roles to display names and colors/emojis
69
+ if role == "assistant":
70
+ header = f"{_Style.FG_GREEN}{_Style.BOLD}HUMAN--🧑‍💻{_Style.RESET}"
71
+ elif role == "user":
72
+ header = f"{_Style.FG_BLUE}{_Style.BOLD}USER--⚙️{_Style.RESET}"
73
+ else:
74
+ header = f"[{_Style.DIM}{role.upper()}{_Style.RESET}]"
75
+ lines.append(header)
76
+ # Indent content for readability
77
+ for line in content.splitlines() or [""]:
78
+ lines.append(f" {line}")
79
+ lines.append("")
80
+ lines.append(_horizontal_rule())
81
+ return "\n".join(lines)
82
+
83
+
84
+ async def _async_input(prompt_text: str) -> str:
85
+ """Non-blocking input using a background thread."""
86
+ return await asyncio.to_thread(input, prompt_text)
87
+
88
+
89
+ def _short_regex_example(regex: str, max_len: int = 30) -> Optional[str]:
90
+ """
91
+ Try to produce a short example string that matches the regex.
92
+ We attempt multiple times and pick the first <= max_len.
93
+ """
94
+ if rstr is None:
95
+ return None
96
+ try:
97
+ for _ in range(20):
98
+ candidate = rstr.xeger(regex)
99
+ if len(candidate) <= max_len:
100
+ return candidate
101
+ # Fallback to truncation (may break match, so don't return)
102
+ return None
103
+ except Exception:
104
+ return None
105
+
106
+
107
+ def _detect_input_type(regex: str | None) -> tuple[str, str, str]:
108
+ """
109
+ Detect what type of input is expected based on the regex pattern.
110
+ Returns (input_type, start_tag, end_tag)
111
+ """
112
+ if regex is None:
113
+ return "text", "", ""
114
+
115
+ if "message_start" in regex and "message_end" in regex:
116
+ return "message", "<<message_start>>", "<<message_end>>"
117
+ elif "proposal_start" in regex and "proposal_end" in regex:
118
+ return "proposal", "<<proposal_start>>", "<<proposal_end>>"
119
+ else:
120
+ return "text", "", ""
121
+
122
+
123
+ async def human_policy(state, agent_id, regex: str | None = None) -> str:
124
+ """
125
+ Async human-in-the-loop policy.
126
+
127
+ - Displays prior conversation context in the terminal.
128
+ - Prompts the user for a response.
129
+ - If a regex is provided, validates and re-prompts until it matches.
130
+ - Automatically adds formatting tags based on expected input type.
131
+
132
+ Args:
133
+ prompt: Chat history as a list of {role, content} dicts.
134
+ regex: Optional fullmatch validation pattern.
135
+
136
+ Returns:
137
+ The user's validated response string.
138
+ """
139
+ # Detect input type and formatting
140
+ input_type, start_tag, end_tag = _detect_input_type(regex)
141
+
142
+ while True:
143
+ _clear_terminal()
144
+ print(_render_chat(state))
145
+
146
+ if regex:
147
+ example = _short_regex_example(regex, max_len=30)
148
+ print(
149
+ f"{_Style.FG_MAGENTA}{_Style.BOLD}Expected format (regex fullmatch):{_Style.RESET}"
150
+ )
151
+ print(f" {_Style.FG_MAGENTA}{regex}{_Style.RESET}")
152
+ if example:
153
+ print(
154
+ f"{_Style.FG_CYAN}Example (random, <=30 chars):{_Style.RESET} {example}"
155
+ )
156
+ print(_horizontal_rule("."))
157
+
158
+ # Custom prompt based on input type
159
+ if input_type == "message":
160
+ print(
161
+ f"{_Style.FG_YELLOW}Type your message content (formatting will be added automatically):{_Style.RESET}"
162
+ )
163
+ elif input_type == "proposal":
164
+ print(
165
+ f"{_Style.FG_YELLOW}Type your proposal (number only, formatting will be added automatically):{_Style.RESET}"
166
+ )
167
+ else:
168
+ print(
169
+ f"{_Style.FG_YELLOW}Type your response and press Enter.{_Style.RESET}"
170
+ )
171
+
172
+ print(
173
+ f"{_Style.DIM}Commands: /help to view commands, /refresh to re-render, /quit to abort{_Style.RESET}"
174
+ )
175
+ else:
176
+ print(
177
+ f"{_Style.FG_YELLOW}Type your response and press Enter.{_Style.RESET} {_Style.DIM}(/help for commands){_Style.RESET}"
178
+ )
179
+
180
+ user_in = (await _async_input("> ")).rstrip("\n")
181
+
182
+ # Commands
183
+ if user_in.strip().lower() in {"/help", "/h"}:
184
+ print(f"\n{_Style.FG_CYAN}{_Style.BOLD}Available commands:{_Style.RESET}")
185
+ print(
186
+ f" {_Style.FG_CYAN}/help{_Style.RESET} or {_Style.FG_CYAN}/h{_Style.RESET} Show this help"
187
+ )
188
+ print(
189
+ f" {_Style.FG_CYAN}/refresh{_Style.RESET} or {_Style.FG_CYAN}/r{_Style.RESET} Re-render the conversation and prompt"
190
+ )
191
+ print(
192
+ f" {_Style.FG_CYAN}/quit{_Style.RESET} or {_Style.FG_CYAN}/q{_Style.RESET} Abort the run (raises KeyboardInterrupt)"
193
+ )
194
+ await asyncio.sleep(1.0)
195
+ continue
196
+ if user_in.strip().lower() in {"/refresh", "/r"}:
197
+ continue
198
+ if user_in.strip().lower() in {"/quit", "/q"}:
199
+ raise KeyboardInterrupt("Human aborted run from human_policy")
200
+
201
+ # Add formatting tags if needed
202
+ if start_tag and end_tag:
203
+ formatted_input = f"{start_tag}{user_in}{end_tag}"
204
+ else:
205
+ formatted_input = user_in
206
+
207
+ if regex is None:
208
+ return ChatTurn(
209
+ role="assistant", agent_id=agent_id, content=formatted_input
210
+ )
211
+
212
+ # Validate against regex (fullmatch)
213
+ try:
214
+ pattern = re.compile(regex)
215
+ except re.error as e:
216
+ # If regex is invalid, fall back to accepting any input
217
+ print(
218
+ f"{_Style.FG_RED}Warning:{_Style.RESET} Provided regex is invalid: {e}. Accepting input without validation."
219
+ )
220
+ await asyncio.sleep(0.5)
221
+ return ChatTurn(
222
+ role="assistant", agent_id=agent_id, content=formatted_input
223
+ )
224
+
225
+ if pattern.fullmatch(formatted_input):
226
+ return ChatTurn(
227
+ role="assistant", agent_id=agent_id, content=formatted_input
228
+ )
229
+
230
+ # Show validation error and re-prompt
231
+ print("")
232
+ print(
233
+ f"{_Style.FG_RED}{_Style.BOLD}Input did not match the required format.{_Style.RESET} Please try again."
234
+ )
235
+
236
+ if input_type == "message":
237
+ print(
238
+ f"You entered: {_Style.FG_CYAN}{start_tag}{user_in}{end_tag}{_Style.RESET}"
239
+ )
240
+ print(f"Just type the message content without tags.")
241
+ elif input_type == "proposal":
242
+ print(
243
+ f"You entered: {_Style.FG_CYAN}{start_tag}{user_in}{end_tag}{_Style.RESET}"
244
+ )
245
+ print(f"Just type the number without tags.")
246
+ else:
247
+ print(f"Expected (regex):")
248
+ print(f" {_Style.FG_MAGENTA}{regex}{_Style.RESET}")
249
+
250
+ print(_horizontal_rule("."))
251
+ print(f"{_Style.FG_YELLOW}Press Enter to retry...{_Style.RESET}")
252
+ await _async_input("")
253
+
254
+
255
+ def get_human_policies() -> Dict[str, Callable[[List[Dict]], str]]:
256
+ """
257
+ Expose the human policy in the same map shape used elsewhere.
258
+ """
259
+ # Type hint says Callable[[List[Dict]], str] but we intentionally return the async callable.
260
+ return {"human_policy": human_policy} # type: ignore[return-value]
src_code_for_reproducibility/models/inference_backend.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/inference_backend.py
3
+ Summary: Declares the inference backend interface and shared dataclasses.
4
+ """
5
+
6
+ from abc import ABC, abstractmethod
7
+ from dataclasses import dataclass
8
+ from typing import Any, Optional
9
+
10
+
11
+ @dataclass
12
+ class LLMInferenceOutput:
13
+ content: str
14
+ reasoning_content: str | None = None
15
+ log_probs: list[float] | None = None
16
+ out_token_ids: list[int] | None = None
17
+
18
+
19
+ class LLMInferenceBackend(ABC):
20
+ @abstractmethod
21
+ def __init__(self, **kwargs):
22
+ ...
23
+
24
+ @abstractmethod
25
+ def prepare_adapter(
26
+ self, adapter_id: str, weights_got_updated: bool = False
27
+ ) -> None:
28
+ """Ensure adapter is ready/loaded for next generation call."""
29
+
30
+ @abstractmethod
31
+ async def generate(self, prompt: list[dict], regex: Optional[str] = None) -> str:
32
+ ...
33
+
34
+ @abstractmethod
35
+ def toggle_training_mode(self) -> None:
36
+ ...
37
+
38
+ @abstractmethod
39
+ def toggle_eval_mode(self) -> None:
40
+ ...
41
+
42
+ @abstractmethod
43
+ def shutdown(self) -> None:
44
+ ...
src_code_for_reproducibility/models/inference_backend_dummy.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/inference_backend_dummy.py
3
+ Summary: Stub inference backend that returns synthetic completions for tests.
4
+ """
5
+
6
+ import asyncio
7
+ from typing import Optional
8
+
9
+ import rstr
10
+ from transformers import AutoTokenizer
11
+
12
+ from mllm.models.inference_backend import LLMInferenceBackend, LLMInferenceOutput
13
+ from mllm.utils.short_id_gen import generate_short_id
14
+
15
+
16
+ class DummyInferenceBackend(LLMInferenceBackend):
17
+ def __init__(
18
+ self,
19
+ *args,
20
+ **kwargs,
21
+ ):
22
+ pass
23
+
24
+ def prepare_adapter(
25
+ self,
26
+ adapter_id: Optional[str],
27
+ weights_got_updated: bool,
28
+ adapter_path: Optional[str] = None,
29
+ ) -> None:
30
+ pass
31
+
32
+ async def toggle_training_mode(self) -> None:
33
+ await asyncio.sleep(0)
34
+ pass
35
+
36
+ async def toggle_eval_mode(self) -> None:
37
+ await asyncio.sleep(0)
38
+ pass
39
+
40
+ def shutdown(self) -> None:
41
+ pass
42
+
43
+ async def generate(
44
+ self,
45
+ prompt_text: str,
46
+ regex: Optional[str] = None,
47
+ extract_thinking: bool = False,
48
+ ) -> LLMInferenceOutput:
49
+ if regex:
50
+ # Create random string that respects the regex
51
+ return LLMInferenceOutput(
52
+ content=rstr.xeger(regex),
53
+ reasoning_content="I don't think, I am a dummy backend.",
54
+ )
55
+ else:
56
+ return LLMInferenceOutput(
57
+ content="I am a dummy backend without a regex.",
58
+ reasoning_content="I don't think, I am a dummy backend.",
59
+ )
src_code_for_reproducibility/models/inference_backend_vllm.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/inference_backend_vllm.py
3
+ Summary: Connects to in-process vLLM instances for batched generation.
4
+ """
5
+
6
+ import asyncio
7
+ import re
8
+ from typing import Optional
9
+
10
+ import torch
11
+ from transformers import AutoTokenizer
12
+ from vllm import AsyncEngineArgs, AsyncLLMEngine, SamplingParams
13
+ from vllm.inputs import TokensPrompt
14
+ from vllm.lora.request import LoRARequest
15
+ from vllm.sampling_params import GuidedDecodingParams, RequestOutputKind
16
+
17
+ from mllm.models.inference_backend import LLMInferenceBackend, LLMInferenceOutput
18
+ from mllm.utils.short_id_gen import generate_short_id
19
+
20
+
21
+ class VLLMAsyncBackend(LLMInferenceBackend):
22
+ def __init__(
23
+ self,
24
+ model_name: str,
25
+ tokenizer: AutoTokenizer,
26
+ # adapter_paths: dict[str, str],
27
+ engine_init_kwargs: dict = {},
28
+ sampling_params: dict = {},
29
+ ):
30
+ self.model_name = model_name
31
+ self.vllm_adapter_ids = {}
32
+ ea = dict(model=model_name, **engine_init_kwargs)
33
+ self.engine = AsyncLLMEngine.from_engine_args(AsyncEngineArgs(**ea))
34
+
35
+ self.sampling_params = sampling_params
36
+ self.tokenizer = tokenizer
37
+
38
+ def prepare_adapter(
39
+ self,
40
+ adapter_id: Optional[str],
41
+ adapter_path: Optional[str],
42
+ weights_got_updated: bool,
43
+ ) -> None:
44
+ if weights_got_updated:
45
+ self.vllm_adapter_ids[adapter_id] = generate_short_id()
46
+ self.current_lora_request = LoRARequest(
47
+ adapter_id,
48
+ self.vllm_adapter_ids[adapter_id],
49
+ adapter_path,
50
+ )
51
+
52
+ async def toggle_training_mode(self) -> None:
53
+ await self.engine.sleep(level=1)
54
+
55
+ async def toggle_eval_mode(self) -> None:
56
+ await self.engine.wake_up()
57
+
58
+ def shutdown(self) -> None:
59
+ # No explicit close call; engine stops when process exits.
60
+ pass
61
+
62
+ async def generate(
63
+ self,
64
+ input_token_ids: list[int],
65
+ regex: Optional[str] = None,
66
+ extract_thinking: bool = False,
67
+ ) -> LLMInferenceOutput:
68
+ # Build SamplingParams correctly
69
+ guided = GuidedDecodingParams(regex=regex) if regex else None
70
+ sp = SamplingParams(
71
+ **self.sampling_params,
72
+ guided_decoding=guided,
73
+ output_kind=RequestOutputKind.FINAL_ONLY,
74
+ )
75
+
76
+ prompt = TokensPrompt(prompt_token_ids=input_token_ids)
77
+ request_id = f"req-{asyncio.get_running_loop().time()}"
78
+ result_generator = self.engine.generate(
79
+ prompt,
80
+ sp, # SamplingParams(...)
81
+ request_id,
82
+ lora_request=self.current_lora_request,
83
+ )
84
+
85
+ async for out in result_generator: # with FINAL_ONLY this runs once
86
+ res = out
87
+
88
+ raw_text = res.outputs[0].text
89
+ out_token_ids = res.outputs[0].token_ids
90
+ log_probs = [
91
+ logprob_dict[token_id].logprob
92
+ for token_id, logprob_dict in zip(out_token_ids, res.outputs[0].logprobs)
93
+ ]
94
+ log_probs = torch.tensor(log_probs)
95
+ out_token_ids = torch.tensor(out_token_ids, dtype=torch.long)
96
+ content = raw_text
97
+ reasoning_content = None
98
+
99
+ if extract_thinking:
100
+ m = re.match(
101
+ r"^\n<think>\n([\s\S]*?)</think>\n\n(.*)$", raw_text, flags=re.DOTALL
102
+ )
103
+ if m:
104
+ reasoning_content = m.group(1)
105
+ content = m.group(2)
106
+ return LLMInferenceOutput(
107
+ content=content,
108
+ reasoning_content=reasoning_content,
109
+ log_probs=log_probs,
110
+ out_token_ids=out_token_ids,
111
+ )
src_code_for_reproducibility/models/large_language_model_api.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/large_language_model_api.py
3
+ Summary: Implements API-based large-language-model inference adapters.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import copy
10
+ import os
11
+ import random
12
+ import re
13
+ from typing import Any, Callable, Dict, List, Optional, Sequence
14
+
15
+ import backoff
16
+ from openai import AsyncOpenAI, OpenAIError
17
+
18
+ from mllm.markov_games.rollout_tree import ChatTurn
19
+ from mllm.models.inference_backend import LLMInferenceOutput
20
+
21
+ # Static list copied from the public OpenAI docs until a discovery endpoint is exposed.
22
+ reasoning_models = [
23
+ "gpt-5-nano",
24
+ "gpt-5-mini",
25
+ "gpt-5",
26
+ "o1-mini",
27
+ "o1",
28
+ "o1-pro",
29
+ "o3-mini",
30
+ "o3",
31
+ "o3-pro",
32
+ "o4-mini",
33
+ "o4",
34
+ "o4-pro",
35
+ "openai/gpt-oss-20b",
36
+ "openai/gpt-oss-120b",
37
+ ]
38
+
39
+
40
+ class LargeLanguageModelOpenAI:
41
+ """Tiny async wrapper for OpenAI Chat Completions."""
42
+
43
+ def __init__(
44
+ self,
45
+ llm_id: str = "",
46
+ model: str = "gpt-4.1-mini",
47
+ reasoning_effort: str = "low",
48
+ add_constraint_msg: bool = True,
49
+ api_key: Optional[str] = None,
50
+ base_url: Optional[str] = None,
51
+ timeout_s: float = 300.0,
52
+ regex_max_attempts: int = 10,
53
+ sampling_params: Optional[Dict[str, Any]] = None,
54
+ init_kwargs: Optional[Dict[str, Any]] = None,
55
+ output_directory: Optional[str] = None,
56
+ ) -> None:
57
+ self.llm_id = llm_id
58
+ self.model = model
59
+ key = api_key or os.getenv("OPENAI_API_KEY")
60
+ if not key:
61
+ raise RuntimeError(
62
+ "Set OPENAI_API_KEY as global environment variable or pass api_key."
63
+ )
64
+ client_kwargs: Dict[str, Any] = {"api_key": key, "timeout": timeout_s}
65
+ if base_url:
66
+ client_kwargs["base_url"] = base_url
67
+ self.client = AsyncOpenAI(**client_kwargs)
68
+
69
+ # Sampling/default request params set at init
70
+ self.sampling_params = sampling_params
71
+ self.use_reasoning = model in reasoning_models
72
+ if self.use_reasoning:
73
+ self.sampling_params["reasoning"] = {
74
+ "effort": reasoning_effort,
75
+ "summary": "detailed",
76
+ }
77
+ self.regex_max_attempts = max(1, int(regex_max_attempts))
78
+ self.add_constraint_msg = add_constraint_msg
79
+
80
+ def get_inference_policies(self) -> Dict[str, Callable]:
81
+ return {
82
+ self.llm_id: self.get_action,
83
+ }
84
+
85
+ async def prepare_adapter_for_inference(self, *args: Any, **kwargs: Any) -> None:
86
+ await asyncio.sleep(0)
87
+ pass
88
+
89
+ async def toggle_eval_mode(self, *args: Any, **kwargs: Any) -> None:
90
+ await asyncio.sleep(0)
91
+ pass
92
+
93
+ async def toggle_training_mode(self, *args: Any, **kwargs: Any) -> None:
94
+ await asyncio.sleep(0)
95
+ pass
96
+
97
+ async def export_adapters(self, *args: Any, **kwargs: Any) -> None:
98
+ await asyncio.sleep(0)
99
+ pass
100
+
101
+ async def checkpoint_all_adapters(self, *args: Any, **kwargs: Any) -> None:
102
+ await asyncio.sleep(0)
103
+ pass
104
+
105
+ def extract_output_from_response(self, resp: Response) -> LLMInferenceOutput:
106
+ if len(resp.output) > 1:
107
+ reasoning_content = resp.output[0].content
108
+ summary = resp.output[0].summary
109
+ if reasoning_content is not None:
110
+ reasoning_content = (
111
+ f"OpenAI Reasoning Content: {reasoning_content[0].text}"
112
+ )
113
+ elif summary != []:
114
+ reasoning_content = f"OpenAI Reasoning Summary: {summary[0].text}"
115
+ else:
116
+ reasoning_content = None
117
+ content = resp.output[1].content[0].text
118
+ else:
119
+ reasoning_content = None
120
+ content = resp.output[0].content[0].text
121
+
122
+ return LLMInferenceOutput(
123
+ content=content,
124
+ reasoning_content=reasoning_content,
125
+ )
126
+
127
+ @backoff.on_exception(
128
+ backoff.expo, Exception, max_time=10**10, max_tries=10**10
129
+ )
130
+ async def get_action(
131
+ self,
132
+ state: list[ChatTurn],
133
+ agent_id: str,
134
+ regex: Optional[str] = None,
135
+ ) -> LLMInferenceOutput:
136
+ # Remove any non-role/content keys from the prompt else openai will error.
137
+ prompt = [{"role": p.role, "content": p.content} for p in state]
138
+
139
+ # if self.sleep_between_requests:
140
+ # await self.wait_random_time()
141
+
142
+ # If regex is required, prime the model and validate client-side
143
+ if regex:
144
+ if self.add_constraint_msg:
145
+ constraint_msg = {
146
+ "role": "user",
147
+ "content": (
148
+ f"Output must match this regex exactly: {regex} \n"
149
+ "Return only the matching string, with no quotes or extra text."
150
+ ),
151
+ }
152
+ prompt = [constraint_msg, *prompt]
153
+ pattern = re.compile(regex)
154
+ for _ in range(self.regex_max_attempts):
155
+ resp = await self.client.responses.create(
156
+ model=self.model,
157
+ input=prompt,
158
+ **self.sampling_params,
159
+ )
160
+ policy_output = self.extract_output_from_response(resp)
161
+ if pattern.fullmatch(policy_output.content):
162
+ return policy_output
163
+ prompt = [
164
+ *prompt,
165
+ {
166
+ "role": "user",
167
+ "content": (
168
+ f"Invalid response format. Expected format (regex): {regex}\n Please try again and provide ONLY a response that matches this regex."
169
+ ),
170
+ },
171
+ ]
172
+ return policy_output
173
+
174
+ # Simple, unconstrained generation
175
+ resp = await self.client.responses.create(
176
+ model=self.model,
177
+ input=prompt,
178
+ **self.sampling_params,
179
+ )
180
+ policy_output = self.extract_output_from_response(resp)
181
+ return policy_output
182
+
183
+ def shutdown(self) -> None:
184
+ self.client = None
src_code_for_reproducibility/models/large_language_model_gemini_api.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/large_language_model_gemini_api.py
3
+ Summary: Implements native Gemini API-based large-language-model inference adapters.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import os
10
+ import re
11
+ from typing import Any, Callable, Dict, List, Optional
12
+
13
+ import backoff
14
+ from google import genai
15
+ from google.genai import types
16
+
17
+ from mllm.markov_games.rollout_tree import ChatTurn
18
+ from mllm.models.inference_backend import LLMInferenceOutput
19
+
20
+
21
+ class LargeLanguageModelGemini:
22
+ """Tiny async wrapper for the native Gemini API."""
23
+
24
+ def __init__(
25
+ self,
26
+ llm_id: str = "",
27
+ model: str = "gemini-3.1-flash-lite-preview",
28
+ api_key: Optional[str] = None,
29
+ timeout_s: float = 300.0,
30
+ regex_max_attempts: int = 10,
31
+ sampling_params: Optional[Dict[str, Any]] = None,
32
+ thinking_level: str = "low",
33
+ include_thoughts: bool = True,
34
+ init_kwargs: Optional[Dict[str, Any]] = None,
35
+ output_directory: Optional[str] = None,
36
+ ) -> None:
37
+ self.llm_id = llm_id
38
+ self.model = model
39
+ self.timeout_s = timeout_s
40
+ key = api_key or os.getenv("GEMINI_API_KEY")
41
+ if not key:
42
+ raise RuntimeError(
43
+ "Set GEMINI_API_KEY as global environment variable or pass api_key."
44
+ )
45
+ self.client = genai.Client(api_key=key)
46
+ self.sampling_params = sampling_params or {}
47
+ self.thinking_level = thinking_level
48
+ self.include_thoughts = include_thoughts
49
+ self.regex_max_attempts = max(1, int(regex_max_attempts))
50
+
51
+ def get_inference_policies(self) -> Dict[str, Callable]:
52
+ return {
53
+ self.llm_id: self.get_action,
54
+ }
55
+
56
+ async def prepare_adapter_for_inference(self, *args: Any, **kwargs: Any) -> None:
57
+ await asyncio.sleep(0)
58
+ pass
59
+
60
+ async def toggle_eval_mode(self, *args: Any, **kwargs: Any) -> None:
61
+ await asyncio.sleep(0)
62
+ pass
63
+
64
+ async def toggle_training_mode(self, *args: Any, **kwargs: Any) -> None:
65
+ await asyncio.sleep(0)
66
+ pass
67
+
68
+ async def export_adapters(self, *args: Any, **kwargs: Any) -> None:
69
+ await asyncio.sleep(0)
70
+ pass
71
+
72
+ async def checkpoint_all_adapters(self, *args: Any, **kwargs: Any) -> None:
73
+ await asyncio.sleep(0)
74
+ pass
75
+
76
+ def messages_to_contents(self, messages: List[Dict[str, str]]) -> List[types.Content]:
77
+ contents: List[types.Content] = []
78
+ system_chunks: List[str] = []
79
+
80
+ for message in messages:
81
+ role = message["role"]
82
+ text = message["content"]
83
+
84
+ if role == "system":
85
+ system_chunks.append(text)
86
+ continue
87
+
88
+ gemini_role = "model" if role == "assistant" else "user"
89
+ contents.append(
90
+ types.Content(
91
+ role=gemini_role,
92
+ parts=[types.Part.from_text(text=text)],
93
+ )
94
+ )
95
+
96
+ if system_chunks:
97
+ system_text = "\n\n".join(system_chunks)
98
+ contents.insert(
99
+ 0,
100
+ types.Content(
101
+ role="user",
102
+ parts=[
103
+ types.Part.from_text(
104
+ text=(
105
+ "System instruction:\n"
106
+ f"{system_text}\n\n"
107
+ "Follow the system instruction for the rest of this conversation."
108
+ )
109
+ )
110
+ ],
111
+ ),
112
+ )
113
+
114
+ return contents
115
+
116
+ def build_generate_config(self) -> types.GenerateContentConfig:
117
+ return types.GenerateContentConfig(
118
+ thinking_config=types.ThinkingConfig(
119
+ thinking_level=self.thinking_level,
120
+ include_thoughts=self.include_thoughts,
121
+ ),
122
+ **self.sampling_params,
123
+ )
124
+
125
+ def extract_output_from_response(self, response: Any) -> LLMInferenceOutput:
126
+ reasoning_parts: List[str] = []
127
+ content_parts: List[str] = []
128
+
129
+ if response.candidates:
130
+ for part in response.candidates[0].content.parts:
131
+ text = getattr(part, "text", None)
132
+ if not text:
133
+ continue
134
+ if getattr(part, "thought", False):
135
+ reasoning_parts.append(text)
136
+ else:
137
+ content_parts.append(text)
138
+
139
+ content = "\n".join(content_parts) if content_parts else (response.text or "")
140
+ reasoning_content = "\n".join(reasoning_parts) if reasoning_parts else None
141
+
142
+ return LLMInferenceOutput(
143
+ content=content,
144
+ reasoning_content=reasoning_content,
145
+ )
146
+
147
+ @backoff.on_exception(
148
+ backoff.expo, Exception, max_time=10**10, max_tries=10**10
149
+ )
150
+ async def get_action(
151
+ self,
152
+ state: list[ChatTurn],
153
+ agent_id: str,
154
+ regex: Optional[str] = None,
155
+ ) -> LLMInferenceOutput:
156
+ prompt = [{"role": p.role, "content": p.content} for p in state]
157
+
158
+ if regex:
159
+ constraint_msg = {
160
+ "role": "user",
161
+ "content": (
162
+ f"Output must match this regex exactly: {regex} \n"
163
+ "Return only the matching string, with no quotes or extra text."
164
+ ),
165
+ }
166
+ prompt = [constraint_msg, *prompt]
167
+ pattern = re.compile(regex)
168
+ for _ in range(self.regex_max_attempts):
169
+ response = await self.client.aio.models.generate_content(
170
+ model=self.model,
171
+ contents=self.messages_to_contents(prompt),
172
+ config=self.build_generate_config(),
173
+ )
174
+ policy_output = self.extract_output_from_response(response)
175
+ if pattern.fullmatch(policy_output.content):
176
+ return policy_output
177
+ prompt = [
178
+ *prompt,
179
+ {
180
+ "role": "user",
181
+ "content": (
182
+ f"Invalid response format. Expected format (regex): {regex}\n"
183
+ "Please try again and provide ONLY a response that matches this regex."
184
+ ),
185
+ },
186
+ ]
187
+ return policy_output
188
+
189
+ response = await self.client.aio.models.generate_content(
190
+ model=self.model,
191
+ contents=self.messages_to_contents(prompt),
192
+ config=self.build_generate_config(),
193
+ )
194
+ return self.extract_output_from_response(response)
195
+
196
+ def shutdown(self) -> None:
197
+ self.client = None
src_code_for_reproducibility/models/large_language_model_local.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/large_language_model_local.py
3
+ Summary: Provides a local large language model wrapper over inference backends.
4
+ """
5
+
6
+ import logging
7
+ import os
8
+ import re
9
+ import sys
10
+ import uuid
11
+ from collections.abc import Callable
12
+ from copy import deepcopy
13
+ from datetime import datetime
14
+ from typing import Literal
15
+
16
+ import httpx
17
+ import requests
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.optim import SGD, Adam, AdamW, RMSprop
21
+ from transformers import AutoModelForCausalLM, AutoTokenizer
22
+
23
+ from mllm.chat_utils.apply_template import chat_turns_to_token_ids
24
+ from mllm.markov_games.rollout_tree import ChatTurn
25
+ from mllm.models.adapter_training_wrapper import AdapterWrapper
26
+ from mllm.models.inference_backend import LLMInferenceOutput
27
+ from mllm.models.inference_backend_dummy import DummyInferenceBackend
28
+ from mllm.models.inference_backend_vllm import VLLMAsyncBackend
29
+
30
+ logger = logging.getLogger(__name__)
31
+ logger.addHandler(logging.StreamHandler(sys.stdout))
32
+
33
+ AdapterID = str
34
+ PolicyID = str
35
+
36
+
37
+ class LeanLocalLLM:
38
+ """
39
+ Wrapper that manages local HuggingFace models, adapters, and inference backends.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ llm_id: str = "base_llm",
45
+ model_name: str = "Qwen/Qwen3-4B-Instruct-2507",
46
+ device: str = "cuda",
47
+ hf_kwargs: dict = {},
48
+ adapter_configs: dict = {},
49
+ output_directory: str = "./models/",
50
+ inference_backend: Literal["vllm", "dummy"] = "vllm",
51
+ inference_backend_sampling_params: dict = {},
52
+ inference_backend_init_kwargs: dict = {},
53
+ initial_adapter_paths: dict[str, str] | None = None,
54
+ initial_buffer_paths: list[str] | None = None,
55
+ enable_thinking: bool = None,
56
+ regex_max_attempts: int = -1,
57
+ max_thinking_characters: int = 0,
58
+ ):
59
+ self.inference_backend_name = inference_backend
60
+ self.output_directory = output_directory
61
+ self.llm_id = llm_id
62
+ self.device = torch.device(device) if device else torch.device("cuda")
63
+ self.model_name = model_name
64
+ self.adapter_configs = adapter_configs
65
+ self.adapter_ids = list(adapter_configs.keys())
66
+ self.enable_thinking = enable_thinking
67
+ self.regex_max_attempts = regex_max_attempts
68
+ self.initial_buffer_paths = initial_buffer_paths
69
+ self.max_thinking_characters = max_thinking_characters
70
+ self.regex_retries_count = 0
71
+
72
+ # Optional user-specified initial adapter weight locations (local or HF Hub)
73
+ # Format: {adapter_id: path_or_repo_id}
74
+ self.initial_adapter_paths: dict[str, str] | None = initial_adapter_paths
75
+
76
+ # Path management / imports
77
+ self.save_path = str(os.path.join(output_directory, model_name, "adapters"))
78
+ self.adapter_paths = {
79
+ adapter_id: os.path.join(self.save_path, adapter_id)
80
+ for adapter_id in self.adapter_ids
81
+ }
82
+ checkpoints_dir = os.path.join(self.output_directory, "checkpoints")
83
+ self.past_agent_adapter_paths = {}
84
+ if os.path.isdir(checkpoints_dir):
85
+ for dirname in os.listdir(checkpoints_dir):
86
+ dirpath = os.path.join(checkpoints_dir, dirname)
87
+ if os.path.isdir(dirpath):
88
+ self.past_agent_adapter_paths[f"{dirname}_buffer"] = os.path.join(
89
+ dirpath, "agent_adapter"
90
+ )
91
+ logger.info(
92
+ f"Loaded {len(self.past_agent_adapter_paths)} past agent adapters from checkpoints directory."
93
+ )
94
+ if self.initial_buffer_paths is not None:
95
+ previous_count = len(self.past_agent_adapter_paths)
96
+ for path in self.initial_buffer_paths:
97
+ if os.path.isdir(path):
98
+ for dirname in os.listdir(path):
99
+ dirpath = os.path.join(path, dirname)
100
+ if os.path.isdir(dirpath):
101
+ self.past_agent_adapter_paths[
102
+ f"{dirname}_buffer"
103
+ ] = os.path.join(dirpath, "agent_adapter")
104
+ else:
105
+ logger.warning(
106
+ f"Initial buffer path {path} does not exist or is not a directory."
107
+ )
108
+ logger.info(
109
+ f"Loaded {len(self.past_agent_adapter_paths) - previous_count} past agent adapters from user-specified initial buffer paths."
110
+ )
111
+ self.past_agent_adapter_ids = list(self.past_agent_adapter_paths.keys())
112
+
113
+ # ID management for tracking adapter versions
114
+ self.adapter_train_ids = {
115
+ adapter_id: self.short_id_generator() for adapter_id in self.adapter_ids
116
+ }
117
+ # Initialize tokenizer
118
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
119
+ # Setup padding token to be same as EOS token
120
+ self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
121
+ self.tokenizer.pad_token = self.tokenizer.eos_token
122
+
123
+ self.weights_got_updated: dict[AdapterID, bool] = {
124
+ adapter_id: False for adapter_id in self.adapter_ids
125
+ }
126
+ self.weights_got_updated.update(
127
+ {adapter_id: False for adapter_id in self.past_agent_adapter_ids}
128
+ )
129
+ self.current_lora_request = None
130
+ self.currently_loaded_adapter_id = None
131
+
132
+ # ---------------------------------------------------------
133
+ # Init HF model, peft adapters
134
+ # ---------------------------------------------------------
135
+ self.shared_hf_llm = AutoModelForCausalLM.from_pretrained(
136
+ pretrained_model_name_or_path=model_name,
137
+ **hf_kwargs,
138
+ )
139
+ self.hf_adapters = {}
140
+ self.optimizers = {}
141
+ for adapter_id in self.adapter_ids:
142
+ # Prefer output-folder path if it exists; else fall back to user-specified initial path if provided
143
+ output_path = os.path.join(self.save_path, adapter_id)
144
+ chosen_path: str | None = None
145
+ if os.path.isdir(output_path) and os.listdir(output_path):
146
+ chosen_path = output_path
147
+ logger.info(
148
+ f"Initializing adapter '{adapter_id}': using existing weights from output folder '{chosen_path}'."
149
+ )
150
+ elif (
151
+ self.initial_adapter_paths and adapter_id in self.initial_adapter_paths
152
+ ):
153
+ chosen_path = self.initial_adapter_paths[adapter_id]
154
+ logger.info(
155
+ f"Initializing adapter '{adapter_id}': using provided initial path '{chosen_path}'."
156
+ )
157
+ else:
158
+ logger.info(
159
+ f"Initializing adapter '{adapter_id}': no initial weights provided or found; starting from scratch."
160
+ )
161
+ hf_adapter = AdapterWrapper(
162
+ shared_llm=self.shared_hf_llm,
163
+ adapter_id=adapter_id,
164
+ lora_config=adapter_configs[adapter_id],
165
+ path=chosen_path,
166
+ ).to(device)
167
+ self.hf_adapters[adapter_id] = hf_adapter
168
+ # Persist current state of all adapters (ensures remote loads are cached to disk)
169
+ self.export_adapters()
170
+
171
+ # ---------------------------------------------------------
172
+ # Init inference inference_backend
173
+ # ---------------------------------------------------------
174
+
175
+ if inference_backend == "vllm":
176
+ self.inference_backend = VLLMAsyncBackend(
177
+ model_name=self.model_name,
178
+ # adapter_paths=self.adapter_paths,
179
+ tokenizer=self.tokenizer,
180
+ engine_init_kwargs=inference_backend_init_kwargs,
181
+ sampling_params=inference_backend_sampling_params,
182
+ )
183
+ elif inference_backend == "dummy":
184
+ self.inference_backend = DummyInferenceBackend()
185
+ else:
186
+ raise ValueError(f"Unknown inference_backend: {inference_backend}")
187
+
188
+ def reset_regex_retries_count(self) -> None:
189
+ self.regex_retries_count = 0
190
+
191
+ def get_inference_policies(self) -> dict[PolicyID, Callable]:
192
+ """
193
+ Build async policy callables keyed by adapter id for inference-only usage.
194
+ """
195
+ policies = {}
196
+ for adapter_id in self.adapter_ids:
197
+ # define policy func
198
+ async def policy(
199
+ state: list[ChatTurn],
200
+ agent_id: str,
201
+ regex: str | None = None,
202
+ _adapter_id=adapter_id,
203
+ ):
204
+ self.prepare_adapter_for_inference(adapter_id=_adapter_id)
205
+ response = await self.get_action(state, agent_id, regex)
206
+ return response
207
+
208
+ policies[self.llm_id + "/" + adapter_id] = policy
209
+
210
+ for adapter_id in self.past_agent_adapter_ids:
211
+ # define policy func
212
+ async def policy(
213
+ state: list[ChatTurn],
214
+ agent_id: str,
215
+ regex: str | None = None,
216
+ _adapter_id=adapter_id,
217
+ ):
218
+ self.prepare_adapter_for_inference(adapter_id=_adapter_id)
219
+ response = await self.get_action(state, agent_id, regex)
220
+ return response
221
+
222
+ policies[self.llm_id + "/" + adapter_id] = policy
223
+ return policies
224
+
225
+ def get_adapter_modules(self) -> dict[PolicyID, nn.Module]:
226
+ """
227
+ Returns wrappers over the adapters which allows them be
228
+ interfaced like regular PyTorch models.
229
+ AdapterWrapper lives in adapter_wrapper.py; the huggingface modules already wrap
230
+ parameters here, so we surface them directly until an extra shim is required.
231
+ """
232
+ trainable_objects = {an: self.hf_adapters[an] for an in self.adapter_ids}
233
+ return trainable_objects
234
+
235
+ async def toggle_training_mode(self) -> None:
236
+ for adn in self.adapter_ids:
237
+ self.adapter_train_ids[adn] = self.short_id_generator()
238
+ await self.inference_backend.toggle_training_mode()
239
+
240
+ async def toggle_eval_mode(self) -> None:
241
+ await self.inference_backend.toggle_eval_mode()
242
+
243
+ def prepare_adapter_for_inference(self, adapter_id: AdapterID) -> None:
244
+ self.inference_backend.prepare_adapter(
245
+ adapter_id,
246
+ adapter_path=self.adapter_paths.get(
247
+ adapter_id, self.past_agent_adapter_paths.get(adapter_id, None)
248
+ ),
249
+ weights_got_updated=self.weights_got_updated[adapter_id],
250
+ )
251
+ self.currently_loaded_adapter_id = adapter_id
252
+ self.weights_got_updated[adapter_id] = False
253
+
254
+ # def _make_prompt_text(self, prompt: list[dict]) -> str:
255
+ # if self.enable_thinking is not None:
256
+ # prompt_text = self.tokenizer.apply_chat_template(
257
+ # prompt,
258
+ # tokenize=False,
259
+ # add_generation_prompt=True,
260
+ # enable_thinking=self.enable_thinking,
261
+ # )
262
+ # else:
263
+ # prompt_text = self.tokenizer.apply_chat_template(
264
+ # prompt,
265
+ # tokenize=False,
266
+ # add_generation_prompt=True,
267
+ # )
268
+
269
+ # return prompt_text
270
+
271
+ async def get_action(
272
+ self, state: list[ChatTurn], agent_id: str, regex: str | None = None
273
+ ) -> ChatTurn:
274
+ current_regex = regex if self.regex_max_attempts == -1 else None
275
+ pattern = re.compile(regex) if regex else None
276
+ nb_attempts = 0
277
+ state = state[:]
278
+ while True:
279
+ context_token_ids = chat_turns_to_token_ids(
280
+ chats=state,
281
+ tokenizer=self.tokenizer,
282
+ enable_thinking=self.enable_thinking,
283
+ )
284
+ policy_output = await self.inference_backend.generate(
285
+ input_token_ids=context_token_ids.tolist(),
286
+ extract_thinking=(self.max_thinking_characters > 0),
287
+ regex=current_regex,
288
+ )
289
+ if (
290
+ pattern is None
291
+ or (nb_attempts >= self.regex_max_attempts)
292
+ or (pattern.fullmatch(policy_output.content))
293
+ ):
294
+ return ChatTurn(
295
+ agent_id=agent_id,
296
+ role="assistant",
297
+ content=policy_output.content,
298
+ reasoning_content=policy_output.reasoning_content,
299
+ out_token_ids=policy_output.out_token_ids,
300
+ log_probs=policy_output.log_probs,
301
+ is_state_end=False,
302
+ )
303
+ else:
304
+ self.regex_retries_count += 1
305
+ nb_attempts += 1
306
+ logger.warning(
307
+ f"Response {policy_output.content} did not match regex: {regex}, retry {nb_attempts}/{self.regex_max_attempts}"
308
+ )
309
+ if nb_attempts == self.regex_max_attempts:
310
+ current_regex = regex
311
+ # regex_prompt = ChatTurn(
312
+ # role="user",
313
+ # content=f"Invalid response format. Expected format (regex): {current_regex}\n Please try again and provide ONLY a response that matches this regex.",
314
+ # reasoning_content=None,
315
+ # log_probs=None,
316
+ # out_token_ids=None,
317
+ # is_state_end=False,
318
+ # )
319
+ # state.append(regex_prompt)
320
+
321
+ def export_adapters(self) -> None:
322
+ """
323
+ Any peft wrapper, by default, saves all adapters, not just the one currently loaded.
324
+ """
325
+
326
+ # New version of the adapters available
327
+ for adapter_id in self.adapter_ids:
328
+ self.weights_got_updated[adapter_id] = True
329
+ for adapter_id in self.past_agent_adapter_ids:
330
+ self.weights_got_updated[adapter_id] = True
331
+
332
+ adapter_id = self.adapter_ids[0]
333
+ self.hf_adapters[adapter_id].save_pretrained(self.save_path)
334
+
335
+ def checkpoint_all_adapters(self, checkpoint_indicator: str) -> None:
336
+ """
337
+ Checkpoints all adapters to the configured output directory.
338
+ """
339
+ adapter_id = self.adapter_ids[0]
340
+ output_dir = os.path.join(self.output_directory, "checkpoints")
341
+ os.makedirs(output_dir, exist_ok=True)
342
+ date_str = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
343
+ agent_adapter_dir = f"{adapter_id}-{checkpoint_indicator}-{date_str}"
344
+ export_path = os.path.join(output_dir, agent_adapter_dir)
345
+ for adapter_id in self.adapter_ids:
346
+ if "agent" in adapter_id:
347
+ self.past_agent_adapter_paths[
348
+ f"{agent_adapter_dir}_buffer"
349
+ ] = os.path.join(export_path, adapter_id)
350
+ self.past_agent_adapter_ids.append(f"{agent_adapter_dir}_buffer")
351
+ self.weights_got_updated[f"{agent_adapter_dir}_buffer"] = False
352
+ self.hf_adapters[adapter_id].save_pretrained(export_path)
353
+
354
+ def short_id_generator(self) -> str:
355
+ """
356
+ Generates a short unique ID for tracking adapter versions.
357
+
358
+ Returns:
359
+ int: An 8-digit integer ID.
360
+ """
361
+ return str(uuid.uuid4().int)[:8]
src_code_for_reproducibility/models/scalar_critic.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/models/scalar_critic.py
3
+ Summary: Defines a scalar critic network and helper utilities.
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.optim as optim
9
+ from peft import LoraConfig, get_peft_model
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer
11
+
12
+ from mllm.models.adapter_training_wrapper import AdapterWrapper
13
+
14
+
15
+ class ScalarCritic(nn.Module):
16
+ """
17
+ A causal-LM critic_adapter + a scalar value head:
18
+ V_φ(s) = wᵀ h_last + b
19
+ Only LoRA adapters (inside critic_adapter) and the value head are trainable.
20
+ """
21
+
22
+ def __init__(self, critic_adapter: AdapterWrapper):
23
+ super().__init__()
24
+ self.critic_adapter = critic_adapter
25
+ hidden_size = self.critic_adapter.shared_llm.config.hidden_size
26
+ self.value_head = nn.Linear(hidden_size, 1).to(
27
+ dtype=critic_adapter.dtype, device=critic_adapter.device
28
+ )
29
+
30
+ def forward(self, input_ids, attention_mask=None, **kwargs):
31
+ # AdapterWrapper activates its own adapter internally
32
+ outputs = self.critic_adapter(
33
+ input_ids=input_ids,
34
+ attention_mask=attention_mask,
35
+ output_hidden_states=True,
36
+ **kwargs,
37
+ )
38
+ h_last = outputs.hidden_states[-1] # (B, S, H)
39
+ values = self.value_head(h_last).squeeze(-1) # (B, S)
40
+ return values
41
+
42
+ def parameters(self, recurse: bool = True):
43
+ """Iterator over *trainable* parameters for this critic."""
44
+ # 1) LoRA params for *this* adapter
45
+ for p in self.critic_adapter.parameters():
46
+ yield p
47
+ # 2) scalar head
48
+ yield from self.value_head.parameters()
49
+
50
+ def gradient_checkpointing_enable(self, *args, **kwargs):
51
+ self.critic_adapter.gradient_checkpointing_enable(*args, **kwargs)
52
+
53
+ @property
54
+ def dtype(self):
55
+ return self.critic_adapter.dtype
56
+
57
+ @property
58
+ def device(self):
59
+ return self.critic_adapter.device
src_code_for_reproducibility/training/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ File: mllm/training/__init__.py
3
+ Summary: Exposes training submodules through the package namespace.
4
+ """
src_code_for_reproducibility/training/__pycache__/annealing_methods.cpython-312.pyc ADDED
Binary file (956 Bytes). View file
 
src_code_for_reproducibility/training/__pycache__/credit_methods.cpython-312.pyc ADDED
Binary file (12.7 kB). View file
 
src_code_for_reproducibility/training/__pycache__/tally_metrics.cpython-312.pyc ADDED
Binary file (3.47 kB). View file
 
src_code_for_reproducibility/training/__pycache__/tally_rollout.cpython-312.pyc ADDED
Binary file (6 kB). View file
 
src_code_for_reproducibility/training/__pycache__/tally_tokenwise.cpython-312.pyc ADDED
Binary file (13.5 kB). View file
 
src_code_for_reproducibility/training/__pycache__/trainer_ad_align.cpython-312.pyc ADDED
Binary file (19.7 kB). View file
 
src_code_for_reproducibility/training/__pycache__/trainer_common.cpython-312.pyc ADDED
Binary file (40.6 kB). View file
 
src_code_for_reproducibility/training/__pycache__/trainer_independent.cpython-312.pyc ADDED
Binary file (6.93 kB). View file
 
src_code_for_reproducibility/training/__pycache__/training_data_utils.cpython-312.pyc ADDED
Binary file (20.8 kB). View file
 
src_code_for_reproducibility/training/annealing_methods.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/annealing_methods.py
3
+ Summary: Implements annealing schedules used across training loops.
4
+ """
5
+
6
+ import numpy as np
7
+
8
+
9
+ def sigmoid_annealing(step: int, temperature: float) -> float:
10
+ """
11
+ Smoothly ramp a scalar from 0 → 1 using a temperature-controlled sigmoid.
12
+
13
+ Args:
14
+ step: Current training step or iteration.
15
+ temperature: Controls how sharp the transition is; larger values flatten the curve.
16
+
17
+ Returns:
18
+ Float in [-1, 1] that can be rescaled for annealing schedules.
19
+ """
20
+ return 2 / (1 + np.exp(-step / temperature)) - 1
src_code_for_reproducibility/training/credit_methods.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/credit_methods.py
3
+ Summary: Holds credit-assignment routines for reinforcement learning updates.
4
+ """
5
+
6
+ import torch
7
+
8
+
9
+ def whiten_advantages(advantages: torch.Tensor) -> torch.Tensor:
10
+ """
11
+ Normalize a vector of advantages to zero mean / unit variance (global).
12
+
13
+ Useful for variance reduction before computing gradients.
14
+ """
15
+ whitened_advantages = (advantages - torch.mean(advantages)) / (
16
+ torch.std(advantages) + 1e-9
17
+ )
18
+ return whitened_advantages
19
+
20
+
21
+ def whiten_advantages_time_step_wise(
22
+ advantages: torch.Tensor, # (B, T)
23
+ ) -> torch.Tensor:
24
+ """
25
+ Whiten advantages independently per timestep (column-wise mean/std).
26
+
27
+ Helps when rollout lengths differ or certain positions have very different scales.
28
+ """
29
+ assert advantages.dim() == 2, "Wrong dimensions."
30
+ whitened_advantages_time_step_wise = (
31
+ advantages - advantages.mean(dim=0, keepdim=True)
32
+ ) / (advantages.std(dim=0, keepdim=True) + 1e-9)
33
+ return whitened_advantages_time_step_wise
34
+
35
+
36
+ def get_discounted_state_visitation_credits(
37
+ credits: torch.Tensor, discount_factor: float # (B, T)
38
+ ) -> torch.Tensor:
39
+ """
40
+ Apply geometric discounting to credits so earlier visits count less.
41
+
42
+ Equivalent to per-timestep multiplication by ``gamma^t``.
43
+ """
44
+ return credits * (
45
+ discount_factor ** torch.arange(credits.shape[1], device=credits.device)
46
+ )
47
+
48
+
49
+ def get_discounted_returns(
50
+ rewards: torch.Tensor, # (B, T)
51
+ discount_factor: float,
52
+ ) -> torch.Tensor:
53
+ """
54
+ Computes Monte Carlo discounted returns for a sequence of rewards.
55
+
56
+ Args:
57
+ rewards (torch.Tensor): Array of rewards for each timestep.
58
+
59
+ Returns:
60
+ torch.Tensor: Array of discounted returns.
61
+ """
62
+ assert rewards.dim() == 2, "Wrong dimensions."
63
+ B, T = rewards.shape
64
+ discounted_returns = torch.zeros_like(rewards)
65
+ accumulator = torch.zeros(B, device=rewards.device, dtype=rewards.dtype)
66
+ for t in reversed(range(T)):
67
+ accumulator = rewards[:, t] + discount_factor * accumulator
68
+ discounted_returns[:, t] = accumulator
69
+ return discounted_returns
70
+
71
+
72
+ def get_rloo_credits(credits: torch.Tensor): # (B, S)
73
+ """Compute leave-one-out baselines for a batch of credits."""
74
+ assert credits.dim() == 2, "Wrong dimensions."
75
+ rloo_baselines = torch.zeros_like(credits)
76
+ n = credits.shape[0]
77
+ if n == 1:
78
+ return credits, rloo_baselines
79
+ rloo_baselines = (torch.sum(credits, dim=0, keepdim=True) - credits) / (n - 1)
80
+ rloo_credits = credits - rloo_baselines
81
+ return rloo_credits, rloo_baselines
82
+
83
+
84
+ def get_generalized_advantage_estimates(
85
+ rewards: torch.Tensor, # (B, T)
86
+ value_estimates: torch.Tensor, # (B, T+1)
87
+ discount_factor: float,
88
+ lambda_coef: float,
89
+ ) -> torch.Tensor:
90
+ """
91
+ Compute Generalized Advantage Estimates (GAE).
92
+
93
+ See https://arxiv.org/pdf/1506.02438 for derivation.
94
+ """
95
+ assert rewards.dim() == value_estimates.dim() == 2, "Wrong dimensions."
96
+
97
+ assert (
98
+ rewards.shape[0] == value_estimates.shape[0]
99
+ ), f"Got shapes {rewards.shape} and {value_estimates.shape} of rewards and value estimates."
100
+ assert (
101
+ rewards.shape[1] == value_estimates.shape[1] - 1
102
+ ), f"Got shapes {rewards.shape} and {value_estimates.shape} of rewards and value estimates."
103
+
104
+ T = rewards.shape[1]
105
+ tds = rewards + discount_factor * value_estimates[:, 1:] - value_estimates[:, :-1]
106
+ gaes = torch.zeros_like(tds)
107
+ acc = 0.0
108
+ for t in reversed(range(T)):
109
+ acc = tds[:, t] + lambda_coef * discount_factor * acc
110
+ gaes[:, t] = acc
111
+ return gaes
112
+
113
+
114
+ def get_advantage_alignment_weights(
115
+ advantages: torch.Tensor, # (B, T)
116
+ exclude_k_equals_t: bool,
117
+ gamma: float,
118
+ discount_t: bool,
119
+ ) -> torch.Tensor:
120
+ """
121
+ The advantage alignment credit is calculated as
122
+
123
+ \[
124
+ A^*(s_t, a_t, b_t) = A^1(s_t, a_t, b_t) + \beta \cdot
125
+ \left( \sum_{k < t} \gamma^{t-k} A^1(s_k, a_k, b_k) \right)
126
+ A^2(s_t, a_t, b_t)
127
+ \]
128
+
129
+ Here, the weights are defined as \( \beta \cdot
130
+ \left( \sum_{k < t} \gamma^{t-k} A^1(s_k, a_k, b_k) \)
131
+ """
132
+ T = advantages.shape[1]
133
+ discounted_advantages = advantages * (
134
+ gamma * torch.ones((1, T), device=advantages.device)
135
+ ) ** (-torch.arange(0, T, 1, device=advantages.device))
136
+ if exclude_k_equals_t:
137
+ sub = torch.eye(T, device=advantages.device)
138
+ else:
139
+ sub = torch.zeros((T, T), device=advantages.device)
140
+ # Identity is for \( k < t \), remove for \( k \leq t \)
141
+ ad_align_weights = discounted_advantages @ (
142
+ torch.triu(torch.ones((T, T), device=advantages.device)) - sub
143
+ )
144
+ t_discounts = (gamma * torch.ones((1, T), device=advantages.device)) ** (
145
+ torch.arange(0, T, 1, device=advantages.device)
146
+ )
147
+ ad_align_weights = t_discounts * ad_align_weights
148
+ if discount_t:
149
+ time_discounted_advantages = advantages * (
150
+ gamma * torch.ones((1, T), device=advantages.device)
151
+ ) ** (torch.arange(0, T, 1, device=advantages.device))
152
+ ad_align_weights = ad_align_weights - advantages + time_discounted_advantages
153
+ return ad_align_weights
154
+
155
+
156
+ def get_advantage_alignment_credits(
157
+ a1: torch.Tensor, # (B, S)
158
+ a1_alternative: torch.Tensor, # (B, S, A)
159
+ a2: torch.Tensor, # (B, S)
160
+ exclude_k_equals_t: bool,
161
+ beta: float,
162
+ gamma: float = 1.0,
163
+ use_old_ad_align: bool = False,
164
+ use_sign: bool = False,
165
+ clipping: float | None = None,
166
+ use_time_regularization: bool = False,
167
+ force_coop_first_step: bool = False,
168
+ use_variance_regularization: bool = False,
169
+ rloo_branch: bool = False,
170
+ reuse_baseline: bool = False,
171
+ mean_normalize_ad_align: bool = False,
172
+ whiten_adalign_advantages: bool = False,
173
+ whiten_adalign_advantages_time_step_wise: bool = False,
174
+ discount_t: bool = False,
175
+ ) -> torch.Tensor:
176
+ """
177
+ Calculate the advantage alignment credits with vectorization, as described in https://arxiv.org/abs/2406.14662.
178
+
179
+ Recall that the advantage opponent shaping term of the AdAlign policy gradient is:
180
+ \[
181
+ \beta \mathbb{E}_{\substack{
182
+ \tau \sim \text{Pr}_{\mu}^{\pi^1, \pi^2} \\
183
+ a_t' \sim \pi^1(\cdot \mid s_t)
184
+ }}
185
+ \left[\sum_{t=0}^\infty \gamma^{t}\left( \sum_{k\leq t} A^1(s_k,a^{\prime}_k,b_k) \right) A^{2}(s_t,a_t, b_t)\nabla_{\theta^1}\text{log } \pi^1(a_t|s_t) \right]
186
+ \]
187
+
188
+ This method computes the following:
189
+ \[
190
+ Credit(s_t, a_t, b_t) = \gamma^t \left[ A^1(s_t, a_t, b_t) + \beta \left( \sum_{k\leq t} A^1(s_k,a^{\prime}_k,b_k) \right) A^{2}(s_t,a_t, b_t) \right]
191
+ \]
192
+
193
+ Args:
194
+ a1: Advantages of the main trajectories for the current agent.
195
+ a1_alternative: Advantages of the alternative trajectories for the current agent.
196
+ a2: Advantages of the main trajectories for the other agent.
197
+ discount_factor: Discount factor for the advantage alignment.
198
+ beta: Beta parameter for the advantage alignment.
199
+ gamma: Gamma parameter for the advantage alignment.
200
+ use_sign_in_ad_align: Whether to use sign in the advantage alignment.
201
+
202
+ Returns:
203
+ torch.Tensor: The advantage alignment credits.
204
+ """
205
+
206
+ assert a1.dim() == a2.dim() == 2, "Advantages must be of shape (B, S)"
207
+ if a1_alternative is not None:
208
+ assert (
209
+ a1_alternative.dim() == 3
210
+ ), "Alternative advantages must be of shape (B, S, A)"
211
+ B, T, A = a1_alternative.shape
212
+ else:
213
+ B, T = a1.shape
214
+ assert a1.shape == a2.shape, "Not the same shape"
215
+
216
+ sub_tensors = {}
217
+
218
+ if use_old_ad_align:
219
+ ad_align_weights = get_advantage_alignment_weights(
220
+ advantages=a1,
221
+ exclude_k_equals_t=exclude_k_equals_t,
222
+ gamma=gamma,
223
+ discount_t=discount_t,
224
+ )
225
+ sub_tensors["ad_align_weights_prev"] = ad_align_weights
226
+ if exclude_k_equals_t:
227
+ ad_align_weights = gamma * ad_align_weights
228
+ else:
229
+ assert a1_alternative is not None, "Alternative advantages must be provided"
230
+ if rloo_branch:
231
+ a1_alternative = torch.cat([a1.unsqueeze(2), a1_alternative], dim=2)
232
+ a1_alternative = a1_alternative.mean(dim=2)
233
+ a1, baseline = get_rloo_credits(a1)
234
+ if reuse_baseline:
235
+ a1_alternative = a1_alternative - baseline
236
+ else:
237
+ a1_alternative, _ = get_rloo_credits(a1_alternative)
238
+ assert a1.shape == a1_alternative.shape, "Not the same shape"
239
+ ad_align_weights = get_advantage_alignment_weights(
240
+ advantages=a1_alternative,
241
+ exclude_k_equals_t=exclude_k_equals_t,
242
+ gamma=gamma,
243
+ )
244
+ sub_tensors["ad_align_weights"] = ad_align_weights
245
+
246
+ # Use sign
247
+ if use_sign:
248
+ assert beta == 1.0, "beta should be 1.0 when using sign"
249
+ positive_signs = ad_align_weights > 0
250
+ negative_signs = ad_align_weights < 0
251
+ ad_align_weights[positive_signs] = 1
252
+ ad_align_weights[negative_signs] = -1
253
+ sub_tensors["ad_align_weights_sign"] = ad_align_weights
254
+ # (rest are 0)
255
+
256
+ ###################
257
+ # Process weights
258
+ ###################
259
+
260
+ # Use clipping
261
+ if clipping not in [0.0, None]:
262
+ upper_mask = ad_align_weights > 1
263
+ lower_mask = ad_align_weights < -1
264
+
265
+ ad_align_weights = torch.clip(
266
+ ad_align_weights,
267
+ -clipping,
268
+ clipping,
269
+ )
270
+ clipping_ratio = (
271
+ torch.sum(upper_mask) + torch.sum(lower_mask)
272
+ ) / upper_mask.size
273
+ sub_tensors["clipped_ad_align_weights"] = ad_align_weights
274
+
275
+ # 1/1+t Regularization
276
+ if use_time_regularization:
277
+ t_values = torch.arange(1, T + 1).to(ad_align_weights.device)
278
+ ad_align_weights = ad_align_weights / t_values
279
+ sub_tensors["time_regularized_ad_align_weights"] = ad_align_weights
280
+
281
+ # Use coop on t=0
282
+ if force_coop_first_step:
283
+ ad_align_weights[:, 0] = 1
284
+ sub_tensors["coop_first_step_ad_align_weights"] = ad_align_weights
285
+
286
+ ####################################
287
+ # Compose elements together
288
+ ####################################
289
+
290
+ opp_shaping_terms = beta * ad_align_weights * a2
291
+ sub_tensors["ad_align_opp_shaping_terms"] = opp_shaping_terms
292
+
293
+ credits = a1 + opp_shaping_terms
294
+ if mean_normalize_ad_align:
295
+ credits = credits - credits.mean(dim=0)
296
+ sub_tensors["mean_normalized_ad_align_credits"] = credits
297
+ if whiten_adalign_advantages:
298
+ credits = (credits - credits.mean()) / (credits.std() + 1e-9)
299
+ sub_tensors["whitened_ad_align_credits"] = credits
300
+ if whiten_adalign_advantages_time_step_wise:
301
+ credits = (credits - credits.mean(dim=0, keepdim=True)) / (
302
+ credits.std(dim=0, keepdim=True) + 1e-9
303
+ )
304
+ sub_tensors["whitened_ad_align_credits_time_step_wise"] = credits
305
+ sub_tensors["final_ad_align_credits"] = credits
306
+
307
+ return credits, sub_tensors
src_code_for_reproducibility/training/tally_metrics.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/tally_metrics.py
3
+ Summary: Transforms tally files into aggregated metric summaries.
4
+ """
5
+
6
+ import os
7
+ from numbers import Number
8
+ from typing import Union
9
+
10
+ import wandb
11
+
12
+
13
+ class Tally:
14
+ """
15
+ Minimal scalar-first tally.
16
+ - Keys are strings.
17
+ - First add stores a scalar; subsequent adds upgrade to a list of scalars.
18
+ """
19
+
20
+ def __init__(self):
21
+ self.stats = {}
22
+
23
+ def reset(self):
24
+ """Reset all recorded metrics back to an empty dictionary."""
25
+ self.stats = {}
26
+
27
+ def _coerce_scalar(self, value: Union[int, float]) -> Union[int, float]:
28
+ """Ensure ``value`` is a plain Python scalar (detach tensors, etc.)."""
29
+ if hasattr(value, "item") and callable(getattr(value, "item")):
30
+ try:
31
+ value = value.item()
32
+ except Exception:
33
+ pass
34
+ if isinstance(value, Number):
35
+ return value
36
+ raise AssertionError("Metric must be a scalar number")
37
+
38
+ def add_metric(self, path: str, metric: Union[int, float]):
39
+ """Accumulate a metric under ``path`` (scalar on first add, list thereafter)."""
40
+ metric = float(metric)
41
+ assert isinstance(path, str), "Path must be a string."
42
+ assert isinstance(metric, float), "Metric must be a scalar number."
43
+
44
+ scalar = self._coerce_scalar(metric)
45
+ existing = self.stats.get(path)
46
+ if existing is None:
47
+ self.stats[path] = scalar
48
+ elif isinstance(existing, list):
49
+ existing.append(scalar)
50
+ else:
51
+ self.stats[path] = [existing, scalar]
52
+
53
+ def save(self, identifier: str, folder: str):
54
+ """Persist the tally as a pickle file under ``folder``."""
55
+ os.makedirs(name=folder, exist_ok=True)
56
+ try:
57
+ import pickle
58
+
59
+ pkl_path = os.path.join(folder, f"{identifier}.tally.pkl")
60
+ payload = self.stats
61
+ with open(pkl_path, "wb") as f:
62
+ pickle.dump(payload, f, protocol=pickle.HIGHEST_PROTOCOL)
63
+ except Exception:
64
+ pass
src_code_for_reproducibility/training/tally_rollout.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/tally_rollout.py
3
+ Summary: Serializes rollout data into tallies for downstream processing.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ from copy import deepcopy
9
+ from typing import Union
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ import torch
14
+ from transformers import AutoTokenizer
15
+
16
+
17
+ class RolloutTallyItem:
18
+ def __init__(
19
+ self,
20
+ crn_ids: list[str],
21
+ rollout_ids: list[str],
22
+ agent_ids: list[str],
23
+ metric_matrix: torch.Tensor,
24
+ ):
25
+ """Lightweight data container that keeps rollout-aligned metric matrices."""
26
+ if isinstance(crn_ids, torch.Tensor):
27
+ crn_ids = crn_ids.detach().cpu().numpy()
28
+ if isinstance(rollout_ids, torch.Tensor):
29
+ rollout_ids = rollout_ids.detach().cpu().numpy()
30
+ if isinstance(agent_ids, torch.Tensor):
31
+ agent_ids = agent_ids.detach().cpu().numpy()
32
+ self.crn_ids = crn_ids
33
+ self.rollout_ids = rollout_ids
34
+ self.agent_ids = agent_ids
35
+ metric_matrix = metric_matrix.detach().cpu()
36
+ assert (
37
+ 0 < metric_matrix.ndim <= 2
38
+ ), "Metric matrix must have less than or equal to 2 dimensions"
39
+ if metric_matrix.ndim == 1:
40
+ metric_matrix = metric_matrix.reshape(1, -1)
41
+ # Convert to float32 if tensor is in BFloat16 format (not supported by numpy)
42
+ if metric_matrix.dtype == torch.bfloat16:
43
+ metric_matrix = metric_matrix.float()
44
+ self.metric_matrix = metric_matrix.numpy()
45
+
46
+
47
+ class RolloutTally:
48
+ """
49
+ Tally is a utility class for collecting and storing training metrics.
50
+ It supports adding metrics at specified paths and saving them to disk.
51
+ """
52
+
53
+ def __init__(self):
54
+ """
55
+ Initializes the RolloutTally object.
56
+
57
+ Args:
58
+ tokenizer (AutoTokenizer): Tokenizer for converting token IDs to strings.
59
+ max_context_length (int, optional): Maximum context length for contextualized metrics. Defaults to 30.
60
+ """
61
+ # Array-preserving structure (leaf lists hold numpy arrays / scalars)
62
+ self.metrics = {}
63
+ # Global ordered list of sample identifiers (crn_id, rollout_id) added in the order samples are processed
64
+
65
+ def reset(self):
66
+ """Reset the tally to an empty dict."""
67
+ self.metrics = {}
68
+
69
+ def get_from_nested_dict(self, dictio: dict, path: str):
70
+ """Retrieve a nested entry, creating intermediate dicts as needed."""
71
+ assert isinstance(path, list), "Path must be list."
72
+ for sp in path[:-1]:
73
+ dictio = dictio.setdefault(sp, {})
74
+ return dictio.get(path[-1], None)
75
+
76
+ def set_at_path(self, dictio: dict, path: str, value):
77
+ """Store ``value`` at ``path``; helper used by ``add_metric``."""
78
+ for sp in path[:-1]:
79
+ dictio = dictio.setdefault(sp, {})
80
+ dictio[path[-1]] = value
81
+
82
+ def add_metric(self, path: list[str], rollout_tally_item: RolloutTallyItem):
83
+ """
84
+ Adds a metric to the base tally at the specified path.
85
+
86
+ Args:
87
+ path (list): List of keys representing the path in the base tally.
88
+ rollout_tally_item (RolloutTallyItem): The rollout tally item to add.
89
+ """
90
+ rollout_tally_item = deepcopy(rollout_tally_item)
91
+
92
+ # Update array-preserving tally
93
+ array_list = self.get_from_nested_dict(dictio=self.metrics, path=path)
94
+ if array_list is None:
95
+ self.set_at_path(dictio=self.metrics, path=path, value=[rollout_tally_item])
96
+ else:
97
+ array_list.append(rollout_tally_item)
98
+
99
+ def save(self, identifier: str, folder: str):
100
+ """Persist the tally as a pickle (metrics only) under ``folder``."""
101
+ os.makedirs(name=folder, exist_ok=True)
102
+
103
+ from datetime import datetime
104
+
105
+ now = datetime.now()
106
+
107
+ # Pickle only (fastest, exact structure with numpy/scalars at leaves)
108
+ try:
109
+ import pickle
110
+
111
+ pkl_path = os.path.join(folder, f"{identifier}.rt_tally.pkl")
112
+ payload = {"metrics": self.metrics}
113
+ with open(pkl_path, "wb") as f:
114
+ pickle.dump(payload, f, protocol=pickle.HIGHEST_PROTOCOL)
115
+ except Exception:
116
+ pass
src_code_for_reproducibility/training/tally_tokenwise.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/tally_tokenwise.py
3
+ Summary: Converts token-level tallies into per-token statistics.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ from typing import Any, Dict, List, Tuple, Union
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import torch
13
+ from transformers import AutoTokenizer
14
+
15
+
16
+ class ContextualizedTokenwiseTally:
17
+ """
18
+ Collect, store, and save token-level metrics per rollout.
19
+
20
+ - One DataFrame per rollout_id in `paths`
21
+ - Index = timestep (int)
22
+ - Columns are added incrementally via `add_contexts()` and `add_data()`
23
+ - Cells may contain scalars, strings, or lists (dtype=object)
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ tokenizer: AutoTokenizer,
29
+ paths: List[str],
30
+ max_context_length: int = 30,
31
+ ):
32
+ """
33
+ Args:
34
+ tokenizer: HuggingFace tokenizer used to convert tids -> tokens
35
+ paths: rollout identifiers (parallel to batch dimension)
36
+ max_context_length: truncate context token lists to this length
37
+ """
38
+ self.tokenizer = tokenizer
39
+ self.paths = paths
40
+ self.max_context_length = max_context_length
41
+ self.tally: Dict[str, pd.DataFrame] = {path: pd.DataFrame() for path in paths}
42
+
43
+ # set later by setters
44
+ self.contexts: torch.Tensor | None = None
45
+ self.action_mask: torch.Tensor | None = None
46
+ self.range: Tuple[int, int] | None = None
47
+
48
+ # --------- Utilities ---------
49
+
50
+ def tids_to_str(self, tids: List[int]) -> List[str]:
51
+ """Convert a list of token IDs to a list of token strings."""
52
+ return self.tokenizer.convert_ids_to_tokens(tids)
53
+
54
+ def _ensure_ready(self):
55
+ """Validate that action mask and range are configured prior to writes."""
56
+ assert self.action_mask is not None, "call set_action_mask(mask) first"
57
+ assert self.range is not None, "call set_range((start, end)) first"
58
+
59
+ @staticmethod
60
+ def _sanitize_filename(name: Any) -> str:
61
+ """Make a safe filename from any rollout_id."""
62
+ s = str(name)
63
+ bad = {os.sep, " ", ":", "|", "<", ">", '"', "'"}
64
+ if os.altsep is not None:
65
+ bad.add(os.altsep)
66
+ for ch in bad:
67
+ s = s.replace(ch, "_")
68
+ return s
69
+
70
+ @staticmethod
71
+ def _pad_left(seq: List[Any], length: int, pad_val: Any = "") -> List[Any]:
72
+ """Left-pad a sequence to `length` with `pad_val`."""
73
+ if len(seq) >= length:
74
+ return seq[-length:]
75
+ return [pad_val] * (length - len(seq)) + list(seq)
76
+
77
+ # --------- Setters ---------
78
+
79
+ def set_action_mask(self, action_mask: torch.Tensor):
80
+ """Register the (B, S) mask indicating which tokens correspond to actions."""
81
+ self.action_mask = action_mask
82
+
83
+ def set_range(self, range: Tuple[int, int]):
84
+ """Record which subset of ``paths`` the current mini-batch corresponds to."""
85
+ self.range = range
86
+
87
+ # --------- Column builders ---------
88
+
89
+ def add_contexts(self, contexts: torch.Tensor):
90
+ """
91
+ Add a single 'context' column (list[str]) for valid steps.
92
+
93
+ Expects `contexts` with shape (B, S): token id at each timestep.
94
+ For each valid timestep t, we use the last N tokens up to and including t:
95
+ window = contexts[i, max(0, t - N + 1) : t + 1]
96
+ The list is left-padded with "" to always be length N.
97
+ """
98
+ self._ensure_ready()
99
+
100
+ current_paths = self.paths[self.range[0] : self.range[1]]
101
+ B, S = contexts.shape
102
+ N = self.max_context_length
103
+
104
+ # to CPU ints once
105
+ contexts_cpu = contexts.detach().to("cpu")
106
+
107
+ for i in range(B):
108
+ rollout_id = current_paths[i]
109
+ df = self.tally.get(rollout_id, pd.DataFrame())
110
+
111
+ valid_idx = torch.nonzero(
112
+ self.action_mask[i].bool(), as_tuple=False
113
+ ).squeeze(-1)
114
+ if valid_idx.numel() == 0:
115
+ self.tally[rollout_id] = df
116
+ continue
117
+
118
+ idx_list = valid_idx.tolist()
119
+
120
+ # ensure index contains valid steps
121
+ if df.empty:
122
+ df = pd.DataFrame(index=idx_list)
123
+ else:
124
+ new_index = sorted(set(df.index.tolist()) | set(idx_list))
125
+ if list(df.index) != new_index:
126
+ df = df.reindex(new_index)
127
+
128
+ # build context windows
129
+ ctx_token_lists = []
130
+ for t in idx_list:
131
+ start = max(0, t - N + 1)
132
+ window_ids = contexts_cpu[i, start : t + 1].tolist()
133
+ window_toks = self.tids_to_str([int(x) for x in window_ids])
134
+ if len(window_toks) < N:
135
+ window_toks = [""] * (N - len(window_toks)) + window_toks
136
+ else:
137
+ window_toks = window_toks[-N:]
138
+ ctx_token_lists.append(window_toks)
139
+
140
+ # single 'context' column
141
+ if "context" not in df.columns:
142
+ df["context"] = pd.Series(index=df.index, dtype=object)
143
+ df.loc[idx_list, "context"] = pd.Series(
144
+ ctx_token_lists, index=idx_list, dtype=object
145
+ )
146
+
147
+ self.tally[rollout_id] = df
148
+
149
+ def add_data(
150
+ self,
151
+ metric_id: str,
152
+ metrics: torch.Tensor,
153
+ to_tids: bool = False,
154
+ ):
155
+ """
156
+ Add a metric column for valid steps.
157
+
158
+ Args:
159
+ metric_id: column name
160
+ metrics: shape (B, S) for scalars/ids or (B, S, K) for top-k vectors
161
+ to_tids: if True, treat ints/lists of ints as tids and convert to tokens
162
+ """
163
+ self._ensure_ready()
164
+ current_paths = self.paths[self.range[0] : self.range[1]]
165
+
166
+ if metrics.dim() == 2:
167
+ B, S = metrics.shape
168
+ elif metrics.dim() == 3:
169
+ B, S, _ = metrics.shape
170
+ else:
171
+ raise ValueError("metrics must be (B, S) or (B, S, K)")
172
+
173
+ for i in range(B):
174
+ rollout_id = current_paths[i]
175
+ df = self.tally.get(rollout_id, pd.DataFrame())
176
+
177
+ valid_idx = torch.nonzero(
178
+ self.action_mask[i].bool(), as_tuple=False
179
+ ).squeeze(-1)
180
+ if valid_idx.numel() == 0:
181
+ self.tally[rollout_id] = df
182
+ continue
183
+
184
+ idx_list = valid_idx.detach().cpu().tolist()
185
+
186
+ # Ensure index contains valid steps
187
+ if df.empty:
188
+ df = pd.DataFrame(index=idx_list)
189
+ else:
190
+ new_index = sorted(set(df.index.tolist()) | set(idx_list))
191
+ if list(df.index) != new_index:
192
+ df = df.reindex(new_index)
193
+
194
+ # Slice metrics at valid steps
195
+ m_valid = metrics[i][valid_idx]
196
+
197
+ # -> pure python lists (1D list or list-of-lists)
198
+ values = m_valid.detach().cpu().tolist()
199
+
200
+ # optional tids -> tokens
201
+ if to_tids:
202
+
203
+ def _to_tokish(x):
204
+ if isinstance(x, list):
205
+ return self.tids_to_str([int(v) for v in x])
206
+ else:
207
+ return self.tids_to_str([int(x)])[0]
208
+
209
+ values = [_to_tokish(v) for v in values]
210
+
211
+ # Ensure column exists with object dtype, then assign via aligned Series
212
+ if metric_id not in df.columns:
213
+ df[metric_id] = pd.Series(index=df.index, dtype=object)
214
+
215
+ if isinstance(values, np.ndarray):
216
+ values = values.tolist()
217
+
218
+ if len(values) != len(idx_list):
219
+ raise ValueError(
220
+ f"Length mismatch for '{metric_id}': values={len(values)} vs idx_list={len(idx_list)}"
221
+ )
222
+
223
+ df.loc[idx_list, metric_id] = pd.Series(
224
+ values, index=idx_list, dtype=object
225
+ )
226
+ self.tally[rollout_id] = df
227
+
228
+ # --------- Saving ---------
229
+
230
+ def save(self, path: str):
231
+ """
232
+ Write a manifest JSON and one CSV per rollout.
233
+
234
+ - Manifest includes metadata only (safe to JSON).
235
+ - Each rollout CSV is written with index label 'timestep'.
236
+ - Only a single 'context' column (list[str]).
237
+ """
238
+ if not self.tally or all(df.empty for df in self.tally.values()):
239
+ return
240
+
241
+ os.makedirs(path, exist_ok=True)
242
+ from datetime import datetime
243
+
244
+ now = datetime.now()
245
+
246
+ manifest = {
247
+ "created_at": f"{now:%Y-%m-%d %H:%M:%S}",
248
+ "max_context_length": self.max_context_length,
249
+ "num_rollouts": len(self.tally),
250
+ "rollouts": [],
251
+ }
252
+
253
+ for rid, df in self.tally.items():
254
+ rid_str = str(rid)
255
+ safe_name = self._sanitize_filename(rid_str)
256
+ csv_path = os.path.join(path, f"{safe_name}_tokenwise.csv")
257
+
258
+ # Put 'context' first, then the rest
259
+ cols = ["context"] + [c for c in df.columns if c != "context"]
260
+ try:
261
+ df[cols].to_csv(csv_path, index=True, index_label="timestep")
262
+ except Exception as e:
263
+ continue
264
+
265
+ manifest["rollouts"].append(
266
+ {
267
+ "rollout_id": rid_str,
268
+ "csv": csv_path,
269
+ "num_rows": int(df.shape[0]),
270
+ "columns": cols,
271
+ }
272
+ )
273
+
274
+ manifest_path = os.path.join(
275
+ path, f"tokenwise_manifest_{now:%Y-%m-%d___%H-%M-%S}.json"
276
+ )
277
+ with open(manifest_path, "w") as fp:
278
+ json.dump(manifest, fp, indent=2)
src_code_for_reproducibility/training/tokenize_chats.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/tokenize_chats.py
3
+ Summary: Tokenizes chat datasets and prepares tensors for training.
4
+ """
5
+
6
+ import logging
7
+ import sys
8
+
9
+ import regex
10
+ import torch
11
+ from transformers import AutoTokenizer
12
+
13
+ from mllm.training.training_data_utils import TrainingChatTurn, TrajectoryBatch
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logger.addHandler(logging.StreamHandler(sys.stdout))
17
+
18
+
19
+ def process_training_chat(
20
+ tokenizer: AutoTokenizer,
21
+ chat_history: list[TrainingChatTurn],
22
+ entropy_mask_regex: str | None = None,
23
+ exploration_prompts_to_remove: list[str] = [],
24
+ use_engine_out_token_ids: bool = False,
25
+ ) -> tuple[torch.IntTensor, torch.BoolTensor, torch.IntTensor, torch.BoolTensor]:
26
+ """Tokenize a single training chat and build aligned per-token masks.
27
+
28
+ Given an ordered list of `TrainingChatTurn`, this function tokenizes each
29
+ turn independently using the tokenizer's chat template, then concatenates
30
+ all resulting token sequences. It also constructs three parallel 1D masks
31
+ that align with the concatenated tokens:
32
+
33
+ - input_ids: token ids for the entire chat, turn by turn
34
+ - action_mask: True for tokens that belong to assistant turns (i.e., model
35
+ actions), False for tokens from other roles
36
+ - timesteps: per-token time step copied from the originating turn's
37
+ `time_step`
38
+ - state_ends_mask: True for the last token of any turn where
39
+ `is_state_end` is True, otherwise False
40
+
41
+ Important details:
42
+ - Each turn is passed as a single-message list to
43
+ `tokenizer.apply_chat_template` and flattened; the per-turn outputs are
44
+ then concatenated in the original order.
45
+ - Turn boundaries are not explicitly encoded beyond what the chat template
46
+ inserts; masks provide alignment for learning signals and state endings.
47
+ - No truncation or padding is performed here; downstream code should handle
48
+ batching/padding as needed.
49
+ - Note on dtypes: `input_ids` will be a LongTensor (int64). `action_mask`
50
+ and `state_ends_mask` are BoolTensors. `timesteps` is currently created
51
+ as a float tensor; adjust the implementation if integer dtype is
52
+ required downstream.
53
+
54
+ Args:
55
+ tokenizer: A Hugging Face tokenizer supporting `apply_chat_template`.
56
+ chat_history: Ordered list of `TrainingChatTurn` forming one dialogue.
57
+
58
+ Returns:
59
+ A tuple of four 1D tensors, all of equal length N (the total number of
60
+ tokens across all turns), in the following order:
61
+ - input_ids (LongTensor)
62
+ - action_mask (BoolTensor)
63
+ - timesteps (FloatTensor as implemented; see note above)
64
+ - state_ends_mask (BoolTensor)
65
+ """
66
+ state_ends_mask = []
67
+ input_ids = []
68
+ action_mask = []
69
+ timesteps = []
70
+ entropy_mask = []
71
+ engine_log_probs = []
72
+ for train_chat_turn in chat_history:
73
+ is_state_end = train_chat_turn.is_state_end
74
+ time_step = train_chat_turn.time_step
75
+ is_action = train_chat_turn.role == "assistant"
76
+
77
+ # Remove exploration prompts from training data
78
+ for exploration_prompt in exploration_prompts_to_remove:
79
+ if exploration_prompt in train_chat_turn.content:
80
+ train_chat_turn.content = train_chat_turn.content.replace(
81
+ exploration_prompt, ""
82
+ )
83
+
84
+ chat_turn = {
85
+ "role": train_chat_turn.role,
86
+ "content": train_chat_turn.content,
87
+ }
88
+ if entropy_mask_regex is not None:
89
+ is_entropy_mask_true = (
90
+ regex.search(entropy_mask_regex, train_chat_turn.content) is not None
91
+ )
92
+ else:
93
+ is_entropy_mask_true = True
94
+ if is_action:
95
+ chat_turn_ids = train_chat_turn.out_token_ids
96
+ nb_chat_turns_ids = chat_turn_ids.numel()
97
+ action_mask.append(torch.ones(nb_chat_turns_ids, dtype=torch.bool))
98
+ engine_log_probs.append(train_chat_turn.log_probs)
99
+ else:
100
+ chat_turn_ids = train_chat_turn.chat_template_token_ids
101
+ nb_chat_turns_ids = chat_turn_ids.numel()
102
+ action_mask.append(torch.zeros(nb_chat_turns_ids, dtype=torch.bool))
103
+ engine_log_probs.append(torch.zeros(nb_chat_turns_ids, dtype=torch.float))
104
+ nb_chat_turns_ids = chat_turn_ids.numel()
105
+ state_ends_mask.append(torch.zeros(nb_chat_turns_ids, dtype=torch.bool))
106
+ if is_state_end:
107
+ state_ends_mask[-1][-1] = True # last token is state end
108
+ input_ids.append(chat_turn_ids)
109
+ entropy_mask.append(torch.ones(nb_chat_turns_ids, dtype=torch.bool))
110
+ if not is_entropy_mask_true:
111
+ entropy_mask[-1] = entropy_mask[-1] * False
112
+ timesteps.append(torch.ones(nb_chat_turns_ids) * time_step)
113
+ input_ids = torch.cat(input_ids)
114
+ action_mask = torch.cat(action_mask)
115
+ entropy_mask = torch.cat(entropy_mask)
116
+ timesteps = torch.cat(timesteps)
117
+ timesteps = timesteps.to(torch.long)
118
+ state_ends_mask = torch.cat(state_ends_mask)
119
+ engine_log_probs = torch.cat(engine_log_probs)
120
+
121
+ return (
122
+ input_ids,
123
+ action_mask,
124
+ entropy_mask,
125
+ timesteps,
126
+ state_ends_mask,
127
+ engine_log_probs,
128
+ )
src_code_for_reproducibility/training/trainer_ad_align.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: mllm/training/trainer_ad_align.py
3
+ Summary: Trainer specialized for the advantage-alignment objective.
4
+ """
5
+
6
+ import copy
7
+ import logging
8
+ import sys
9
+ from dataclasses import dataclass
10
+ from typing import Tuple
11
+
12
+ import torch
13
+ from torch.nn.utils.rnn import pad_sequence
14
+
15
+ from mllm.markov_games.rollout_tree import (
16
+ ChatTurn,
17
+ RolloutTreeBranchNode,
18
+ RolloutTreeRootNode,
19
+ )
20
+ from mllm.training.credit_methods import (
21
+ get_advantage_alignment_credits,
22
+ get_discounted_state_visitation_credits,
23
+ )
24
+ from mllm.training.tally_metrics import Tally
25
+ from mllm.training.tally_rollout import RolloutTally, RolloutTallyItem
26
+ from mllm.training.tally_tokenwise import ContextualizedTokenwiseTally
27
+ from mllm.training.tokenize_chats import process_training_chat
28
+ from mllm.training.trainer_common import BaseTrainer
29
+ from mllm.training.training_data_utils import (
30
+ AdvantagePacket,
31
+ TrainingBatch,
32
+ TrainingChatTurn,
33
+ TrajectoryBatch,
34
+ get_main_chat_list_and_rewards,
35
+ get_tokenwise_credits,
36
+ )
37
+ from mllm.utils.resource_context import resource_logger_context
38
+
39
+ logger = logging.getLogger(__name__)
40
+ logger.addHandler(logging.StreamHandler(sys.stdout))
41
+
42
+ RolloutId = int
43
+ AgentId = str
44
+
45
+
46
+ @dataclass
47
+ class AdAlignTrainingData:
48
+ """Holds tensorized rollouts plus precomputed advantages for one agent."""
49
+
50
+ agent_id: str
51
+ main_data: TrajectoryBatch
52
+ # list-of-tensors: per rollout advantages with length jT
53
+ main_advantages: list[torch.FloatTensor] | None = None
54
+ # list-of-tensors: per rollout matrix (jT, A)
55
+ alternative_advantages: list[torch.FloatTensor] | None = None
56
+ advantage_alignment_credits: list[torch.FloatTensor] | None = None
57
+
58
+
59
+ def get_alternative_chat_histories(
60
+ agent_id: str, root: RolloutTreeRootNode
61
+ ) -> list[list[TrainingChatTurn], list[torch.FloatTensor]]:
62
+ """
63
+ Traverse every unilateral branch under ``root`` and collect chat/reward histories.
64
+
65
+ Returns
66
+ -------
67
+ alternative_chats:
68
+ Flattened list of chat turns for each branch (ordered by branch depth).
69
+ alternative_rewards:
70
+ Matching list of reward tensors aligned with the chat history.
71
+ """
72
+ current_node = root.child
73
+ branches = current_node.branches
74
+ pre_branch_chat = []
75
+ pre_branch_rewards = []
76
+ alternative_rewards = []
77
+ alternative_chats = []
78
+ while current_node is not None:
79
+ assert isinstance(
80
+ current_node, RolloutTreeBranchNode
81
+ ), "Current node should be a branch node."
82
+ main_node = current_node.main_child
83
+ branches = current_node.branches
84
+ current_node = main_node.child
85
+
86
+ # Get the `A` alternative trajectories
87
+ alternative_nodes = branches[agent_id]
88
+ for alt_node in alternative_nodes:
89
+ post_branch_chat, post_branch_rewards = get_main_chat_list_and_rewards(
90
+ agent_id=agent_id, root=alt_node
91
+ )
92
+ branch_chat = pre_branch_chat + post_branch_chat
93
+ alternative_chats.append(branch_chat)
94
+ alternative_rewards.append(
95
+ torch.cat([torch.tensor(pre_branch_rewards), post_branch_rewards])
96
+ )
97
+
98
+ chat_turns: list[ChatTurn] = main_node.step_log.action_logs[agent_id].chat_turns
99
+ chat_turns: list[TrainingChatTurn] = [
100
+ TrainingChatTurn(time_step=main_node.time_step, **turn.model_dump())
101
+ for turn in chat_turns
102
+ ]
103
+
104
+ pre_branch_chat.extend(chat_turns)
105
+ pre_branch_rewards.append(
106
+ main_node.step_log.simulation_step_log.rewards[agent_id]
107
+ )
108
+
109
+ return alternative_chats, alternative_rewards
110
+
111
+
112
+ class TrainerAdAlign(BaseTrainer):
113
+ """
114
+ Extends the reinforce trainer to support Advantage Alignment.
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ ad_align_beta: float,
120
+ ad_align_gamma: float,
121
+ ad_align_exclude_k_equals_t: bool,
122
+ ad_align_use_sign: bool,
123
+ ad_align_clipping: float,
124
+ ad_align_force_coop_first_step: bool,
125
+ use_old_ad_align: bool,
126
+ use_time_regularization: bool,
127
+ rloo_branch: bool,
128
+ reuse_baseline: bool,
129
+ ad_align_beta_anneal_step: int = -1,
130
+ ad_align_beta_anneal_rate: float = 0.5,
131
+ min_ad_align_beta: float = 0.1,
132
+ mean_normalize_ad_align: bool = False,
133
+ whiten_adalign_advantages: bool = False,
134
+ whiten_adalign_advantages_time_step_wise: bool = False,
135
+ ad_align_discount_t: bool = False,
136
+ *args,
137
+ **kwargs,
138
+ ):
139
+ """
140
+ Initialize the advantage alignment trainer.
141
+ Args:
142
+ ad_align_beta: Beta parameter for the advantage alignment.
143
+ ad_align_gamma: Gamma parameter for the advantage alignment.
144
+ ad_align_exclude_k_equals_t: Whether to include k = t in the advantage alignment.
145
+ ad_align_use_sign: Whether to use sign in the advantage alignment.
146
+ ad_align_clipping: Clipping value for the advantage alignment.
147
+ ad_align_force_coop_first_step: Whether to force coop on the first step of the advantage alignment.
148
+ """
149
+ super().__init__(*args, **kwargs)
150
+ self.ad_align_beta = ad_align_beta
151
+ self.ad_align_gamma = ad_align_gamma
152
+ self.ad_align_exclude_k_equals_t = ad_align_exclude_k_equals_t
153
+ self.ad_align_use_sign = ad_align_use_sign
154
+ self.ad_align_clipping = ad_align_clipping
155
+ self.ad_align_force_coop_first_step = ad_align_force_coop_first_step
156
+ self.use_old_ad_align = use_old_ad_align
157
+ self.use_time_regularization = use_time_regularization
158
+ self.rloo_branch = rloo_branch
159
+ self.reuse_baseline = reuse_baseline
160
+ self.ad_align_beta_anneal_step = ad_align_beta_anneal_step
161
+ self.ad_align_beta_anneal_rate = ad_align_beta_anneal_rate
162
+ self.min_ad_align_beta = min_ad_align_beta
163
+ self.past_ad_align_step = -1
164
+ self.mean_normalize_ad_align = mean_normalize_ad_align
165
+ self.whiten_adalign_advantages = whiten_adalign_advantages
166
+ self.whiten_adalign_advantages_time_step_wise = (
167
+ whiten_adalign_advantages_time_step_wise
168
+ )
169
+ self.ad_align_discount_t = ad_align_discount_t
170
+ self.training_data: dict[AgentId, AdAlignTrainingData] = {}
171
+ self.debug_path_list: list[str] = []
172
+
173
+ def set_agent_trajectory_data(
174
+ self, agent_id: str, roots: list[RolloutTreeRootNode]
175
+ ):
176
+ """
177
+ Materialize main and alternative trajectory tensors used by the advantage-alignment trainer.
178
+ """
179
+
180
+ B = len(roots) # Number of rollouts
181
+
182
+ # For main rollouts
183
+ batch_rollout_ids = []
184
+ batch_crn_ids = []
185
+ batch_input_ids = []
186
+ batch_action_mask = []
187
+ batch_entropy_mask = []
188
+ batch_timesteps = []
189
+ batch_state_ends_mask = []
190
+ batch_engine_log_probs = []
191
+ batch_rewards = []
192
+
193
+ # For alternative actions rollouts
194
+ batch_branching_time_steps = []
195
+ alternative_batch_input_ids = []
196
+ alternative_batch_action_mask = []
197
+ alternative_batch_entropy_mask = []
198
+ alternative_batch_timesteps = []
199
+ alternative_batch_state_ends_mask = []
200
+ alternative_batch_engine_log_probs = []
201
+ alternative_batch_rewards = []
202
+ jT_list = []
203
+
204
+ try:
205
+ A = len(roots[0].child.branches[agent_id]) # Number of alternative actions
206
+ except:
207
+ A = 0
208
+
209
+ for root in roots:
210
+ rollout_id = root.id
211
+ self.debug_path_list.append(
212
+ "mgid:" + str(rollout_id) + "_agent_id:" + agent_id
213
+ )
214
+ # Get main trajectory
215
+ batch_rollout_ids.append(rollout_id)
216
+ batch_crn_ids.append(root.crn_id)
217
+ main_chat, main_rewards = get_main_chat_list_and_rewards(
218
+ agent_id=agent_id, root=root
219
+ )
220
+ (
221
+ input_ids,
222
+ action_mask,
223
+ entropy_mask,
224
+ timesteps,
225
+ state_ends_mask,
226
+ engine_log_probs,
227
+ ) = process_training_chat(
228
+ tokenizer=self.tokenizer,
229
+ chat_history=main_chat,
230
+ entropy_mask_regex=self.entropy_mask_regex,
231
+ exploration_prompts_to_remove=self.exploration_prompts_to_remove,
232
+ )
233
+ batch_input_ids.append(input_ids)
234
+ batch_action_mask.append(action_mask)
235
+ batch_entropy_mask.append(entropy_mask)
236
+ batch_timesteps.append(timesteps)
237
+ batch_state_ends_mask.append(state_ends_mask)
238
+ batch_engine_log_probs.append(engine_log_probs)
239
+ batch_rewards.append(main_rewards)
240
+ jT = (
241
+ main_rewards.numel()
242
+ ) # Number of timesteps inferred from reward tensor length.
243
+ jT_list.append(jT)
244
+ if A > 0:
245
+ # We get the branching time steps for each of the `jT` time steps in the main trajectory.
246
+ branching_time_steps = [bt for item in range(jT) for bt in A * [item]]
247
+ batch_branching_time_steps.extend(branching_time_steps)
248
+
249
+ # Get all of the (jT*A) alternative trajectories in the tree
250
+ # (jT is the number of time steps in the main trajectory, A is the number of alternative actions)
251
+ alternative_chats, alternative_rewards = get_alternative_chat_histories(
252
+ agent_id=agent_id, root=root
253
+ )
254
+ assert (
255
+ len(alternative_chats) == A * jT
256
+ ), "Incorrect number of alternative trajectories."
257
+
258
+ for chat, rewards in zip(alternative_chats, alternative_rewards):
259
+ (
260
+ input_ids,
261
+ action_mask,
262
+ entropy_mask,
263
+ timesteps,
264
+ state_ends_mask,
265
+ engine_log_probs,
266
+ ) = process_training_chat(
267
+ tokenizer=self.tokenizer,
268
+ chat_history=chat,
269
+ entropy_mask_regex=self.entropy_mask_regex,
270
+ exploration_prompts_to_remove=self.exploration_prompts_to_remove,
271
+ )
272
+ alternative_batch_input_ids.append(input_ids)
273
+ alternative_batch_action_mask.append(action_mask)
274
+ alternative_batch_entropy_mask.append(entropy_mask)
275
+ alternative_batch_timesteps.append(timesteps)
276
+ alternative_batch_state_ends_mask.append(state_ends_mask)
277
+ alternative_batch_engine_log_probs.append(engine_log_probs)
278
+ alternative_batch_rewards.append(rewards)
279
+
280
+ jT_list = torch.Tensor(jT_list)
281
+
282
+ # Assert that number of alternative actions is constant
283
+ # assert len(set(nb_alternative_actions)) == 1, "Number of alternative actions must be constant"
284
+ # A = nb_alternative_actions[0]
285
+
286
+ trajectory_batch = TrajectoryBatch(
287
+ rollout_ids=torch.tensor(batch_rollout_ids, dtype=torch.int32), # (B,)
288
+ crn_ids=torch.tensor(batch_crn_ids, dtype=torch.int32),
289
+ agent_ids=[agent_id] * len(batch_rollout_ids),
290
+ batch_input_ids=batch_input_ids,
291
+ batch_action_mask=batch_action_mask,
292
+ batch_entropy_mask=batch_entropy_mask,
293
+ batch_timesteps=batch_timesteps,
294
+ batch_state_ends_mask=batch_state_ends_mask,
295
+ batch_engine_log_probs=batch_engine_log_probs,
296
+ batch_rewards=batch_rewards,
297
+ )
298
+ # Get Advantages & Train Critic
299
+ with resource_logger_context(
300
+ logger, "Get advantages with critic gradient accumulation"
301
+ ):
302
+ self.batch_advantages: torch.FloatTensor = (
303
+ self.get_advantages_with_critic_gradient_accumulation(trajectory_batch)
304
+ ) # (B, jT)
305
+
306
+ if A > 0:
307
+ # Here, `A` is the number of alternative actions / trajectories taken at each time step.
308
+ # For each of the `B` rollout perspectives, at each of its jT (`j` is for jagged, since each main rollout may be of a different length) steps, we take A alternate trajectories (from different actions).
309
+ # Therefore, we have ∑jT * A trajectories to process. If each of the main trajectories have T steps, we will have `B*T*A` to process.
310
+ with resource_logger_context(logger, "Create alternative trajectory batch"):
311
+ sum_jT = int(torch.sum(jT_list).item())
312
+ jT_list = (
313
+ jT_list.int().tolist()
314
+ ) # (jT,) # (we only want the advantages where we branched out)
315
+ alternative_trajectory_batch = TrajectoryBatch(
316
+ rollout_ids=torch.zeros(A * sum_jT, dtype=torch.int32),
317
+ crn_ids=torch.zeros(A * sum_jT, dtype=torch.int32),
318
+ agent_ids=[agent_id] * (A * sum_jT),
319
+ batch_input_ids=alternative_batch_input_ids,
320
+ batch_action_mask=alternative_batch_action_mask,
321
+ batch_entropy_mask=alternative_batch_entropy_mask,
322
+ batch_timesteps=alternative_batch_timesteps,
323
+ batch_state_ends_mask=alternative_batch_state_ends_mask,
324
+ batch_engine_log_probs=alternative_batch_engine_log_probs,
325
+ batch_rewards=alternative_batch_rewards,
326
+ )
327
+
328
+ # Get alternative advantages
329
+ # BAAs stands for batch alternative advantages
330
+ # (torch nested tensors have very little api support, so we have to do some odd manual work here)
331
+ with resource_logger_context(
332
+ logger, "Compute alternative advantage estimates"
333
+ ):
334
+ BAAs_list = self.get_advantages_with_critic_gradient_accumulation(
335
+ alternative_trajectory_batch
336
+ ) # list length (∑jT * A), each (jT',)
337
+ # Pad alternative advantages to (∑jT*A, P)
338
+
339
+ BAAs_padded = pad_sequence(
340
+ BAAs_list, batch_first=True, padding_value=0.0
341
+ )
342
+ branch_idx = torch.tensor(
343
+ batch_branching_time_steps,
344
+ device=BAAs_padded.device,
345
+ dtype=torch.long,
346
+ )
347
+ gathered = BAAs_padded.gather(
348
+ dim=1, index=branch_idx.unsqueeze(1)
349
+ ).squeeze(1)
350
+ # Reshape and split per rollout, then transpose to (jT_i, A)
351
+ gathered = gathered.view(A, sum_jT) # (A, ∑jT)
352
+ blocks = list(
353
+ torch.split(gathered, jT_list, dim=1)
354
+ ) # len B, shapes (A, jT_i)
355
+ BAAs = [
356
+ blk.transpose(0, 1).contiguous() for blk in blocks
357
+ ] # list of (jT_i, A)
358
+ if self.ad_align_beta_anneal_step > 0:
359
+ max_rollout_id = torch.max(trajectory_batch.rollout_ids) + 1
360
+ if (
361
+ max_rollout_id % self.ad_align_beta_anneal_step == 0
362
+ and self.past_ad_align_step != max_rollout_id
363
+ ):
364
+ self.ad_align_beta = max(
365
+ self.ad_align_beta * self.ad_align_beta_anneal_rate,
366
+ self.min_ad_align_beta,
367
+ )
368
+ logger.info(f"Annealing ad_align_beta to {self.ad_align_beta}")
369
+ self.past_ad_align_step = max_rollout_id
370
+ self.training_data[agent_id] = AdAlignTrainingData(
371
+ agent_id=agent_id,
372
+ main_data=trajectory_batch,
373
+ main_advantages=self.batch_advantages,
374
+ alternative_advantages=BAAs if A > 0 else None,
375
+ )
376
+
377
+ def share_advantage_data(self) -> list[AdvantagePacket]:
378
+ """
379
+ Share the advantage alignment data with other agents.
380
+ Returns:
381
+ AdvantagePacket: The advantage packet containing the agent's advantages.
382
+ """
383
+ logger.info(f"Sharing advantage alignment data.")
384
+ advantage_packets = []
385
+ for _, agent_data in self.training_data.items():
386
+ advantage_packets.append(
387
+ AdvantagePacket(
388
+ agent_id=agent_data.agent_id,
389
+ rollout_ids=agent_data.main_data.rollout_ids,
390
+ main_advantages=agent_data.main_advantages,
391
+ )
392
+ )
393
+ return advantage_packets
394
+
395
+ def receive_advantage_data(self, advantage_packets: list[AdvantagePacket]):
396
+ """
397
+ Receive advantage packets from other players.
398
+ These contain the advantages of the other players' rollouts estimated by them.
399
+ """
400
+ logger.info(f"Receiving advantage packets.")
401
+
402
+ assert (
403
+ len(advantage_packets) > 0
404
+ ), "At least one advantage packet must be provided."
405
+
406
+ for agent_id, agent_data in self.training_data.items():
407
+ coagent_advantage_packets = [
408
+ packet for packet in advantage_packets if packet.agent_id != agent_id
409
+ ]
410
+ agent_rollout_ids = agent_data.main_data.rollout_ids
411
+ agent_advantages = agent_data.main_advantages
412
+ co_agent_advantages = []
413
+ for rollout_id in agent_rollout_ids:
414
+ for co_agent_packet in coagent_advantage_packets:
415
+ if rollout_id in co_agent_packet.rollout_ids:
416
+ index = torch.where(rollout_id == co_agent_packet.rollout_ids)[
417
+ 0
418
+ ].item()
419
+ co_agent_advantages.append(
420
+ co_agent_packet.main_advantages[index]
421
+ )
422
+ # assumes that its two player game, with one co-agent
423
+ break
424
+ assert len(co_agent_advantages) == len(agent_advantages)
425
+ B = len(agent_advantages)
426
+ assert all(
427
+ a.shape[0] == b.shape[0]
428
+ for a, b in zip(co_agent_advantages, agent_advantages)
429
+ ), "Number of advantages must match for advantage alignment."
430
+
431
+ # Get padded tensors (advantage alignment is invariant to padding)
432
+ lengths = torch.tensor(
433
+ [len(t) for t in agent_advantages],
434
+ device=self.device,
435
+ dtype=torch.long,
436
+ )
437
+ padded_main_advantages = pad_sequence(
438
+ agent_advantages, batch_first=True, padding_value=0.0
439
+ )
440
+ if agent_data.alternative_advantages:
441
+ padded_alternative_advantages = pad_sequence(
442
+ agent_data.alternative_advantages,
443
+ batch_first=True,
444
+ padding_value=0.0,
445
+ ) # (B, P, A)
446
+ else:
447
+ padded_alternative_advantages = None
448
+ padded_co_agent_advantages = pad_sequence(
449
+ co_agent_advantages, batch_first=True, padding_value=0.0
450
+ )
451
+
452
+ # Create training batch data
453
+ credits, sub_tensors = get_advantage_alignment_credits(
454
+ a1=padded_main_advantages,
455
+ a1_alternative=padded_alternative_advantages,
456
+ a2=padded_co_agent_advantages,
457
+ beta=self.ad_align_beta,
458
+ gamma=self.ad_align_gamma,
459
+ exclude_k_equals_t=self.ad_align_exclude_k_equals_t,
460
+ use_sign=self.ad_align_use_sign,
461
+ clipping=self.ad_align_clipping,
462
+ force_coop_first_step=self.ad_align_force_coop_first_step,
463
+ use_old_ad_align=self.use_old_ad_align,
464
+ use_time_regularization=self.use_time_regularization,
465
+ rloo_branch=self.rloo_branch,
466
+ reuse_baseline=self.reuse_baseline,
467
+ mean_normalize_ad_align=self.mean_normalize_ad_align,
468
+ whiten_adalign_advantages=self.whiten_adalign_advantages,
469
+ whiten_adalign_advantages_time_step_wise=self.whiten_adalign_advantages_time_step_wise,
470
+ discount_t=self.ad_align_discount_t,
471
+ )
472
+ for key, value in sub_tensors.items():
473
+ self.rollout_tally.add_metric(
474
+ path=[key],
475
+ rollout_tally_item=RolloutTallyItem(
476
+ crn_ids=agent_data.main_data.crn_ids,
477
+ rollout_ids=agent_data.main_data.rollout_ids,
478
+ agent_ids=agent_data.main_data.agent_ids,
479
+ metric_matrix=value,
480
+ ),
481
+ )
482
+
483
+ if not self.skip_discounted_state_visitation:
484
+ credits = get_discounted_state_visitation_credits(
485
+ credits,
486
+ self.discount_factor,
487
+ )
488
+ self.rollout_tally.add_metric(
489
+ path=["discounted_state_visitation_credits"],
490
+ rollout_tally_item=RolloutTallyItem(
491
+ crn_ids=agent_data.main_data.crn_ids,
492
+ rollout_ids=agent_data.main_data.rollout_ids,
493
+ agent_ids=agent_data.main_data.agent_ids,
494
+ metric_matrix=sub_tensors[
495
+ "discounted_state_visitation_credits"
496
+ ],
497
+ ),
498
+ )
499
+
500
+ # Slice back to jagged
501
+ advantage_alignment_credits = [credits[i, : lengths[i]] for i in range(B)]
502
+ # Replace stored training data for this agent by the concrete trajectory batch
503
+ # and attach the computed credits for policy gradient.
504
+ self.training_data[agent_id] = agent_data.main_data
505
+ self.training_data[agent_id].batch_credits = advantage_alignment_credits