Ouzhang commited on
Commit
abf246e
·
verified ·
1 Parent(s): 8e29a6e

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. MemGen-main/common/config.py +91 -0
  2. MemGen-main/common/logger.py +10 -0
  3. MemGen-main/configs/latent_memory/gpqa.yaml +173 -0
  4. MemGen-main/configs/latent_memory/gsm8k.yaml +173 -0
  5. MemGen-main/configs/latent_memory/kodcode.yaml +176 -0
  6. MemGen-main/configs/latent_memory/triviaqa.yaml +172 -0
  7. MemGen-main/configs/zero2.yaml +22 -0
  8. MemGen-main/data/__init__.py +26 -0
  9. MemGen-main/data/base_builder.py +38 -0
  10. MemGen-main/data/base_env.py +38 -0
  11. MemGen-main/data/gpqa/builder.py +102 -0
  12. MemGen-main/data/gpqa/env.py +14 -0
  13. MemGen-main/data/gsm8k/builder.py +74 -0
  14. MemGen-main/data/gsm8k/env.py +13 -0
  15. MemGen-main/data/kodcode/builder.py +76 -0
  16. MemGen-main/data/kodcode/env.py +36 -0
  17. MemGen-main/data/triviaqa/builder.py +139 -0
  18. MemGen-main/data/triviaqa/env.py +120 -0
  19. MemGen-main/data/utils/code_utils.py +169 -0
  20. MemGen-main/data/utils/dynamic_padding.py +78 -0
  21. MemGen-main/data/utils/math_utils.py +254 -0
  22. MemGen-main/data/utils/processor.py +39 -0
  23. MemGen-main/data/utils/retrieval_utils.py +43 -0
  24. MemGen-main/data/utils/search_utils.py +70 -0
  25. MemGen-main/interactions/base_interaction.py +67 -0
  26. MemGen-main/interactions/multiturn_interaction.py +263 -0
  27. MemGen-main/interactions/singleturn_interaction.py +144 -0
  28. MemGen-main/interactions/tensor_utils.py +85 -0
  29. MemGen-main/memgen/__init__.py +7 -0
  30. MemGen-main/memgen/model/__init__.py +1 -0
  31. MemGen-main/memgen/model/configuration_memgen.py +32 -0
  32. MemGen-main/memgen/model/modeling_memgen.py +787 -0
  33. MemGen-main/memgen/model/modeling_utils.py +430 -0
  34. MemGen-main/memgen/model/trigger.py +45 -0
  35. MemGen-main/memgen/model/weaver.py +125 -0
  36. MemGen-main/memgen/runner.py +446 -0
  37. MemGen-main/memgen/trainer/__init__.py +0 -0
  38. MemGen-main/memgen/trainer/trigger_grpo_trainer.py +390 -0
  39. MemGen-main/memgen/trainer/utils.py +52 -0
  40. MemGen-main/memgen/trainer/weaver_grpo_trainer.py +466 -0
  41. MemGen-main/memgen/utils.py +268 -0
  42. MemGen-main/scripts/eval.sh +63 -0
  43. MemGen-main/scripts/eval/qwen2_5_gsm8k_grpo.sh +51 -0
  44. MemGen-main/scripts/eval/qwen2_5_gsm8k_sft.sh +51 -0
  45. MemGen-main/scripts/eval/qwen2_5_kodcode_grpo.sh +51 -0
  46. MemGen-main/scripts/eval/qwen2_5_kodcode_sft.sh +51 -0
  47. MemGen-main/scripts/eval/qwen2_5_triviaqa.sh +51 -0
  48. MemGen-main/scripts/eval/smollm_kodcode.sh +50 -0
  49. MemGen-main/scripts/eval/smollm_triviaqa.sh +50 -0
  50. MemGen-main/scripts/train/qwen2_5_gsm8k_grpo.sh +58 -0
MemGen-main/common/config.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+
4
+ from omegaconf import OmegaConf
5
+
6
+ class Config:
7
+ def __init__(self, args):
8
+ self.config = {}
9
+
10
+ self.args = args
11
+
12
+ user_config = self._build_opt_list(self.args.options)
13
+
14
+ config = OmegaConf.load(self.args.cfg_path)
15
+ runner_config = self.build_runner_config(config, **user_config)
16
+ model_config = self.build_model_config(config, **user_config)
17
+ dataset_config = self.build_dataset_config(config, **user_config)
18
+
19
+ # Override the default configuration with user options.
20
+ self.config = OmegaConf.merge(
21
+ runner_config, model_config, dataset_config, user_config
22
+ )
23
+
24
+
25
+ def _build_opt_list(self, opts):
26
+ opts_dot_list = self._convert_to_dot_list(opts)
27
+ return OmegaConf.from_dotlist(opts_dot_list)
28
+
29
+ @staticmethod
30
+ def build_model_config(config, **kwargs):
31
+ return {"model": config.model}
32
+
33
+ @staticmethod
34
+ def build_runner_config(config, **kwargs):
35
+ return {"run": config.run}
36
+
37
+ @staticmethod
38
+ def build_dataset_config(config, **kwargs):
39
+ dataset = config.get("dataset", None)
40
+ if dataset is None:
41
+ raise KeyError(
42
+ "Expecting 'dataset' as the root key for dataset configuration."
43
+ )
44
+
45
+ return dict(dataset=dataset)
46
+
47
+ def _convert_to_dot_list(self, opts):
48
+ if opts is None:
49
+ opts = []
50
+
51
+ if len(opts) == 0:
52
+ return opts
53
+
54
+ has_equal = opts[0].find("=") != -1
55
+
56
+ if has_equal:
57
+ return opts
58
+
59
+ return [(opt + "=" + value) for opt, value in zip(opts[0::2], opts[1::2])]
60
+
61
+ def get_config(self):
62
+ return self.config
63
+
64
+ @property
65
+ def run_cfg(self):
66
+ return self.config.run
67
+
68
+ @property
69
+ def dataset_cfg(self):
70
+ return self.config.dataset
71
+
72
+ @property
73
+ def model_cfg(self):
74
+ return self.config.model
75
+
76
+ def pretty_print(self):
77
+ logging.info("\n===== Running Parameters =====")
78
+ logging.info(self._convert_node_to_json(self.config.run))
79
+
80
+ logging.info("\n====== Dataset Attributes ======")
81
+ logging.info(self._convert_node_to_json(self.config.dataset))
82
+
83
+ logging.info(f"\n====== Model Attributes ======")
84
+ logging.info(self._convert_node_to_json(self.config.model))
85
+
86
+ def _convert_node_to_json(self, node):
87
+ container = OmegaConf.to_container(node, resolve=True)
88
+ return json.dumps(container, indent=4, sort_keys=True)
89
+
90
+ def to_dict(self):
91
+ return OmegaConf.to_container(self.config)
MemGen-main/common/logger.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+
4
+ def setup_logger(output_dir):
5
+ os.makedirs(output_dir, exist_ok=True)
6
+ logging.basicConfig(
7
+ level=logging.INFO,
8
+ format="%(asctime)s [%(levelname)s] %(message)s",
9
+ handlers=[logging.StreamHandler(), logging.FileHandler(os.path.join(output_dir, 'log.txt'))],
10
+ )
MemGen-main/configs/latent_memory/gpqa.yaml ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ # base llm
3
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
4
+ load_model_path: null
5
+
6
+ # max prompt/inference augmentation num
7
+ max_prompt_aug_num: 1 # single turn
8
+ max_inference_aug_num: 5
9
+
10
+ # weaver configs
11
+ weaver:
12
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
13
+ prompt_latents_len: 8
14
+ inference_latents_len: 8
15
+
16
+ lora_config:
17
+ r: 16
18
+ lora_alpha: 32
19
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
20
+ lora_dropout: 0.1
21
+ bias: "none"
22
+ task_type: "CAUSAL_LM"
23
+
24
+ # trigger configs
25
+ trigger:
26
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
27
+ active: False
28
+
29
+ lora_config:
30
+ r: 16
31
+ lora_alpha: 32
32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
33
+ lora_dropout: 0.1
34
+ bias: "none"
35
+ task_type: "CAUSAL_LM"
36
+
37
+ # dataset configs
38
+ dataset:
39
+ name: gpqa
40
+ mode: sft # NOTE - options: ["sft", "grpo"], should manually keep align with the training method in `run` configs
41
+ sft:
42
+ valid_ratio: 0.1
43
+ grpo:
44
+ valid_ratio: 0.1
45
+
46
+ # training/evaluation configs
47
+ run:
48
+
49
+ seed: 42
50
+
51
+ # route
52
+ mode: train
53
+ train_weaver: True
54
+ train_weaver_method: sft # sft or grpo
55
+ train_trigger: False
56
+ train_trigger_method: grpo # grpo only
57
+
58
+ # processor training configs
59
+ weaver:
60
+
61
+ # sft configs
62
+ sft:
63
+ # epochs and batchsize
64
+ num_train_epochs: 2
65
+ per_device_train_batch_size: 4
66
+ per_device_eval_batch_size: 4
67
+ gradient_accumulation_steps: 1
68
+
69
+ # optimizer configs
70
+ optim: adamw_torch
71
+ lr_scheduler_type: cosine
72
+ warmup_ratio: 0.1
73
+ learning_rate: 1e-5
74
+
75
+ # duration
76
+ logging_strategy: steps
77
+ logging_steps: 1
78
+ eval_strategy: epoch
79
+ eval_steps: 100
80
+ save_strategy: epoch
81
+ save_steps: 100
82
+
83
+ assistant_only_loss: False # used only in conversational dataset
84
+ max_length: 1024 # max sequence length
85
+ remove_unused_columns: False
86
+ load_best_model_at_end: True
87
+ bf16: True
88
+ report_to:
89
+ - tensorboard
90
+
91
+ # grpo configs
92
+ grpo:
93
+ num_train_epochs: 1
94
+ per_device_train_batch_size: 8
95
+ per_device_eval_batch_size: 8
96
+ num_generations: 8
97
+ num_iterations: 1
98
+ gradient_accumulation_steps: 1
99
+ beta: 0.0
100
+ loss_type: grpo
101
+
102
+ max_prompt_length: 1024
103
+ max_completion_length: 512
104
+ temperature: 1.0
105
+
106
+ # optimizer configs
107
+ optim: adamw_torch
108
+ lr_scheduler_type: cosine
109
+ warmup_ratio: 0.1
110
+ learning_rate: 1e-5
111
+
112
+ # duration
113
+ logging_strategy: steps
114
+ logging_steps: 1
115
+ eval_strategy: epoch
116
+ eval_steps: 100
117
+ save_strategy: epoch
118
+ save_steps: 100
119
+
120
+ remove_unused_columns: False
121
+ load_best_model_at_end: True
122
+ bf16: True
123
+ report_to:
124
+ - tensorboard
125
+
126
+ # trigger training configs
127
+ trigger:
128
+
129
+ grpo:
130
+ num_train_epochs: 1
131
+ per_device_train_batch_size: 8
132
+ per_device_eval_batch_size: 8
133
+ num_generations: 8
134
+ num_iterations: 1
135
+ gradient_accumulation_steps: 1
136
+ beta: 0.0
137
+ loss_type: bnpo
138
+
139
+ max_prompt_length: 1024
140
+ max_completion_length: 512
141
+ temperature: 1.0
142
+
143
+ # optimizer configs
144
+ optim: adamw_torch
145
+ learning_rate: 1e-5
146
+ lr_scheduler_type: cosine
147
+ warmup_ratio: 0.1
148
+
149
+ # duration
150
+ logging_strategy: steps
151
+ logging_steps: 1
152
+ eval_strategy: epoch
153
+ eval_steps: 100
154
+ save_strategy: epoch
155
+ save_steps: 100
156
+
157
+ remove_unused_columns: False
158
+ load_best_model_at_end: True
159
+ bf16: True
160
+ report_to:
161
+ - tensorboard
162
+
163
+ # interaction config for evaluation
164
+ interaction:
165
+ max_turns: 1
166
+ max_start_length: 1024 # Maximum length of the initial prompt.
167
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
168
+ max_response_length: 1024
169
+ max_obs_length: 512
170
+ temperature: 1.0
171
+ batch_size: 8
172
+ weaver_do_sample: False
173
+ trigger_do_sample: False
MemGen-main/configs/latent_memory/gsm8k.yaml ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ # base llm
3
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
4
+ load_model_path: null
5
+
6
+ # max prompt/inference augmentation num
7
+ max_prompt_aug_num: 1 # single turn
8
+ max_inference_aug_num: 5
9
+
10
+ # weaver configs
11
+ weaver:
12
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
13
+ prompt_latents_len: 8
14
+ inference_latents_len: 8
15
+
16
+ lora_config:
17
+ r: 16
18
+ lora_alpha: 32
19
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
20
+ lora_dropout: 0.1
21
+ bias: "none"
22
+ task_type: "CAUSAL_LM"
23
+
24
+ # trigger configs
25
+ trigger:
26
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
27
+ active: False
28
+
29
+ lora_config:
30
+ r: 16
31
+ lora_alpha: 32
32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
33
+ lora_dropout: 0.1
34
+ bias: "none"
35
+ task_type: "CAUSAL_LM"
36
+
37
+ # dataset configs
38
+ dataset:
39
+ name: gsm8k
40
+ mode: sft # options: ["sft", "grpo"], should manually keep align with the training method in `run` configs
41
+ sft:
42
+ val_ratio: 0.1
43
+ grpo:
44
+ val_ratio: 0.1
45
+
46
+ # training/evaluation configs
47
+ run:
48
+
49
+ seed: 42
50
+
51
+ # route
52
+ mode: train
53
+ train_weaver: True
54
+ train_weaver_method: sft # sft or grpo
55
+ train_trigger: False
56
+ train_trigger_method: grpo # grpo only
57
+
58
+ # processor training configs
59
+ weaver:
60
+
61
+ # sft configs
62
+ sft:
63
+ # epochs and batchsize
64
+ num_train_epochs: 2
65
+ per_device_train_batch_size: 4
66
+ per_device_eval_batch_size: 4
67
+ gradient_accumulation_steps: 1
68
+
69
+ # optimizer configs
70
+ optim: adamw_torch
71
+ lr_scheduler_type: cosine
72
+ warmup_ratio: 0.1
73
+ learning_rate: 1e-5
74
+
75
+ # duration
76
+ logging_strategy: steps
77
+ logging_steps: 1
78
+ eval_strategy: epoch
79
+ eval_steps: 100
80
+ save_strategy: epoch
81
+ save_steps: 100
82
+
83
+ assistant_only_loss: True
84
+ max_length: 1024 # max sequence length
85
+ remove_unused_columns: False
86
+ load_best_model_at_end: True
87
+ bf16: True
88
+ report_to:
89
+ - tensorboard
90
+
91
+ # grpo configs
92
+ grpo:
93
+ num_train_epochs: 1
94
+ per_device_train_batch_size: 8
95
+ per_device_eval_batch_size: 8
96
+ num_generations: 8
97
+ num_iterations: 1
98
+ gradient_accumulation_steps: 1
99
+ beta: 0.0
100
+ loss_type: bnpo
101
+
102
+ max_prompt_length: 1024
103
+ max_completion_length: 1024
104
+ temperature: 1.0
105
+
106
+ # optimizer configs
107
+ optim: adamw_torch
108
+ lr_scheduler_type: cosine
109
+ warmup_ratio: 0.1
110
+ learning_rate: 1e-5
111
+
112
+ # duration
113
+ logging_strategy: steps
114
+ logging_steps: 1
115
+ eval_strategy: epoch
116
+ eval_steps: 100
117
+ save_strategy: epoch
118
+ save_steps: 100
119
+
120
+ remove_unused_columns: False
121
+ load_best_model_at_end: True
122
+ bf16: True
123
+ report_to:
124
+ - tensorboard
125
+
126
+ # trigger training configs
127
+ trigger:
128
+
129
+ grpo:
130
+ num_train_epochs: 1
131
+ per_device_train_batch_size: 8
132
+ per_device_eval_batch_size: 8
133
+ num_generations: 8
134
+ num_iterations: 1
135
+ gradient_accumulation_steps: 1
136
+ beta: 0.0
137
+ loss_type: bnpo
138
+
139
+ max_prompt_length: 1024
140
+ max_completion_length: 1024
141
+ temperature: 1.0
142
+
143
+ # optimizer configs
144
+ optim: adamw_torch
145
+ learning_rate: 1e-6
146
+ lr_scheduler_type: cosine
147
+ warmup_ratio: 0.1
148
+
149
+ # duration
150
+ logging_strategy: steps
151
+ logging_steps: 1
152
+ eval_strategy: epoch
153
+ eval_steps: 100
154
+ save_strategy: epoch
155
+ save_steps: 100
156
+
157
+ remove_unused_columns: False
158
+ load_best_model_at_end: True
159
+ bf16: True
160
+ report_to:
161
+ - tensorboard
162
+
163
+ # interaction config for evaluation
164
+ interaction:
165
+ max_turns: 1
166
+ max_start_length: 1024 # Maximum length of the initial prompt.
167
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
168
+ max_response_length: 1024
169
+ max_obs_length: 512
170
+ temperature: 0.0
171
+ batch_size: 8
172
+ weaver_do_sample: False
173
+ trigger_do_sample: False
MemGen-main/configs/latent_memory/kodcode.yaml ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ # base llm
3
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
4
+ load_model_path: null
5
+
6
+ # max prompt/inference augmentation num
7
+ max_prompt_aug_num: 1 # single turn
8
+ max_inference_aug_num: 5
9
+
10
+ # weaver configs
11
+ weaver:
12
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
13
+ prompt_latents_len: 8
14
+ inference_latents_len: 8
15
+
16
+ lora_config:
17
+ r: 16
18
+ lora_alpha: 32
19
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
20
+ lora_dropout: 0.1
21
+ bias: "none"
22
+ task_type: "CAUSAL_LM"
23
+
24
+ # trigger configs
25
+ trigger:
26
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
27
+ active: False
28
+
29
+ lora_config:
30
+ r: 16
31
+ lora_alpha: 32
32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
33
+ lora_dropout: 0.1
34
+ bias: "none"
35
+ task_type: "CAUSAL_LM"
36
+
37
+ dataset:
38
+ name: kodcode
39
+ mode: sft
40
+ sft:
41
+ train_ratio: 0.7
42
+ valid_ratio: 0.1
43
+ test_ratio: 0.2
44
+ grpo:
45
+ train_ratio: 0.7
46
+ valid_ratio: 0.1
47
+ test_ratio: 0.2
48
+
49
+ # training/evaluation configs
50
+ run:
51
+
52
+ seed: 42
53
+
54
+ # route
55
+ mode: train
56
+ train_weaver: True
57
+ train_weaver_method: sft # sft or grpo
58
+ train_trigger: False
59
+ train_trigger_method: grpo # grpo only
60
+
61
+ # processor training configs
62
+ weaver:
63
+
64
+ # sft configs
65
+ sft:
66
+ # epochs and batchsize
67
+ num_train_epochs: 2
68
+ per_device_train_batch_size: 4
69
+ per_device_eval_batch_size: 4
70
+ gradient_accumulation_steps: 1
71
+
72
+ # optimizer configs
73
+ optim: adamw_torch
74
+ lr_scheduler_type: cosine
75
+ warmup_ratio: 0.1
76
+ learning_rate: 1e-5
77
+
78
+ # duration
79
+ logging_strategy: steps
80
+ logging_steps: 1
81
+ eval_strategy: epoch
82
+ eval_steps: 100
83
+ save_strategy: epoch
84
+ save_steps: 100
85
+
86
+ assistant_only_loss: False # used only in conversational dataset
87
+ max_length: 1024 # max sequence length
88
+ remove_unused_columns: False
89
+ load_best_model_at_end: True
90
+ bf16: True
91
+ report_to:
92
+ - tensorboard
93
+
94
+ # grpo configs
95
+ grpo:
96
+ num_train_epochs: 1
97
+ per_device_train_batch_size: 8
98
+ per_device_eval_batch_size: 8
99
+ num_generations: 8
100
+ num_iterations: 1
101
+ gradient_accumulation_steps: 1
102
+ beta: 0.0
103
+ loss_type: bnpo
104
+
105
+ max_prompt_length: 1024
106
+ max_completion_length: 512
107
+ temperature: 1.0
108
+
109
+ # optimizer configs
110
+ optim: adamw_torch
111
+ lr_scheduler_type: cosine
112
+ warmup_ratio: 0.1
113
+ learning_rate: 1e-5
114
+
115
+ # duration
116
+ logging_strategy: steps
117
+ logging_steps: 1
118
+ eval_strategy: epoch
119
+ eval_steps: 100
120
+ save_strategy: epoch
121
+ save_steps: 100
122
+
123
+ remove_unused_columns: False
124
+ load_best_model_at_end: True
125
+ bf16: True
126
+ report_to:
127
+ - tensorboard
128
+
129
+ # trigger training configs
130
+ trigger:
131
+
132
+ grpo:
133
+ num_train_epochs: 1
134
+ per_device_train_batch_size: 8
135
+ per_device_eval_batch_size: 8
136
+ num_generations: 8
137
+ num_iterations: 1
138
+ gradient_accumulation_steps: 1
139
+ beta: 0.0
140
+ loss_type: bnpo
141
+
142
+ max_prompt_length: 1024
143
+ max_completion_length: 512
144
+ temperature: 1.0
145
+
146
+ # optimizer configs
147
+ optim: adamw_torch
148
+ learning_rate: 1e-5
149
+ lr_scheduler_type: cosine
150
+ warmup_ratio: 0.1
151
+
152
+ # duration
153
+ logging_strategy: steps
154
+ logging_steps: 1
155
+ eval_strategy: epoch
156
+ eval_steps: 100
157
+ save_strategy: epoch
158
+ save_steps: 100
159
+
160
+ remove_unused_columns: False
161
+ load_best_model_at_end: True
162
+ bf16: True
163
+ report_to:
164
+ - tensorboard
165
+
166
+ # interaction config for evaluation
167
+ interaction:
168
+ max_turns: 1
169
+ max_start_length: 1024 # Maximum length of the initial prompt.
170
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
171
+ max_response_length: 1024
172
+ max_obs_length: 512
173
+ temperature: 0.0
174
+ batch_size: 8
175
+ weaver_do_sample: False
176
+ trigger_do_sample: False
MemGen-main/configs/latent_memory/triviaqa.yaml ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ # base llm
3
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
4
+ load_model_path: null
5
+
6
+ # max prompt/inference augmentation num
7
+ max_prompt_aug_num: 8 # single turn
8
+ max_inference_aug_num: 0
9
+
10
+ # weaver configs
11
+ weaver:
12
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
13
+ prompt_latents_len: 8
14
+ inference_latents_len: 8
15
+
16
+ lora_config:
17
+ r: 16
18
+ lora_alpha: 32
19
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
20
+ lora_dropout: 0.1
21
+ bias: "none"
22
+ task_type: "CAUSAL_LM"
23
+
24
+ # trigger configs
25
+ trigger:
26
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
27
+ active: False
28
+
29
+ lora_config:
30
+ r: 16
31
+ lora_alpha: 32
32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
33
+ lora_dropout: 0.1
34
+ bias: "none"
35
+ task_type: "CAUSAL_LM"
36
+
37
+ dataset:
38
+ name: triviaqa
39
+ mode: sft
40
+ sft:
41
+ valid_ratio: 0.1
42
+ grpo:
43
+ valid_ratio: 0.1
44
+
45
+
46
+ # training/evaluation configs
47
+ run:
48
+
49
+ seed: 42
50
+
51
+ # route
52
+ mode: train
53
+ train_weaver: True
54
+ train_weaver_method: sft # sft or grpo
55
+ train_trigger: False
56
+ train_trigger_method: grpo # grpo only
57
+
58
+ # processor training configs
59
+ weaver:
60
+
61
+ # sft configs
62
+ sft:
63
+ # epochs and batchsize
64
+ num_train_epochs: 2
65
+ per_device_train_batch_size: 4
66
+ per_device_eval_batch_size: 4
67
+ gradient_accumulation_steps: 1
68
+
69
+ # optimizer configs
70
+ optim: adamw_torch
71
+ lr_scheduler_type: cosine
72
+ warmup_ratio: 0.1
73
+ learning_rate: 1e-5
74
+
75
+ # duration
76
+ logging_strategy: steps
77
+ logging_steps: 1
78
+ eval_strategy: epoch
79
+ eval_steps: 100
80
+ save_strategy: epoch
81
+ save_steps: 100
82
+
83
+ assistant_only_loss: True # used only in conversational dataset
84
+ max_length: 1024 # max sequence length
85
+ remove_unused_columns: False
86
+ load_best_model_at_end: True
87
+ bf16: True
88
+ report_to:
89
+ - tensorboard
90
+
91
+ # grpo configs
92
+ grpo:
93
+ num_train_epochs: 1
94
+ per_device_train_batch_size: 8
95
+ per_device_eval_batch_size: 8
96
+ num_generations: 8
97
+ num_iterations: 1
98
+ gradient_accumulation_steps: 1
99
+ beta: 0.0
100
+ loss_type: grpo
101
+
102
+ max_prompt_length: 1024
103
+ max_completion_length: 512
104
+ temperature: 1.0
105
+
106
+ # optimizer configs
107
+ optim: adamw_torch
108
+ lr_scheduler_type: cosine
109
+ warmup_ratio: 0.1
110
+ learning_rate: 1e-5
111
+
112
+ # duration
113
+ logging_strategy: steps
114
+ logging_steps: 1
115
+ eval_strategy: epoch
116
+ eval_steps: 100
117
+ save_strategy: epoch
118
+ save_steps: 100
119
+
120
+ remove_unused_columns: False
121
+ load_best_model_at_end: True
122
+ bf16: True
123
+ report_to:
124
+ - tensorboard
125
+
126
+ # trigger training configs
127
+ trigger:
128
+
129
+ grpo:
130
+ num_train_epochs: 1
131
+ per_device_train_batch_size: 8
132
+ per_device_eval_batch_size: 8
133
+ num_generations: 8
134
+ num_iterations: 1
135
+ gradient_accumulation_steps: 1
136
+ beta: 0.0
137
+ loss_type: bnpo
138
+
139
+ max_prompt_length: 1024
140
+ max_completion_length: 512
141
+ temperature: 1.0
142
+
143
+ # optimizer configs
144
+ optim: adamw_torch
145
+ learning_rate: 1e-5
146
+ lr_scheduler_type: cosine
147
+ warmup_ratio: 0.1
148
+
149
+ # duration
150
+ logging_strategy: steps
151
+ logging_steps: 1
152
+ eval_strategy: epoch
153
+ eval_steps: 100
154
+ save_strategy: epoch
155
+ save_steps: 100
156
+
157
+ remove_unused_columns: False
158
+ load_best_model_at_end: True
159
+ bf16: True
160
+ report_to:
161
+ - tensorboard
162
+
163
+ interaction:
164
+ max_turns: 5
165
+ max_start_length: 1024 # Maximum length of the initial prompt.
166
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
167
+ max_response_length: 1024
168
+ max_obs_length: 512
169
+ temperature: 0.0
170
+ batch_size: 8
171
+ weaver_do_sample: False
172
+ trigger_do_sample: False
MemGen-main/configs/zero2.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ deepspeed_multinode_launcher: standard
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: false
8
+ zero_stage: 2
9
+ distributed_type: DEEPSPEED
10
+ downcast_bf16: 'no'
11
+ machine_rank: 0
12
+ main_training_function: main
13
+ mixed_precision: 'no'
14
+ num_machines: 1
15
+ num_processes: 1 # 会被脚本自动覆盖,无需手动修改
16
+ main_process_port: 44326
17
+ rdzv_backend: static
18
+ same_network: true
19
+ tpu_env: []
20
+ tpu_use_cluster: false
21
+ tpu_use_sudo: false
22
+ use_cpu: false
MemGen-main/data/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from data.base_builder import BaseBuilder
2
+ from data.base_env import (
3
+ BaseEnv,
4
+ StaticEnv,
5
+ DynamicEnv,
6
+ )
7
+ from data.gpqa.builder import GPQABuilder
8
+ from data.gsm8k.builder import GSM8KBuilder
9
+ from data.kodcode.builder import KodCodeBuilder
10
+ from data.triviaqa.builder import TriviaQABuilder
11
+
12
+ _DATA_BUILDER_MAP = {
13
+ "gpqa": GPQABuilder,
14
+ "gsm8k": GSM8KBuilder,
15
+ "kodcode": KodCodeBuilder,
16
+ "triviaqa": TriviaQABuilder
17
+ }
18
+
19
+ def get_data_builder(dataset_cfg) -> BaseBuilder:
20
+ if dataset_cfg.get("name") not in _DATA_BUILDER_MAP:
21
+ raise ValueError("Unsupported dataset.")
22
+
23
+ builder_cls = _DATA_BUILDER_MAP[dataset_cfg.get("name")]
24
+ builder = builder_cls(dataset_cfg)
25
+
26
+ return builder
MemGen-main/data/base_builder.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Type
3
+
4
+ from datasets import DatasetDict
5
+
6
+ from data.base_env import BaseEnv
7
+
8
+ class BaseBuilder(ABC):
9
+
10
+ def __init__(self, cfg: dict = None):
11
+ super().__init__()
12
+
13
+ self.mode = cfg.get("mode", "sft")
14
+ self.config = cfg.get(self.mode)
15
+
16
+ def get_dataset_dict(self) -> DatasetDict:
17
+ method_builder_map = {
18
+ "sft": self._build_sft_datasets,
19
+ "grpo": self._build_rl_datasets,
20
+ }
21
+
22
+ if self.mode not in method_builder_map:
23
+ raise ValueError("Unsupported datasets mode")
24
+
25
+ return method_builder_map[self.mode]()
26
+
27
+ @abstractmethod
28
+ def get_env_cls(self) -> Type[BaseEnv]:
29
+ ...
30
+
31
+ @abstractmethod
32
+ def _build_sft_datasets(self) -> DatasetDict:
33
+ ...
34
+
35
+ @abstractmethod
36
+ def _build_rl_datasets(self) -> DatasetDict:
37
+ ...
38
+
MemGen-main/data/base_env.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Literal, Dict, Tuple
3
+
4
+ class BaseEnv(ABC):
5
+ ENV_CARD: Literal["STATIC", "DYNAMIC"] = None
6
+
7
+ def __init__(self, config):
8
+ self.config = config
9
+
10
+ @classmethod
11
+ @abstractmethod
12
+ def compute_reward(cls, **kwargs):
13
+ ...
14
+
15
+
16
+ class StaticEnv(BaseEnv):
17
+ ENV_CARD = "STATIC"
18
+
19
+
20
+ class DynamicEnv(BaseEnv):
21
+ ENV_CARD = "DYNAMIC"
22
+
23
+ @abstractmethod
24
+ def set_env(self, task_config: Dict) -> Tuple[str, str]:
25
+ ...
26
+
27
+ @classmethod
28
+ @abstractmethod
29
+ def preprocess_action(self, action: str) -> str:
30
+ ...
31
+
32
+ @abstractmethod
33
+ def step(self, action: str) -> Tuple[str, bool]:
34
+ ...
35
+
36
+ @abstractmethod
37
+ def feedback(self) -> Tuple[float, bool]:
38
+ ...
MemGen-main/data/gpqa/builder.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from datasets import DatasetDict, load_dataset
3
+
4
+ from data.base_builder import BaseBuilder
5
+ from data.gpqa.env import GPQAEnv
6
+
7
+ class GPQABuilder(BaseBuilder):
8
+
9
+ def get_env_cls(self):
10
+ return GPQAEnv
11
+
12
+ def _build_datasets(self) -> DatasetDict:
13
+ # download data
14
+ raw_train_dataset = load_dataset("Idavidrein/gpqa", "gpqa_main")["train"]
15
+ raw_test_dataset = load_dataset("Idavidrein/gpqa", "gpqa_diamond")["train"]
16
+ val_size = int(len(raw_train_dataset) * self.config.get("valid_ratio"))
17
+ split = raw_train_dataset.train_test_split(test_size=val_size, shuffle=True)
18
+ raw_train_dataset, raw_valid_dataset = split["train"], split["test"]
19
+
20
+ # preprocess
21
+ train_dataset = raw_train_dataset.map(self._preprocess).select_columns(self._keep_keys())
22
+ valid_dataset = raw_valid_dataset.map(self._preprocess).select_columns(self._keep_keys())
23
+ test_dataset = raw_test_dataset.map(self._preprocess).select_columns(self._keep_keys())
24
+
25
+ # build dataset
26
+ dataset_dict = DatasetDict()
27
+ dataset_dict["train"] = train_dataset
28
+ dataset_dict["valid"] = valid_dataset
29
+ dataset_dict["test"] = test_dataset
30
+
31
+ return dataset_dict
32
+
33
+ def _build_sft_datasets(self) -> DatasetDict:
34
+ return self._build_datasets()
35
+
36
+
37
+ def _build_rl_datasets(self) -> DatasetDict:
38
+ return self._build_datasets()
39
+
40
+ @classmethod
41
+ def _preprocess(cls, example: dict):
42
+
43
+ def build_answer_map(candidates: list[str]) -> dict[str, dict[str, object]]:
44
+
45
+ indices = list(range(len(candidates)))
46
+ random.shuffle(indices)
47
+
48
+ orders = [chr(ord("A") + i) for i in range(len(candidates))]
49
+
50
+ answer_map = {}
51
+ for idx, candidate_idx in enumerate(indices):
52
+ answer = candidates[candidate_idx]
53
+ answer_map[answer] = {
54
+ "order": orders[idx],
55
+ "is_correct": (candidate_idx == 0)
56
+ }
57
+
58
+ return answer_map
59
+
60
+ def build_question(question, answer_map: dict) -> str:
61
+ result = question.strip() + "\n\nPlease choose one of the following options:\n"
62
+
63
+ sorted_items = sorted(answer_map.items(), key=lambda x: x[1]["order"])
64
+
65
+ for answer, meta in sorted_items:
66
+ result += f"{meta['order']}. {answer}\n"
67
+
68
+ return result
69
+
70
+ def build_answer(rationale: str, answer_map: dict) -> str:
71
+ correct_answer = None
72
+ for key, value in answer_map.items():
73
+ if value.get("is_correct") is True:
74
+ correct_answer = value.get("order")
75
+ assert correct_answer is not None
76
+ return rationale + f"\n\nTherefore, the final answer is \\boxed{{{correct_answer}}}"
77
+
78
+ question = example["Question"].strip()
79
+ explanation = example["Explanation"].strip()
80
+ correct_answer = example["Correct Answer"].strip()
81
+ incorrect_answer1 = example["Incorrect Answer 1"].strip()
82
+ incorrect_answer2 = example["Incorrect Answer 2"].strip()
83
+ incorrect_answer3 = example["Incorrect Answer 3"].strip()
84
+
85
+ answers_map = build_answer_map([correct_answer, incorrect_answer1, incorrect_answer2, incorrect_answer3])
86
+ question = build_question(question, answers_map)
87
+ answer = build_answer(explanation, answers_map)
88
+
89
+ format_template = r"""Solve the problem with proper reasoning, and make sure to put the FINAL CHOICE inside \boxed{}."""
90
+ prompt_template = "Question: {prompt}\n"
91
+ processed_prompt = format_template + prompt_template.format(prompt=question)
92
+
93
+ text_output = {
94
+ "prompt": processed_prompt,
95
+ "completion": answer,
96
+ "solution": answer
97
+ }
98
+ return text_output
99
+
100
+ @classmethod
101
+ def _keep_keys(cls):
102
+ return ["prompt", "completion", "solution"]
MemGen-main/data/gpqa/env.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from data.utils.math_utils import compute_score
2
+ from data.base_env import StaticEnv
3
+
4
+ class GPQAEnv(StaticEnv):
5
+
6
+ def __init__(self, config):
7
+ super().__init__(config)
8
+
9
+ @classmethod
10
+ def compute_reward(cls, completions: list[str], solution: list[str], **kwargs) -> list[float]:
11
+
12
+ scores = [compute_score(completion=c, ground_truth=s) for c, s in zip(completions, solution)]
13
+ return scores
14
+
MemGen-main/data/gsm8k/builder.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import DatasetDict, load_dataset
2
+ from typing import Dict
3
+
4
+ from data.base_builder import BaseBuilder
5
+ from data.gsm8k.env import GSM8KEnv
6
+
7
+ class GSM8KBuilder(BaseBuilder): # Env
8
+
9
+ def get_env_cls(self):
10
+ return GSM8KEnv
11
+
12
+ def _build_datasets(self) -> DatasetDict:
13
+
14
+ # download data
15
+ raw_dataset = load_dataset("gsm8k", "main")
16
+ raw_train_dataset, raw_test_dataset = raw_dataset['train'], raw_dataset['test']
17
+ val_size = int(len(raw_train_dataset) * self.config.get("val_ratio"))
18
+ split = raw_train_dataset.train_test_split(test_size=val_size, shuffle=True)
19
+ raw_train_dataset, raw_valid_dataset = split["train"], split["test"]
20
+
21
+ # preprocess
22
+ num_workers = 32
23
+ train_dataset = raw_train_dataset.map(self._preprocess, num_proc=num_workers).select_columns(self._keep_keys())
24
+ valid_dataset = raw_valid_dataset.map(self._preprocess, num_proc=num_workers).select_columns(self._keep_keys())
25
+ test_dataset = raw_test_dataset.map(self._preprocess, num_proc=num_workers).select_columns(self._keep_keys())
26
+
27
+ # build dataset
28
+ dataset_dict = DatasetDict()
29
+ dataset_dict["train"] = train_dataset
30
+ dataset_dict["valid"] = valid_dataset
31
+ dataset_dict["test"] = test_dataset
32
+
33
+ return dataset_dict
34
+
35
+ def _build_sft_datasets(self) -> DatasetDict:
36
+ return self._build_datasets()
37
+
38
+
39
+ def _build_rl_datasets(self) -> DatasetDict:
40
+ return self._build_datasets()
41
+
42
+ @classmethod
43
+ def _preprocess(cls, example: Dict):
44
+ def _preprocess_answer(answer: str) -> str:
45
+ raw_answer_list = answer.split("\n####")
46
+ rationale = raw_answer_list[0]
47
+ clean_answer = raw_answer_list[-1].strip()
48
+ boxed_answer = "\\boxed{" + clean_answer + "}"
49
+ new_string = rationale + boxed_answer
50
+ return new_string.strip()
51
+
52
+ format_template = r"""Solve the math problem with proper reasoning, and make sure to put the FINAL ANSWER inside \boxed{}."""
53
+ prompt_template = "Question: {prompt}\n"
54
+
55
+ question = example["question"].strip()
56
+ answer = example["answer"].strip()
57
+
58
+ processed_prompt = format_template + prompt_template.format(prompt=question)
59
+ processed_label = _preprocess_answer(answer)
60
+
61
+ text_output = {
62
+ "prompt": [{"role": "user", "content": processed_prompt}],
63
+ "completion": [{"role": "assistant", "content": processed_label}],
64
+ "solution": processed_label,
65
+ "test": processed_label,
66
+ }
67
+
68
+ # NOTE - To use the built-in tokenization mechanism of SFTTrainer,
69
+ # it is necessary to ensure that the prompt + completion is lossless.
70
+ return text_output
71
+
72
+ @classmethod
73
+ def _keep_keys(cls):
74
+ return ["prompt", "completion", "solution"]
MemGen-main/data/gsm8k/env.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from data.utils.math_utils import compute_score
2
+ from data.base_env import StaticEnv
3
+
4
+ class GSM8KEnv(StaticEnv):
5
+
6
+ def __init__(self, config):
7
+ super().__init__(config)
8
+
9
+ @classmethod
10
+ def compute_reward(cls, completions: list[str], solution: list[str], **kwargs) -> list[float]:
11
+
12
+ scores = [compute_score(completion=c, ground_truth=s) for c, s in zip(completions, solution)]
13
+ return scores
MemGen-main/data/kodcode/builder.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import DatasetDict, load_dataset
2
+ from typing import Dict
3
+
4
+ from data.base_builder import BaseBuilder
5
+ from data.kodcode.env import KodCodeEnv
6
+
7
+ class KodCodeBuilder(BaseBuilder):
8
+
9
+ def get_env_cls(self):
10
+ return KodCodeEnv
11
+
12
+ def _build_datasets(self) -> DatasetDict:
13
+ # download dataset
14
+ all_dataset = load_dataset("KodCode/KodCode-Light-RL-10K")
15
+ all_correct_dataset = all_dataset["train"]
16
+
17
+ # train, valid, test dataset split
18
+ train_ratio, valid_ratio, test_ratio = self.config.get("train_ratio"), self.config.get("valid_ratio"), self.config.get("test_ratio")
19
+ assert train_ratio + valid_ratio + test_ratio == 1
20
+
21
+ all_size = len(all_correct_dataset)
22
+ test_size = int(all_size * test_ratio)
23
+ split = all_correct_dataset.train_test_split(test_size=test_size, shuffle=True)
24
+ train_valid_dataset, test_dataset = split["train"], split["test"]
25
+
26
+ valid_size = int(len(train_valid_dataset) * valid_ratio / (train_ratio + valid_ratio))
27
+ split = train_valid_dataset.train_test_split(test_size=valid_size, shuffle=True)
28
+ train_dataset, valid_dataset = split["train"], split["test"]
29
+
30
+ # preprocess
31
+ train_dataset = train_dataset.map(self._sft_preprocess).select_columns(self._sft_keep_keys())
32
+ valid_dataset = valid_dataset.map(self._sft_preprocess).select_columns(self._sft_keep_keys())
33
+ test_dataset = test_dataset.map(self._sft_preprocess).select_columns(self._sft_keep_keys())
34
+
35
+ # build dataset dict
36
+ dataset_dict = DatasetDict()
37
+ dataset_dict["train"] = train_dataset
38
+ dataset_dict["valid"] = valid_dataset
39
+ dataset_dict["test"] = test_dataset
40
+
41
+ return dataset_dict
42
+
43
+ def _build_sft_datasets(self) -> DatasetDict:
44
+ return self._build_datasets()
45
+
46
+
47
+ def _build_rl_datasets(self) -> DatasetDict:
48
+ return self._build_datasets()
49
+
50
+ @classmethod
51
+ def _sft_preprocess(cls, example: Dict):
52
+
53
+ format_template = r"Write an efficient and correct Python function to solve the following problem."
54
+ prompt_template = "Question: {prompt}\n"
55
+
56
+ question = example["question"].strip()
57
+ solution = example["solution"].strip()
58
+
59
+ processed_prompt = format_template + prompt_template.format(prompt=question)
60
+ processed_label = solution
61
+
62
+ text_output = {
63
+ "prompt": [{"role": "user", "content": processed_prompt}],
64
+ "completion": [{"role": "assistant", "content": processed_label}],
65
+ "solution": processed_label,
66
+ "test": example["test"].strip(),
67
+ "test_info": example["test_info"]
68
+ }
69
+
70
+ return text_output
71
+
72
+ @classmethod
73
+ def _sft_keep_keys(cls):
74
+ return ["prompt", "completion", "solution", "test", "test_info"]
75
+
76
+
MemGen-main/data/kodcode/env.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from data.base_env import StaticEnv
4
+ from data.utils.code_utils import PyExecutor, extract_python_code
5
+
6
+ class KodCodeEnv(StaticEnv):
7
+
8
+ def __init__(self, config):
9
+ super().__init__(config)
10
+
11
+ @classmethod
12
+ def _rename_func(cls, answer: str, function_name: str) -> str:
13
+ """
14
+ Replace the name of the first function in `answer` with `function_name`.
15
+ Only modifies the function name, keeps everything else intact.
16
+ """
17
+ pattern = r"def\s+(\w+)\s*\("
18
+
19
+ new_answer = re.sub(pattern, f"def {function_name}(", answer, count=1)
20
+ return new_answer
21
+
22
+ @classmethod
23
+ def compute_reward(cls, completions: list[str], test: list[str], test_info: list, **kwargs) -> list[float]:
24
+
25
+ py_executor = PyExecutor()
26
+ scores = []
27
+ for completion, t, tf in zip(completions, test, test_info):
28
+ func_blocks = extract_python_code(completion.strip())
29
+ collected_answer = '\n'.join(func_blocks)
30
+ renamed_answer = cls._rename_func(collected_answer, tf[0]["function_name"])
31
+ _, _, results = py_executor.execute(renamed_answer, [t])
32
+
33
+ score = sum(results) / len(results)
34
+ scores.append(score)
35
+
36
+ return scores
MemGen-main/data/triviaqa/builder.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import DatasetDict, load_dataset
2
+ from typing import Dict, List
3
+ import re
4
+ import copy
5
+
6
+ from data.base_builder import BaseBuilder
7
+ from data.triviaqa.env import TriviaQAEnv
8
+
9
+
10
+ TRIVIAQA_SYSTEM_PROMPT = """Answer the given question. \
11
+ You must conduct reasoning inside <think> and </think> first every time you get new information. \
12
+ After reasoning, if you find you lack some knowledge, you can call a search engine by <search> query </search> and it will return the top searched results between <information> and </information>. \
13
+ You can search as many times as your want. \
14
+ If you find no further external knowledge needed, you can directly provide the answer inside <answer> and </answer>, without detailed illustrations. For example, <answer> Beijing </answer>. \
15
+ """
16
+
17
+ class TriviaQABuilder(BaseBuilder): # Env
18
+
19
+ def get_env_cls(self):
20
+ return TriviaQAEnv
21
+
22
+ def _build_sft_datasets(self) -> DatasetDict:
23
+
24
+ # build train/valid dataset from agentbank
25
+ train_ds = load_dataset("Solaris99/AgentBank", "triviaqa")["train"]
26
+
27
+ valid_ratio = self.config.get("valid_ratio")
28
+ all_size = len(train_ds)
29
+ valid_size = int(all_size * valid_ratio)
30
+ split = train_ds.train_test_split(test_size=valid_size, shuffle=True)
31
+ raw_train_dataset, raw_valid_dataset = split["train"], split["test"]
32
+
33
+ # build test dataset from triviaqa
34
+ ds = load_dataset("mandarjoshi/trivia_qa", "rc.wikipedia.nocontext")
35
+ raw_test_dataset = ds["validation"]
36
+
37
+ # preprocess
38
+ num_workers = 32
39
+ train_dataset = raw_train_dataset.map(self._sft_preprocess, num_proc=num_workers).select_columns(self._sft_keep_keys())
40
+ valid_dataset = raw_valid_dataset.map(self._sft_preprocess, num_proc=num_workers).select_columns(self._sft_keep_keys())
41
+ test_dataset = raw_test_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
42
+
43
+ dataset_dict = DatasetDict()
44
+ dataset_dict["train"] = train_dataset
45
+ dataset_dict["valid"] = valid_dataset
46
+ dataset_dict["test"] = test_dataset
47
+
48
+ return dataset_dict
49
+
50
+ def _build_rl_datasets(self) -> DatasetDict:
51
+
52
+ ds = load_dataset("mandarjoshi/trivia_qa", "rc.wikipedia.nocontext")
53
+ raw_train_dataset = ds["train"]
54
+ raw_valid_dataset = ds["validation"]
55
+ raw_test_dataset = ds["test"]
56
+
57
+ num_workers = 32
58
+ train_dataset = raw_train_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
59
+ valid_dataset = raw_valid_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
60
+ test_dataset = raw_test_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
61
+
62
+ dataset_dict = DatasetDict()
63
+ dataset_dict["train"] = train_dataset
64
+ dataset_dict["valid"] = valid_dataset
65
+ dataset_dict["test"] = test_dataset
66
+
67
+ return dataset_dict
68
+
69
+ @classmethod
70
+ def _sft_preprocess(cls, example: Dict):
71
+
72
+ def _add_user_special_tokens(content: str) -> str:
73
+ observation_match = re.search(r'Observation: (.*)', content)
74
+
75
+ if observation_match:
76
+ observation_content = f"<observation> {observation_match.group(1).strip()} </observation>"
77
+ else:
78
+ observation_content = content
79
+
80
+ return observation_content
81
+
82
+ def _add_assistant_special_tokens(content: str) -> str:
83
+ thought_match = re.search(r'Thought: (.*?)(?=\nAction:|\nFinal Answer:|$)', content, re.DOTALL)
84
+ action_match = re.search(r'Action: search\[(.*?)\]', content)
85
+ answer_match = re.search(r'Final Answer: (.*)', content)
86
+
87
+ parts = []
88
+
89
+ if thought_match:
90
+ thought_content = thought_match.group(1).strip()
91
+ parts.append(f"<think> {thought_content} </think>")
92
+
93
+ if action_match:
94
+ action_content = action_match.group(1).strip()
95
+ parts.append(f"<search> {action_content} </search>")
96
+
97
+ if answer_match:
98
+ answer_content = answer_match.group(1).strip()
99
+ parts.append(f"<answer> {answer_content} </answer>")
100
+
101
+ aggregated_content = "\n".join(parts)
102
+ return aggregated_content
103
+
104
+ messages = []
105
+ system_prompt = {"role": "system", "content": TRIVIAQA_SYSTEM_PROMPT.strip()}
106
+ messages.append(system_prompt)
107
+
108
+ for sample in example["conversations"]:
109
+ message = {}
110
+ # role
111
+ if sample["from"] == "human":
112
+ message["role"] = "user"
113
+ message["content"] = _add_user_special_tokens(sample["value"])
114
+ elif sample["from"] == "gpt":
115
+ message["role"] = "assistant"
116
+ message["content"] = _add_assistant_special_tokens(sample["value"])
117
+ else:
118
+ raise ValueError("Unsupported Role type.")
119
+
120
+ messages.append(message)
121
+
122
+ return {
123
+ "messages": messages
124
+ }
125
+
126
+ @classmethod
127
+ def _sft_keep_keys(cls) -> List[str]:
128
+ return ["messages"]
129
+
130
+ @classmethod
131
+ def _rl_preprocess(cls, example: Dict) -> Dict:
132
+ output = copy.deepcopy(example)
133
+ output["answer"] = output["answer"]["normalized_aliases"]
134
+ output["prompt"] = output["question"]
135
+ return output
136
+
137
+ @classmethod
138
+ def _rl_keep_keys(cls) -> List[str]:
139
+ return ["prompt", "answer"]
MemGen-main/data/triviaqa/env.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Tuple
2
+ import re
3
+
4
+ from data.base_env import DynamicEnv
5
+ from data.utils.retrieval_utils import Retriever
6
+
7
+ class TriviaQAEnv(DynamicEnv):
8
+
9
+ def __init__(self, configs: Dict):
10
+ super().__init__(configs)
11
+ self.explorer = Retriever()
12
+
13
+ def set_env(self, task_config: Dict) -> None:
14
+ if task_config.get('answer') is None:
15
+ raise ValueError('Please provide the answer for the task')
16
+ if task_config.get("prompt") is None:
17
+ raise ValueError('Please provide the prompt for the task')
18
+
19
+ self.task_config = task_config
20
+
21
+ self._reset()
22
+
23
+ from data.triviaqa.builder import TRIVIAQA_SYSTEM_PROMPT
24
+ return TRIVIAQA_SYSTEM_PROMPT, task_config["prompt"]
25
+
26
+ def _reset(self):
27
+ self.done = False
28
+ self.reward = 0.0
29
+
30
+ def step(self, action: str) -> Tuple[str, float, bool]:
31
+ action = self.preprocess_action(action)
32
+ action_type, action_content = self._process_action(action)
33
+ observation = None
34
+
35
+ if action_type == "search":
36
+ try:
37
+ observation = self.explorer.batch_search([action_content])[0]
38
+ except Exception as e:
39
+ observation = f'Cannot find corresponding pages.'
40
+ self.done = False
41
+ self.reward = 0.0
42
+
43
+ elif action_type == "answer":
44
+ observation = ""
45
+ self.done = True
46
+ self.reward = 1.0 if self._check_answer(action_content, self.task_config["answer"]) else 0.0
47
+ else:
48
+ observation = "\nMy previous action is invalid. \
49
+ If I want to search, I should put the query between <search> and </search>. \
50
+ If I want to give the final answer, I should put the answer between <answer> and </answer>. Let me try again.\n"
51
+ self.done = False
52
+ self.reward = 0.0
53
+
54
+ return observation, self.reward, self.done
55
+
56
+ @classmethod
57
+ def preprocess_action(cls, action: str) -> str:
58
+ if "</search>" in action:
59
+ return action.split("</search>", 1)[0] + "</search>"
60
+ elif "</answer>" in action:
61
+ return action.split("</answer>", 1)[0] + "</answer>"
62
+ else:
63
+ return action
64
+
65
+ @classmethod
66
+ def _process_action(cls, action: str):
67
+ action = action.strip()
68
+
69
+ if "<search>" in action and "</search>" in action:
70
+ start = action.index("<search>") + len("<search>")
71
+ end = action.index("</search>")
72
+ content = action[start:end].strip().split("\n", 1)[0].strip()
73
+ return "search", content
74
+
75
+ if "<answer>" in action and "</answer>" in action:
76
+ start = action.index("<answer>") + len("<answer>")
77
+ end = action.index("</answer>")
78
+ content = action[start:end].strip().split("\n", 1)[0].strip()
79
+ return "answer", content
80
+
81
+ return "think", action
82
+
83
+ def _check_answer(self, answer: str, ground_truth: List[str]):
84
+ answer = answer.lower()
85
+ for gt in ground_truth:
86
+ if gt.lower() in answer:
87
+ return True
88
+
89
+ return False
90
+
91
+ def feedback(self) -> float:
92
+ return self.reward
93
+
94
+ @classmethod
95
+ def compute_reward(cls, completions: List[str], envs: List['TriviaQAEnv'], **kwargs) -> List[float]:
96
+ scores = []
97
+ for completion, env in zip(completions, envs):
98
+ solution = env.task_config['answer']
99
+
100
+ matches = re.findall(r"<answer>(.*?)</answer>", completion, re.DOTALL)
101
+
102
+ if not matches:
103
+ scores.append(0.0)
104
+ continue
105
+
106
+ extracted = matches[-1].strip()
107
+
108
+ correct = False
109
+ for s in solution:
110
+ if s.lower() in extracted.lower():
111
+ correct = True
112
+ break
113
+
114
+ if correct:
115
+ scores.append(1.0)
116
+ else:
117
+ scores.append(0.5)
118
+
119
+ return scores
120
+
MemGen-main/data/utils/code_utils.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ from typing import List, Tuple, Any, Optional
5
+ import re
6
+ import multiprocessing
7
+ from multiprocessing.connection import Connection
8
+
9
+ ExecuteResult = Tuple[bool, str, Tuple[bool]]
10
+
11
+
12
+ def extract_python_code(text_string: str) -> List[str]:
13
+ code_blocks = re.findall(r"```python(.*?)```", text_string, re.DOTALL)
14
+ if not code_blocks:
15
+ code_blocks = [text_string]
16
+
17
+ results = []
18
+ for block in code_blocks:
19
+ imports = re.findall(r"^(?:from\s+\S+\s+import\s+\S+|import\s+\S+.*)$", block, re.MULTILINE)
20
+
21
+ funcs = re.findall(r"(def\s+\w+\(.*?:[\s\S]*?)(?=^def\s|\Z)", block.strip(), re.MULTILINE)
22
+
23
+ if imports:
24
+ import_block = "\n".join(imports)
25
+ if funcs:
26
+ funcs = [import_block] + funcs
27
+ else:
28
+ funcs = [import_block]
29
+
30
+ results.extend(funcs)
31
+
32
+ return results
33
+
34
+ def rename_function(function: str, function_name: str) -> str:
35
+ """
36
+ Replace the name of the first function in `answer` with `function_name`.
37
+ Only modifies the function name, keeps everything else intact.
38
+ """
39
+ pattern = r"def\s+(\w+)\s*\("
40
+
41
+ new_answer = re.sub(pattern, f"def {function_name}(", function, count=1)
42
+ return new_answer
43
+
44
+
45
+ def _exec_code_and_capture(code: str, conn: Connection, work_dir: Optional[str] = None):
46
+ try:
47
+ if work_dir is not None:
48
+ os.makedirs(work_dir, exist_ok=True)
49
+ os.chdir(work_dir)
50
+
51
+ local_ns = {}
52
+ exec(code, local_ns)
53
+
54
+ for name, func in local_ns.items():
55
+ if callable(func) and name.startswith("test_"):
56
+ func()
57
+ conn.send(True)
58
+ except Exception as e:
59
+ conn.send(e)
60
+ finally:
61
+ conn.close()
62
+
63
+
64
+ class PyExecutor:
65
+
66
+ def _run_with_timeout(self, code: str, timeout: int, work_dir: Optional[str] = "./code_stuff") -> Any:
67
+ parent_conn, child_conn = multiprocessing.Pipe()
68
+ p = multiprocessing.Process(
69
+ target=_exec_code_and_capture,
70
+ args=(code, child_conn, work_dir)
71
+ )
72
+
73
+ p.start()
74
+ p.join(timeout)
75
+
76
+ if p.is_alive():
77
+ p.kill()
78
+ p.join()
79
+ raise TimeoutError("Test execution timed out")
80
+
81
+ if parent_conn.poll():
82
+ result = parent_conn.recv()
83
+ if isinstance(result, Exception):
84
+ raise result
85
+ return result
86
+ else:
87
+ raise RuntimeError("Child process terminated unexpectedly without sending a result.")
88
+
89
+ def execute(self, func: str, tests: List[str], timeout: int = 5, verbose: bool = True) -> ExecuteResult:
90
+ success_tests = []
91
+ failed_tests = []
92
+ is_passing = True
93
+
94
+ for test_code in tests:
95
+ cleaned_test = re.sub(r"^\s*from\s+solution\s+import\s+\w+\s*", "", test_code, flags=re.MULTILINE)
96
+ code_to_run = func + "\n" + cleaned_test
97
+ try:
98
+ self._run_with_timeout(code_to_run, timeout)
99
+ success_tests.append(test_code)
100
+ except Exception as e:
101
+ failed_tests.append(f"{test_code} # output: {e}")
102
+ is_passing = False
103
+
104
+ state = tuple(test in success_tests for test in tests)
105
+ feedback = (
106
+ "Tests passed:\n" + "\n".join(success_tests)
107
+ + "\n\nTests failed:\n" + "\n".join(failed_tests)
108
+ )
109
+ return is_passing, feedback, state
110
+
111
+ def evaluate(self, name: str, func: str, test: str, timeout: int = 5) -> bool:
112
+ cleaned_test = re.sub(r"^\s*from\s+solution\s+import\s+\w+\s*", "", test, flags=re.MULTILINE)
113
+ code_to_run = func + "\n" + cleaned_test
114
+ try:
115
+ self._run_with_timeout(code_to_run, timeout)
116
+ return True
117
+ except Exception:
118
+ return False
119
+
120
+ def check_code_report(self, completions: list[str], tests: list[str], timeout: int = 5) -> tuple[list[str], list[float]]:
121
+ def extract_failed_tests(text: str) -> str:
122
+ match = re.search(r"Tests failed:\s*(.*)", text, re.DOTALL)
123
+ return match.group(1).strip() if match else ""
124
+
125
+ def extract_correct_function_name(text: str) -> str:
126
+ match = re.search(r"from\s+solution\s+import\s+([a-zA-Z_]\w*)", text)
127
+ return match.group(1) if match else ""
128
+
129
+ reports = []
130
+ avg_scores = []
131
+
132
+ for completion, test_code_str in zip(completions, tests):
133
+ func_blocks = extract_python_code(completion.strip())
134
+ collected_answer = '\n'.join(func_blocks)
135
+
136
+ correct_function_name = extract_correct_function_name(test_code_str)
137
+ if correct_function_name != "":
138
+ collected_answer = rename_function(collected_answer, correct_function_name)
139
+
140
+ test_block = extract_python_code(test_code_str.strip())
141
+ test_list = [test_block[0] + "\n\n" + block for block in test_block[1:]]
142
+
143
+ report_lines = []
144
+ success_examples = 0
145
+
146
+ for test in test_list:
147
+ func_name_match = re.search(r"def\s+(test_\w+)\s*\(", test)
148
+ func_name = func_name_match.group(1) if func_name_match else "unknown_test"
149
+
150
+ is_passing, feedback, _ = self.execute(collected_answer, [test], timeout=timeout)
151
+
152
+ if is_passing:
153
+ success_examples += 1
154
+ report_lines.append(f"✅ Test passed for '{func_name}'")
155
+ else:
156
+ report_lines.append(f"❌ Test failed for '{func_name}': \n{extract_failed_tests(feedback)}")
157
+
158
+ if len(test_list) != 0:
159
+ avg_score = success_examples / len(test_list)
160
+ else:
161
+ avg_score = 1.0
162
+ avg_scores.append(avg_score)
163
+ report_lines.append(f"\nAverage correctness: {avg_score:.2f}")
164
+
165
+ reports.append("\n".join(report_lines))
166
+
167
+ return reports, avg_scores
168
+
169
+
MemGen-main/data/utils/dynamic_padding.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import PreTrainedTokenizerBase
3
+ from typing import Dict, List, Any
4
+
5
+ class DynamicPaddingDataCollater:
6
+ def __init__(self, tokenizer: PreTrainedTokenizerBase):
7
+
8
+ self.tokenizer = tokenizer
9
+
10
+ if tokenizer.pad_token_id is None:
11
+ print("Warning: Tokenizer does not have a pad_token_id. Using 0 for input_ids and attention_mask padding.")
12
+ self.padding_value_input = 0
13
+ else:
14
+ self.padding_value_input = tokenizer.pad_token_id
15
+
16
+ # labels 的填充值
17
+ self.padding_value_label = tokenizer.pad_token_id
18
+
19
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]:
20
+
21
+ processed_features = []
22
+ for feature in features:
23
+ input_ids = feature["input_ids"]
24
+ completion_mask = feature["completion_mask"]
25
+
26
+ prompt_ids = [token for token, is_completion in zip(input_ids, completion_mask) if not is_completion]
27
+
28
+ label_ids = [token for token, is_completion in zip(input_ids, completion_mask) if is_completion]
29
+
30
+ processed_features.append({
31
+ "prompt_ids": prompt_ids,
32
+ "label_ids": label_ids,
33
+
34
+ "original": feature
35
+ })
36
+
37
+ max_prompt_len = max(len(f["prompt_ids"]) for f in processed_features)
38
+ max_label_len = max(len(f["label_ids"]) for f in processed_features)
39
+
40
+ padded_prompt_ids = []
41
+ padded_input_attention_mask = []
42
+ padded_label_ids = []
43
+ padded_labels_attention_mask = []
44
+
45
+ for feature in processed_features:
46
+
47
+ prompt_ids = feature["prompt_ids"]
48
+ label_ids = feature["label_ids"]
49
+
50
+
51
+ num_input_pads = max_prompt_len - len(prompt_ids)
52
+ padded_prompt_ids.append([self.padding_value_input] * num_input_pads + prompt_ids)
53
+
54
+ input_attention_mask = [1] * len(prompt_ids)
55
+ num_input_mask_pads = max_prompt_len - len(input_attention_mask)
56
+ padded_input_attention_mask.append([0] * num_input_mask_pads + input_attention_mask)
57
+
58
+ num_label_pads = max_label_len - len(label_ids)
59
+ padded_label_ids.append(label_ids + [self.padding_value_label] * num_label_pads)
60
+
61
+ labels_attention_mask = [1] * len(label_ids)
62
+ num_label_mask_pads = max_label_len - len(labels_attention_mask)
63
+ padded_labels_attention_mask.append(labels_attention_mask + [0] * num_label_mask_pads)
64
+
65
+ batch = {
66
+ "prompt_ids": torch.tensor(padded_prompt_ids, dtype=torch.long),
67
+ "prompt_attention_mask": torch.tensor(padded_input_attention_mask, dtype=torch.long),
68
+ "label_ids": torch.tensor(padded_label_ids, dtype=torch.long),
69
+ "label_attention_mask": torch.tensor(padded_labels_attention_mask, dtype=torch.long),
70
+ }
71
+
72
+ batch["raw_samples"] = [f["original"] for f in processed_features]
73
+
74
+ return batch
75
+
76
+
77
+
78
+
MemGen-main/data/utils/math_utils.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # Adapted from https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/hendrycks_math/utils.py
15
+
16
+
17
+ def compute_score(completion, ground_truth) -> float:
18
+ retval = 0.0
19
+ try:
20
+ # string_in_last_boxed = last_boxed_only_string(solution_str)
21
+ string_in_first_boxed = first_boxed_only_string(completion)
22
+ ground_truth_in_last_boxed = last_boxed_only_string(ground_truth)
23
+ if string_in_first_boxed is not None:
24
+ answer = remove_boxed(string_in_first_boxed)
25
+ ground_truth = remove_boxed(ground_truth_in_last_boxed)
26
+ if is_equiv(answer, ground_truth):
27
+ retval = 1.0
28
+ except Exception as e:
29
+ print(e)
30
+
31
+ return retval
32
+
33
+
34
+ # string normalization from https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_math.py
35
+ def is_equiv(str1, str2, verbose=False):
36
+ if str1 is None and str2 is None:
37
+ print("WARNING: Both None")
38
+ return True
39
+ if str1 is None or str2 is None:
40
+ return False
41
+
42
+ try:
43
+ ss1 = strip_string(str1)
44
+ ss2 = strip_string(str2)
45
+ if verbose:
46
+ print(ss1, ss2)
47
+ return ss1 == ss2
48
+ except Exception:
49
+ return str1 == str2
50
+
51
+
52
+ def remove_boxed(s):
53
+ if "\\boxed " in s:
54
+ left = "\\boxed "
55
+ assert s[: len(left)] == left
56
+ return s[len(left) :]
57
+
58
+ left = "\\boxed{"
59
+
60
+ assert s[: len(left)] == left
61
+ assert s[-1] == "}"
62
+
63
+ return s[len(left) : -1]
64
+
65
+ def first_boxed_only_string(string):
66
+ if "\\boxed " in string:
67
+ return "\\boxed " + string.split("\\boxed ")[1].split("$")[0]
68
+
69
+ idx = string.find("\\boxed")
70
+ if idx < 0:
71
+ idx = string.find("\\fbox")
72
+ if idx < 0:
73
+ return None
74
+
75
+ i = idx
76
+ right_brace_idx = None
77
+ num_left_braces_open = 0
78
+ while i < len(string):
79
+ if string[i] == "{":
80
+ num_left_braces_open += 1
81
+ if string[i] == "}":
82
+ num_left_braces_open -= 1
83
+ if num_left_braces_open == 0:
84
+ right_brace_idx = i
85
+ break
86
+ i += 1
87
+
88
+ retval = None if right_brace_idx is None else string[idx : right_brace_idx + 1]
89
+
90
+ return retval
91
+
92
+
93
+ def last_boxed_only_string(string):
94
+ idx = string.rfind("\\boxed")
95
+ if "\\boxed " in string:
96
+ return "\\boxed " + string.split("\\boxed ")[-1].split("$")[0]
97
+ if idx < 0:
98
+ idx = string.rfind("\\fbox")
99
+ if idx < 0:
100
+ return None
101
+
102
+ i = idx
103
+ right_brace_idx = None
104
+ num_left_braces_open = 0
105
+ while i < len(string):
106
+ if string[i] == "{":
107
+ num_left_braces_open += 1
108
+ if string[i] == "}":
109
+ num_left_braces_open -= 1
110
+ if num_left_braces_open == 0:
111
+ right_brace_idx = i
112
+ break
113
+ i += 1
114
+
115
+ retval = None if right_brace_idx is None else string[idx : right_brace_idx + 1]
116
+
117
+ return retval
118
+
119
+
120
+ def fix_fracs(string):
121
+ substrs = string.split("\\frac")
122
+ new_str = substrs[0]
123
+ if len(substrs) > 1:
124
+ substrs = substrs[1:]
125
+ for substr in substrs:
126
+ new_str += "\\frac"
127
+ if substr[0] == "{":
128
+ new_str += substr
129
+ else:
130
+ try:
131
+ assert len(substr) >= 2
132
+ except: # noqa: E722
133
+ return string
134
+ a = substr[0]
135
+ b = substr[1]
136
+ if b != "{":
137
+ if len(substr) > 2:
138
+ post_substr = substr[2:]
139
+ new_str += "{" + a + "}{" + b + "}" + post_substr
140
+ else:
141
+ new_str += "{" + a + "}{" + b + "}"
142
+ else:
143
+ if len(substr) > 2:
144
+ post_substr = substr[2:]
145
+ new_str += "{" + a + "}" + b + post_substr
146
+ else:
147
+ new_str += "{" + a + "}" + b
148
+ string = new_str
149
+ return string
150
+
151
+
152
+ def fix_a_slash_b(string):
153
+ if len(string.split("/")) != 2:
154
+ return string
155
+ a = string.split("/")[0]
156
+ b = string.split("/")[1]
157
+ try:
158
+ a = int(a)
159
+ b = int(b)
160
+ assert string == "{}/{}".format(a, b)
161
+ new_string = "\\frac{" + str(a) + "}{" + str(b) + "}"
162
+ return new_string
163
+ except: # noqa: E722
164
+ return string
165
+
166
+
167
+ def remove_right_units(string):
168
+ # "\\text{ " only ever occurs (at least in the val set) when describing units
169
+ if "\\text{ " in string:
170
+ splits = string.split("\\text{ ")
171
+ assert len(splits) == 2
172
+ return splits[0]
173
+ else:
174
+ return string
175
+
176
+
177
+ def fix_sqrt(string):
178
+ if "\\sqrt" not in string:
179
+ return string
180
+ splits = string.split("\\sqrt")
181
+ new_string = splits[0]
182
+ for split in splits[1:]:
183
+ if split[0] != "{":
184
+ a = split[0]
185
+ new_substr = "\\sqrt{" + a + "}" + split[1:]
186
+ else:
187
+ new_substr = "\\sqrt" + split
188
+ new_string += new_substr
189
+ return new_string
190
+
191
+
192
+ def strip_string(string):
193
+ # linebreaks
194
+ string = string.replace("\n", "")
195
+
196
+ # remove inverse spaces
197
+ string = string.replace("\\!", "")
198
+
199
+ # replace \\ with \
200
+ string = string.replace("\\\\", "\\")
201
+
202
+ # replace tfrac and dfrac with frac
203
+ string = string.replace("tfrac", "frac")
204
+ string = string.replace("dfrac", "frac")
205
+
206
+ # remove \left and \right
207
+ string = string.replace("\\left", "")
208
+ string = string.replace("\\right", "")
209
+
210
+ # Remove circ (degrees)
211
+ string = string.replace("^{\\circ}", "")
212
+ string = string.replace("^\\circ", "")
213
+
214
+ # remove dollar signs
215
+ string = string.replace("\\$", "")
216
+
217
+ # remove units (on the right)
218
+ string = remove_right_units(string)
219
+
220
+ # remove percentage
221
+ string = string.replace("\\%", "")
222
+ string = string.replace("\%", "") # noqa: W605
223
+
224
+ # " 0." equivalent to " ." and "{0." equivalent to "{." Alternatively, add "0" if "." is the start of the string
225
+ string = string.replace(" .", " 0.")
226
+ string = string.replace("{.", "{0.")
227
+ # if empty, return empty string
228
+ if len(string) == 0:
229
+ return string
230
+ if string[0] == ".":
231
+ string = "0" + string
232
+
233
+ # to consider: get rid of e.g. "k = " or "q = " at beginning
234
+ if len(string.split("=")) == 2 and len(string.split("=")[0]) <= 2:
235
+ string = string.split("=")[1]
236
+
237
+ # fix sqrt3 --> sqrt{3}
238
+ string = fix_sqrt(string)
239
+
240
+ # remove spaces
241
+ string = string.replace(" ", "")
242
+
243
+ # \frac1b or \frac12 --> \frac{1}{b} and \frac{1}{2}, etc. Even works with \frac1{72} (but not \frac{72}1).
244
+ # Also does a/b --> \\frac{a}{b}
245
+ string = fix_fracs(string)
246
+
247
+ # manually change 0.5 --> \frac{1}{2}
248
+ if string == "0.5":
249
+ string = "\\frac{1}{2}"
250
+
251
+ # NOTE: X/Y changed to \frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y
252
+ string = fix_a_slash_b(string)
253
+
254
+ return string
MemGen-main/data/utils/processor.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+
3
+ def add_eos(example, eos_token):
4
+ """在 labels 部分末尾添加 eos token
5
+ """
6
+ if "text" in example and not example["text"].endswith(eos_token):
7
+ example["text"] = example["text"] + eos_token
8
+ elif "completion" in example and not example["completion"].endswith(eos_token):
9
+ example["completion"] = example["completion"] + eos_token
10
+ return example
11
+
12
+ def tokenize(example, processing_class) -> Dict:
13
+
14
+ output = dict(example)
15
+ prompt_ids = processing_class(
16
+ text=example["prompt"], add_special_tokens=False
17
+ )["input_ids"]
18
+ completion_ids = processing_class(
19
+ text=example["completion"], add_special_tokens=False
20
+ )["input_ids"]
21
+ input_ids = prompt_ids + completion_ids
22
+
23
+ # Create a completion mask
24
+ completion_mask = [0] * len(prompt_ids) + [1] * len(completion_ids)
25
+ output["input_ids"] = input_ids
26
+ output["completion_mask"] = completion_mask
27
+
28
+ return output
29
+
30
+ def tokenize_instruction_example(example: Dict, processing_class) -> Dict:
31
+ eos_token = processing_class.eos_token
32
+ eos_example = add_eos(example, eos_token)
33
+ tokenized_example = tokenize(eos_example, processing_class)
34
+
35
+ return tokenized_example
36
+
37
+
38
+ def tokenize_conversation_example(example: Dict, processing_class) -> Dict:
39
+ ...
MemGen-main/data/utils/retrieval_utils.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import requests
3
+
4
+ class Retriever:
5
+
6
+ def __init__(self):
7
+ self.config = {
8
+ "search_url": "http://127.0.0.1:8001/retrieve",
9
+ "topk": 3
10
+ }
11
+
12
+ def batch_search(self, queries: List[str] = None) -> List[str]:
13
+ """
14
+ Batchified search for queries.
15
+ Args:
16
+ queries: queries to call the search engine
17
+ Returns:
18
+ search results which is concatenated into a string
19
+ """
20
+ results = self._batch_search(queries)['result']
21
+
22
+ return [self._passages2string(result) for result in results]
23
+
24
+ def _batch_search(self, queries):
25
+
26
+ payload = {
27
+ "queries": queries,
28
+ "topk": self.config["topk"],
29
+ "return_scores": True
30
+ }
31
+
32
+ return requests.post(self.config["search_url"], json=payload).json()
33
+
34
+ def _passages2string(self, retrieval_result):
35
+ format_reference = ''
36
+ for idx, doc_item in enumerate(retrieval_result):
37
+
38
+ content = doc_item['document']['contents']
39
+ title = content.split("\n")[0]
40
+ text = "\n".join(content.split("\n")[1:])
41
+ format_reference += f"Doc {idx+1}(Title: {title}) {text}\n"
42
+
43
+ return format_reference
MemGen-main/data/utils/search_utils.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+ from langchain.docstore.document import Document
3
+ import wikipedia
4
+
5
+ class LangChainWiki:
6
+
7
+ def __init__(self) -> None:
8
+ self.document: Optional[Document] = None
9
+ self.lookup_str = ""
10
+ self.lookup_index = 0
11
+
12
+ def search(self, search: str) -> Union[str, Document]:
13
+ def _try_search(term: str) -> Union[str, Document]:
14
+ try:
15
+ page_content = wikipedia.page(search).content
16
+ url = wikipedia.page(search).url
17
+ result: Union[str, Document] = Document( page_content=page_content, metadata={"page": url} )
18
+ return result
19
+ except wikipedia.PageError:
20
+ return f"Could not find [{term}]. Similar: {wikipedia.search(term)}"
21
+ except wikipedia.DisambiguationError:
22
+ return f"Could not find [{term}]. Similar: {wikipedia.search(term)}"
23
+ except Exception:
24
+ return f"Could not find [{term}]. Similar: {wikipedia.search(term)}"
25
+
26
+ result = _try_search(search)
27
+
28
+ if isinstance(result, str) and "Similar:" in result:
29
+ try:
30
+ similar = wikipedia.search(search)
31
+ if similar:
32
+ fallback = similar[0]
33
+ print(f"[INFO] Falling back to similar term: {fallback}")
34
+ result = _try_search(fallback)
35
+ except Exception as e:
36
+ print(f"[ERROR] Could not fetch similar terms: {e}")
37
+
38
+ if isinstance(result, Document):
39
+ self.document = result
40
+ return self._sumary
41
+ else:
42
+ self.document = None
43
+ return result
44
+
45
+ def lookup(self, term: str):
46
+ if self.document is None:
47
+ raise ValueError("Cannot lookup without a successful search first")
48
+ if term.lower() != self.lookup_str:
49
+ self.lookup_str = term.lower()
50
+ self.lookup_index = 0
51
+ else:
52
+ self.lookup_index += 1
53
+ lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()]
54
+ if len(lookups) == 0:
55
+ return "No Results"
56
+ elif self.lookup_index >= len(lookups):
57
+ return "No More Results"
58
+ else:
59
+ result_prefix = f"(Result {self.lookup_index + 1}/{len(lookups)})"
60
+ return f"{result_prefix} {lookups[self.lookup_index]}"
61
+
62
+ @property
63
+ def _sumary(self) -> str:
64
+ return self._paragraphs[0]
65
+
66
+ @property
67
+ def _paragraphs(self) -> list[str]:
68
+ if self.document is None:
69
+ raise ValueError("Cannot get paragraphs without a document")
70
+ return self.document.page_content.split("\n\n")
MemGen-main/interactions/base_interaction.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import dataclass, field
3
+ import logging
4
+ from typing import Optional
5
+
6
+ from transformers import GenerationConfig
7
+
8
+ from interactions.tensor_utils import TensorHelper, TensorConfig
9
+
10
+
11
+ @dataclass
12
+ class InteractionConfig:
13
+ max_turns: int = 1
14
+ max_start_length: int = 1024
15
+ max_prompt_length: int = 4096
16
+ max_response_length: int = 512
17
+ max_obs_length: int = 512
18
+ # do_sample: bool = False
19
+ temperature: float = 1.0
20
+ batch_size: int = 8
21
+ output_dir: Optional[str] = None
22
+ weaver_do_sample: bool = False
23
+ trigger_do_sample: bool = False
24
+
25
+ @dataclass
26
+ class InteractionDataProto:
27
+ batch: dict = field(default_factory=dict)
28
+ no_tensor_batch: dict = field(default_factory=dict)
29
+
30
+ class InteractionManager(ABC):
31
+
32
+ def __init__(
33
+ self,
34
+ tokenizer,
35
+ actor_rollout_wg,
36
+ config: InteractionConfig,
37
+ is_validation: bool = False,
38
+ ):
39
+ self.tokenizer = tokenizer
40
+ self.tokenizer.padding_side = "left"
41
+ self.actor_rollout_wg = actor_rollout_wg
42
+ self.config = config
43
+ self.is_validation = is_validation
44
+
45
+ assert tokenizer.pad_token_id is not None
46
+ self.tensor_fn = TensorHelper(TensorConfig(
47
+ pad_token_id=tokenizer.pad_token_id,
48
+ max_prompt_length=config.max_prompt_length,
49
+ max_obs_length=config.max_obs_length,
50
+ max_start_length=config.max_start_length
51
+ ))
52
+
53
+ # generation configs for agent
54
+ self.generation_config = GenerationConfig(
55
+ max_new_tokens=self.config.max_response_length,
56
+ temperature=self.config.temperature,
57
+ pad_token_id=self.tokenizer.pad_token_id,
58
+ eos_token_id=self.tokenizer.eos_token_id
59
+ )
60
+ self.generation_config.weaver_do_sample = self.config.weaver_do_sample
61
+ self.generation_config.trigger_do_sample = self.config.trigger_do_sample
62
+
63
+ logging.info(f"Weaver do sample: {self.generation_config.weaver_do_sample}, Trigger do sample: {self.generation_config.trigger_do_sample}")
64
+
65
+ @abstractmethod
66
+ def run_agent_loop(self, gen_batch: InteractionDataProto) -> InteractionDataProto:
67
+ ...
MemGen-main/interactions/multiturn_interaction.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Dict, List, Tuple
3
+ import copy
4
+
5
+ from interactions.base_interaction import (
6
+ InteractionDataProto,
7
+ InteractionConfig,
8
+ InteractionManager
9
+ )
10
+
11
+
12
+ class MultiTurnInteractionManager(InteractionManager):
13
+ def __init__(
14
+ self,
15
+ tokenizer,
16
+ actor_rollout_wg,
17
+ config: InteractionConfig,
18
+ is_validation: bool = False,
19
+ ):
20
+ super().__init__(
21
+ tokenizer, actor_rollout_wg, config, is_validation
22
+ )
23
+
24
+ def _batch_tokenize(self, responses: List[str]) -> torch.Tensor:
25
+ """Tokenize a batch of responses."""
26
+ return self.tokenizer(
27
+ responses,
28
+ add_special_tokens=False,
29
+ return_tensors='pt',
30
+ padding="longest"
31
+ )['input_ids']
32
+
33
+ def _build_chat_history(self, rollings: Dict) -> List[Dict]:
34
+
35
+ init_prompts = rollings.get("init_prompts")
36
+ if init_prompts is None:
37
+ raise ValueError("")
38
+
39
+ inter_histories = rollings.get("inter_histories")
40
+ if inter_histories is None:
41
+ raise ValueError("")
42
+
43
+ chat_histories: List[List[Dict]] = []
44
+ for init_prompt, inter_history in zip(init_prompts, inter_histories):
45
+ chat_histories.append(init_prompt + inter_history)
46
+
47
+ return chat_histories
48
+
49
+ def _update_interaction_history(self, rollings: InteractionDataProto, responses: List[str], observations: List[str]) -> List[List[Dict]]:
50
+
51
+ inter_histories = copy.deepcopy(rollings.no_tensor_batch.get("inter_histories"))
52
+ assert len(inter_histories) == len(responses) == len(observations)
53
+ for inter_history, response, observation in zip(inter_histories, responses, observations):
54
+ assistant_info = {"role": "assistant", "content": response}
55
+ user_info = {"role": "user", "content": observation}
56
+
57
+ inter_history.append(assistant_info)
58
+ inter_history.append(user_info)
59
+
60
+ return inter_histories
61
+
62
+ def _postprocess_responses(self, responses: torch.Tensor, envs: List) -> torch.Tensor:
63
+
64
+ responses_str = self.tokenizer.batch_decode(
65
+ responses,
66
+ skip_special_tokens=True
67
+ )
68
+
69
+ processed_responses_str = []
70
+ for r, env in zip(responses_str, envs):
71
+ processed_r = env.preprocess_action(r)
72
+ processed_responses_str.append(processed_r)
73
+
74
+ responses = self._batch_tokenize(processed_responses_str)
75
+ return responses, processed_responses_str
76
+
77
+
78
+ def _example_level_pad(
79
+ self, responses_ids: torch.Tensor, responses_str: List[str], active_mask: torch.Tensor
80
+ ) -> Tuple[torch.Tensor, List[str]]:
81
+
82
+ assert active_mask.sum() == responses_ids.shape[0]
83
+ # Create masked responses tensor
84
+ batch_size = active_mask.shape[0]
85
+ seq_len = responses_ids.shape[1]
86
+ padded_responses = torch.full(
87
+ (batch_size, seq_len), self.tokenizer.pad_token_id,
88
+ dtype=responses_ids.dtype, device=responses_ids.device
89
+ )
90
+ padded_responses[active_mask] = responses_ids
91
+
92
+ # Create masked response strings
93
+ padded_responses_str = [""] * batch_size
94
+
95
+ s = 0
96
+ for i, is_active in enumerate(active_mask):
97
+ if is_active:
98
+ padded_responses_str[i] = responses_str[s]
99
+ s += 1
100
+
101
+ return padded_responses, padded_responses_str
102
+
103
+ def run_agent_loop(self, gen_batch: InteractionDataProto) -> InteractionDataProto:
104
+ """Run main LLM generation loop (conversation format)."""
105
+ assert "init_prompts" in gen_batch.no_tensor_batch
106
+ assert "envs" in gen_batch.no_tensor_batch
107
+ batch_size = len(gen_batch.no_tensor_batch["init_prompts"])
108
+
109
+ rollings = gen_batch
110
+ rollings.no_tensor_batch["inter_histories"] = [[] for _ in range(batch_size)]
111
+
112
+ active_mask = torch.ones(batch_size, dtype=torch.bool)
113
+ active_num_list = [active_mask.sum().item()]
114
+
115
+ for step in range(self.config.max_turns):
116
+ if not active_mask.sum():
117
+ break
118
+
119
+ mask_list = active_mask.tolist()
120
+ rollings_active = {
121
+ k: [item for item, keep in zip(v, mask_list) if keep]
122
+ for k, v in rollings.no_tensor_batch.items()
123
+ }
124
+ # use tokenizer to add chat template and encode text to tokens: input_ids, attention_mask
125
+ messages = self._build_chat_history(rollings_active)
126
+ self.tokenizer.padding_side = "left"
127
+ inputs = self.tokenizer.apply_chat_template(
128
+ messages, tokenize=True,
129
+ add_generation_prompt=True,
130
+ padding=True, return_tensors="pt", return_dict=True
131
+ )
132
+
133
+ # agent rollout
134
+ gen_output = self.actor_rollout_wg.generate(
135
+ input_ids=inputs["input_ids"],
136
+ attention_mask=inputs["attention_mask"],
137
+ generation_config=self.generation_config,
138
+ ).to("cpu")
139
+
140
+ # postprocess
141
+ prompt_len = inputs["input_ids"].size(1)
142
+ responses = gen_output[:, prompt_len:]
143
+ responses = self.tensor_fn.erase_after_first_eos(responses, self.tokenizer.eos_token_id)
144
+ responses_ids, responses_str = self._postprocess_responses(responses, rollings_active["envs"])
145
+ all_responses_ids, all_responses_str = self._example_level_pad(responses_ids, responses_str, active_mask)
146
+
147
+ next_obs, dones = self._execute_predictions(rollings, all_responses_str, active_mask)
148
+ processed_obs = self._postprocess_observations(next_obs)
149
+
150
+ # post process interaction states
151
+ curr_active_mask = torch.tensor([not done for done in dones], dtype=torch.bool)
152
+ active_mask = active_mask * curr_active_mask
153
+ active_num_list.append(active_mask.sum().item())
154
+
155
+ interaction_histories = self._update_interaction_history(rollings, all_responses_str, processed_obs)
156
+ rollings.no_tensor_batch["inter_histories"] = interaction_histories
157
+
158
+ # build final outputs
159
+ final_outputs = self._build_final_outputs(rollings)
160
+ return final_outputs
161
+
162
+ def _execute_predictions(self, rollings: InteractionDataProto, responses: List[str], active_mask: torch.Tensor) -> Tuple[List[str], List[str]]:
163
+ observations = []
164
+ dones = []
165
+ for response, env, is_active in zip(responses, rollings.no_tensor_batch["envs"], active_mask):
166
+ if is_active:
167
+ observation, _, done = env.step(response)
168
+ else:
169
+ observation = ""
170
+ done = True
171
+ observations.append(observation)
172
+ dones.append(done)
173
+
174
+ return observations, dones
175
+
176
+
177
+ def _postprocess_observations(self, observations: List[str]) -> List[str]:
178
+ self.tokenizer.padding_side = "right"
179
+ next_obs_ids = self._batch_tokenize(observations)
180
+
181
+ max_len = self.config.max_obs_length
182
+ if next_obs_ids.shape[1] > max_len:
183
+ extra_text = "..."
184
+ extra_ids = self.tokenizer.encode(
185
+ extra_text, add_special_tokens=False, return_tensors="pt"
186
+ ).to(next_obs_ids.device)
187
+ extra_len = extra_ids.shape[1]
188
+
189
+ new_obs_ids = []
190
+ for row in next_obs_ids:
191
+ valid_len = (row != self.tokenizer.pad_token_id).sum().item()
192
+
193
+ if valid_len > max_len:
194
+ truncated = row[: max_len - extra_len]
195
+ new_row = torch.cat([truncated, extra_ids.squeeze(0)], dim=0)
196
+ else:
197
+ new_row = row[:max_len]
198
+
199
+ new_obs_ids.append(new_row.unsqueeze(0))
200
+
201
+ next_obs_ids = torch.cat(new_obs_ids, dim=0)
202
+ observations = self.tokenizer.batch_decode(next_obs_ids, skip_special_tokens=True)
203
+
204
+ return observations
205
+
206
+ def _build_final_outputs(self, rollings: InteractionDataProto) -> InteractionDataProto:
207
+
208
+ init_prompts: List[List[Dict]] = rollings.no_tensor_batch["init_prompts"]
209
+ inter_histories: List[List[Dict]] = rollings.no_tensor_batch["inter_histories"]
210
+
211
+ output = InteractionDataProto()
212
+
213
+ output.no_tensor_batch["inter_histories"] = [
214
+ prompt + inter for prompt, inter in zip(init_prompts, inter_histories)
215
+ ]
216
+
217
+ # ---------- prompts ----------
218
+ self.tokenizer.padding_side = "left"
219
+ prompt_ids = self.tokenizer.apply_chat_template(
220
+ init_prompts, tokenize=True,
221
+ add_generation_prompt=False,
222
+ padding=True, return_tensors="pt", return_dict=True
223
+ )
224
+ output.batch["prompts"] = prompt_ids["input_ids"]
225
+ prompt_attn_mask = prompt_ids["attention_mask"]
226
+
227
+ # ---------- responses ----------
228
+ self.tokenizer.padding_side = "right"
229
+ response_ids = self.tokenizer.apply_chat_template(
230
+ inter_histories,
231
+ tokenize=True,
232
+ padding=True,
233
+ return_assistant_tokens_mask=True,
234
+ add_generation_prompt=False,
235
+ return_tensors="pt", return_dict=True
236
+ )
237
+ output.batch["responses"] = response_ids["input_ids"]
238
+ response_attn_mask = response_ids["attention_mask"]
239
+
240
+ completion_info_mask = response_ids["assistant_masks"]
241
+
242
+ # ---------- input_ids ----------
243
+ output.batch["input_ids"] = torch.cat(
244
+ [prompt_ids["input_ids"], response_ids["input_ids"]], dim=1
245
+ )
246
+ output.batch["attention_mask"] = torch.cat(
247
+ [prompt_attn_mask, response_attn_mask], dim=1
248
+ )
249
+
250
+ # ---------- info_mask ----------
251
+ prompt_info_mask = torch.zeros(
252
+ prompt_ids["input_ids"].shape,
253
+ dtype=completion_info_mask.dtype,
254
+ device=completion_info_mask.device
255
+ )
256
+
257
+ output.batch["info_mask"] = torch.cat(
258
+ [prompt_info_mask, completion_info_mask], dim=1
259
+ )
260
+
261
+ self.tokenizer.padding_side = "left"
262
+
263
+ return output
MemGen-main/interactions/singleturn_interaction.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Dict, List
3
+
4
+ from interactions.base_interaction import (
5
+ InteractionConfig,
6
+ InteractionManager,
7
+ InteractionDataProto
8
+ )
9
+
10
+
11
+ class SingleTurnInteractionManager(InteractionManager):
12
+ def __init__(
13
+ self,
14
+ tokenizer,
15
+ actor_rollout_wg,
16
+ config: InteractionConfig,
17
+ is_validation: bool = False,
18
+ ):
19
+ super().__init__(
20
+ tokenizer, actor_rollout_wg, config, is_validation
21
+ )
22
+
23
+ def _batch_tokenize(self, responses: List[str]) -> torch.Tensor:
24
+ """Tokenize a batch of responses."""
25
+ return self.tokenizer(
26
+ responses,
27
+ add_special_tokens=False,
28
+ return_tensors='pt',
29
+ padding="longest"
30
+ )['input_ids']
31
+
32
+ def _info_masked_concatenate_with_padding(self,
33
+ prompt: torch.Tensor,
34
+ prompt_with_mask: torch.Tensor,
35
+ response: torch.Tensor,
36
+ info: torch.Tensor = None,
37
+ pad_to_left: bool = True
38
+ ) -> torch.Tensor:
39
+ """Concatenate tensors and handle padding. Additionally, create a mask (info_mask) to cover the information block if it exists."""
40
+ pad_id = self.tokenizer.pad_token_id
41
+ tensors = [prompt, response]
42
+ tensors_with_mask = [prompt_with_mask, response]
43
+ if info is not None:
44
+ tensors.append(info)
45
+ info_mask = torch.full(info.size(), pad_id, dtype=info.dtype, device=info.device) # information mask
46
+ tensors_with_mask.append(info_mask)
47
+
48
+ concatenated = torch.cat(tensors, dim=1)
49
+ concatenated_with_info = torch.cat(tensors_with_mask, dim=1)
50
+ mask = concatenated != pad_id if pad_to_left else concatenated == pad_id
51
+ sorted_indices = mask.to(torch.int64).argsort(dim=1, stable=True)
52
+ padded_tensor = concatenated.gather(1, sorted_indices)
53
+ padded_tensor_with_info = concatenated_with_info.gather(1, sorted_indices)
54
+
55
+ return padded_tensor, padded_tensor_with_info
56
+
57
+ def _update_right_side(
58
+ self, right_side: Dict,
59
+ cur_responses: torch.Tensor,
60
+ next_obs_ids: torch.Tensor = None
61
+ ) -> Dict:
62
+ """Update right side state."""
63
+ if next_obs_ids != None:
64
+ responses, responses_with_info_mask = self._info_masked_concatenate_with_padding(
65
+ right_side['responses'],
66
+ right_side['responses_with_info_mask'],
67
+ cur_responses,
68
+ next_obs_ids,
69
+ pad_to_left=False
70
+ )
71
+ else:
72
+ responses, responses_with_info_mask = self._info_masked_concatenate_with_padding(
73
+ right_side['responses'],
74
+ right_side['responses_with_info_mask'],
75
+ cur_responses,
76
+ pad_to_left=False
77
+ )
78
+ effective_len = self.tensor_fn.create_attention_mask(responses).sum(dim=1).max()
79
+ max_len = min(self.config.max_prompt_length, effective_len)
80
+
81
+ return {'responses': responses[:, :max_len], 'responses_with_info_mask': responses_with_info_mask[:, :max_len]}
82
+
83
+ def run_agent_loop(self, gen_batch: InteractionDataProto) -> InteractionDataProto:
84
+
85
+ initial_input_ids = gen_batch.batch["input_ids"]
86
+ original_left_side = {'input_ids': initial_input_ids[:, -self.config.max_start_length:]}
87
+ original_right_side = {'responses': initial_input_ids[:, []], 'responses_with_info_mask': initial_input_ids[:, []]}
88
+
89
+ # postprocess model inputs
90
+ rollings = gen_batch
91
+ rollings.batch = self.tensor_fn.cut_to_effective_len(
92
+ rollings.batch,
93
+ keys=['input_ids', 'attention_mask']
94
+ )
95
+ rollings_active = {
96
+ k: v for k, v in rollings.batch.items()
97
+ }
98
+
99
+ # model generation
100
+ gen_output = self.actor_rollout_wg.generate(
101
+ rollings_active["input_ids"],
102
+ rollings_active["attention_mask"],
103
+ generation_config=self.generation_config,
104
+ )
105
+ responses_ids = gen_output[:, rollings_active["input_ids"].size(1):]
106
+ responses_ids = self.tensor_fn.erase_after_first_eos(responses_ids, self.tokenizer.eos_token_id)
107
+
108
+ # update right side
109
+ original_right_side = self._update_right_side(original_right_side, responses_ids, next_obs_ids=None)
110
+
111
+ # construct final output
112
+ return self._compose_final_output(original_left_side, original_right_side)
113
+
114
+ def _compose_final_output(
115
+ self, left_side: Dict,
116
+ right_side: Dict,
117
+ ) -> InteractionDataProto:
118
+ """Compose final generation output."""
119
+
120
+ final_output_batch = right_side.copy()
121
+ final_output_batch['prompts'] = left_side['input_ids']
122
+ final_output_batch["responses"] = right_side['responses']
123
+
124
+ # Combine input IDs: input_ids + responses
125
+ final_output_batch['input_ids'] = torch.cat([
126
+ left_side['input_ids'],
127
+ right_side['responses']
128
+ ], dim=1)
129
+
130
+ # Create attention mask
131
+ final_output_batch['attention_mask'] = torch.cat([
132
+ self.tensor_fn.create_attention_mask(left_side['input_ids']),
133
+ self.tensor_fn.create_attention_mask(final_output_batch['responses'])
134
+ ], dim=1)
135
+
136
+ final_output_batch['info_mask'] = torch.cat([
137
+ self.tensor_fn.create_attention_mask(left_side['input_ids']),
138
+ self.tensor_fn.create_attention_mask(final_output_batch['responses_with_info_mask'])
139
+ ], dim=1)
140
+
141
+ final_output = InteractionDataProto(batch=final_output_batch)
142
+
143
+ return final_output
144
+
MemGen-main/interactions/tensor_utils.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Dict, Tuple, List
3
+ from dataclasses import dataclass
4
+
5
+ @dataclass
6
+ class TensorConfig:
7
+ pad_token_id: int
8
+ max_prompt_length: int
9
+ max_obs_length: int
10
+ max_start_length: int
11
+
12
+ class TensorHelper:
13
+ def __init__(self, config: TensorConfig):
14
+ self.config = config
15
+
16
+ def cut_to_effective_len(self, tensor_dict: Dict[str, torch.Tensor],
17
+ keys: List[str], cut_left: bool = True) -> Dict[str, torch.Tensor]:
18
+ """Cut tensors to their effective length based on attention mask."""
19
+ effective_len = tensor_dict['attention_mask'].sum(dim=1).max()
20
+ result = tensor_dict.copy()
21
+
22
+ for key in keys:
23
+ if cut_left: # 裁剪左侧
24
+ result[key] = tensor_dict[key][:, -effective_len:]
25
+ else:
26
+ result[key] = tensor_dict[key][:, :effective_len]
27
+ return result
28
+
29
+ def convert_pad_structure(self, tensor: torch.Tensor, pad_to_left: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
30
+ """Convert padding structure and return sorted tensor with indices."""
31
+ mask = tensor != self.config.pad_token_id if pad_to_left else tensor == self.config.pad_token_id
32
+ sorted_indices = mask.to(torch.int64).argsort(dim=1, stable=True)
33
+ return tensor.gather(1, sorted_indices), sorted_indices
34
+
35
+ def create_attention_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
36
+ """Create attention mask from input ids."""
37
+ return torch.where(input_ids != self.config.pad_token_id, 1, 0)
38
+
39
+ def create_position_ids(self, attention_mask: torch.Tensor) -> torch.Tensor:
40
+ """Create position ids from attention mask."""
41
+ return (torch.cumsum(attention_mask, dim=1) - 1) * attention_mask
42
+
43
+ def concatenate_with_padding(
44
+ self, tensors: List[torch.Tensor],
45
+ pad_to_left: bool = True
46
+ )-> torch.Tensor:
47
+ """Concatenate tensors and handle padding."""
48
+ concatenated = torch.cat(tensors, dim=1)
49
+ padded_tensor, _ = self.convert_pad_structure(concatenated, pad_to_left)
50
+ return padded_tensor
51
+
52
+ def example_level_pad(
53
+ self, responses: torch.Tensor,
54
+ responses_str: List[str],
55
+ active_mask: torch.Tensor
56
+ ) -> Tuple[torch.Tensor, List[str]]:
57
+ assert active_mask.sum() == responses.shape[0]
58
+ # Create masked responses tensor
59
+ batch_size = active_mask.shape[0]
60
+ seq_len = responses.shape[1]
61
+ padded_responses = torch.full(
62
+ (batch_size, seq_len), self.config.pad_token_id,
63
+ dtype=responses.dtype, device=responses.device
64
+ )
65
+ padded_responses[active_mask] = responses
66
+
67
+ # Create masked response strings
68
+ padded_responses_str = [""] * batch_size
69
+
70
+ s = 0
71
+ for i, is_active in enumerate(active_mask):
72
+ if is_active:
73
+ padded_responses_str[i] = responses_str[s]
74
+ s += 1
75
+
76
+ return padded_responses, padded_responses_str
77
+
78
+ def erase_after_first_eos(self, completion_ids: torch.Tensor, eos_token_id: int) -> torch.Tensor:
79
+ is_eos_mask = (completion_ids == eos_token_id)
80
+ first_eos_indices = torch.argmax(is_eos_mask.int(), dim=1)
81
+ seq_len = completion_ids.size(1)
82
+ col_indices = torch.arange(seq_len, device=completion_ids.device)
83
+ mask_to_replace = (col_indices > first_eos_indices.unsqueeze(1)) & is_eos_mask.any(dim=1).unsqueeze(1)
84
+ completion_ids[mask_to_replace] = eos_token_id
85
+ return completion_ids
MemGen-main/memgen/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .model.modeling_memgen import MemGenModel
2
+ from .runner import MemGenRunner
3
+
4
+ __all__ = [
5
+ "MemGenModel",
6
+ "MemGenRunner",
7
+ ]
MemGen-main/memgen/model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from memgen.model.modeling_memgen import MemGenModel
MemGen-main/memgen/model/configuration_memgen.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from typing import Optional
3
+
4
+
5
+ class MemGenConfig(PretrainedConfig):
6
+ model_type = "memgen"
7
+
8
+ def __init__(
9
+ self,
10
+ # weaver configs
11
+ weaver_lora_config: Optional[dict] = None,
12
+ prompt_latents_len: int = 0,
13
+ inference_latents_len: int = 0,
14
+ # trigger configs
15
+ trigger_active: bool = False,
16
+ trigger_lora_config: Optional[dict] = None,
17
+ max_prompt_aug_num: int = 1,
18
+ max_inference_aug_num: int = 5,
19
+ **kwargs
20
+ ):
21
+ super().__init__(**kwargs)
22
+
23
+ # weaver configs
24
+ self.weaver_lora_config = weaver_lora_config
25
+ self.prompt_latents_len = prompt_latents_len
26
+ self.inference_latents_len = inference_latents_len
27
+
28
+ # trigger configs
29
+ self.trigger_active = trigger_active
30
+ self.trigger_lora_config = trigger_lora_config
31
+ self.max_prompt_aug_num = max_prompt_aug_num
32
+ self.max_inference_aug_num = max_inference_aug_num
MemGen-main/memgen/model/modeling_memgen.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import random
4
+ from typing import Union
5
+
6
+ from peft import PeftModel
7
+ import torch
8
+ import torch.nn as nn
9
+ from transformers import (
10
+ AutoModelForCausalLM,
11
+ AutoTokenizer,
12
+ GenerationConfig,
13
+ DynamicCache
14
+ )
15
+ from transformers.modeling_utils import PreTrainedModel
16
+
17
+ from memgen.model.configuration_memgen import MemGenConfig
18
+ from memgen.model.modeling_utils import (
19
+ MemGenOutputWithPast,
20
+ MemGenLoraSwitchMixin,
21
+ MemGenGenerationMixin,
22
+ )
23
+ from memgen.model.trigger import MemGenTrigger
24
+ from memgen.model.weaver import MemGenWeaver
25
+ from memgen.utils import (
26
+ CONVERSATION_TEMPLATE,
27
+ fix_model_parameters,
28
+ log_trainable_params
29
+ )
30
+
31
+ class MemGenModel(PreTrainedModel, MemGenLoraSwitchMixin, MemGenGenerationMixin):
32
+ config_class = MemGenConfig
33
+ INSTRUCTION_STATE = 0
34
+ CONVERSATION_STATE = 1
35
+
36
+ def __init__(
37
+ self,
38
+ config: MemGenConfig,
39
+ base_tokenizer,
40
+ reasoner_base_model: PreTrainedModel,
41
+ weaver_base_model: PreTrainedModel,
42
+ trigger_base_model: PreTrainedModel,
43
+ ):
44
+ super().__init__(config)
45
+
46
+ self.config = config
47
+
48
+ # insert lora adapters into weaver and trigger
49
+ weaver_model_w_lora, trigger_model_w_lora = self._insert_lora_adapters(
50
+ weaver_base_model, config.weaver_lora_config, trigger_base_model, config.trigger_lora_config,
51
+ )
52
+
53
+ # use base model with lora adapters to initiate weaver and trigger
54
+ self.weaver = MemGenWeaver(weaver_model_w_lora, config.prompt_latents_len, config.inference_latents_len)
55
+ self.trigger = MemGenTrigger(trigger_model_w_lora, config.trigger_active)
56
+
57
+ # base reasoner
58
+ self.reasoner = reasoner_base_model
59
+ self.tokenizer = base_tokenizer
60
+
61
+ # projection layers for mapping embeddings between reasoner and weaver
62
+ reasoner_hidden_size = reasoner_base_model.config.hidden_size
63
+ weaver_hidden_size = weaver_base_model.config.hidden_size
64
+ self.reasoner_to_weaver = nn.Linear(reasoner_hidden_size, weaver_hidden_size) # map reasoner input embeddings to weaver input embeddings
65
+ self.weaver_to_reasoner = nn.Linear(weaver_hidden_size, reasoner_hidden_size) # Map weaver hidden states to reasoner input embeddings
66
+
67
+ # delimiters for detecting augmentation points
68
+ self.delimiters: list[str] = [",", ".", "\n"]
69
+
70
+ self.state = None
71
+
72
+ # postprocess
73
+ self._postprocess_models()
74
+ logging.info("##### MemGen Initialization #####")
75
+ log_trainable_params(self)
76
+
77
+ def _postprocess_models(self):
78
+ # fix base model parameters
79
+ fix_model_parameters(self.reasoner)
80
+
81
+ # Ensure tokenizer has a pad token
82
+ if self.tokenizer.pad_token is None:
83
+ self.tokenizer.pad_token = self.tokenizer.eos_token
84
+ self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
85
+ self.tokenizer.padding_side = "left"
86
+ logging.info(
87
+ f"Tokenizer has no pad token. Using EOS token ({self.tokenizer.eos_token}) as pad token."
88
+ )
89
+
90
+ # Normalize the tokenizer's chat template
91
+ self.tokenizer.chat_template = CONVERSATION_TEMPLATE
92
+
93
+
94
+ @property
95
+ def device(self):
96
+ return self.reasoner.device
97
+
98
+ def _forward(
99
+ self,
100
+ input_ids: torch.Tensor,
101
+ attention_mask: torch.Tensor,
102
+ labels: torch.Tensor,
103
+ **kwargs
104
+ ) -> torch.Tensor:
105
+ # preprocess inputs
106
+ assert input_ids.shape == attention_mask.shape == labels.shape
107
+
108
+ tokenizer = self.tokenizer
109
+ reasoner = self.reasoner
110
+ weaver = self.weaver
111
+ delimiters = self.delimiters
112
+ max_augment_num = self.config.max_inference_aug_num # Limit the number of inference augmentation points to avoid excessive augmentation
113
+ device = self.device
114
+ embeds_dtype = reasoner.get_input_embeddings().weight.dtype
115
+ B, _ = input_ids.shape
116
+ hidden_size = self.config.hidden_size
117
+
118
+ # select augment idx
119
+ augmentation_indices = self._select_augment_points_after_delimiter(
120
+ input_ids, labels, delimiters, tokenizer, max_augment_num
121
+ )
122
+
123
+ # origin inputs embeds
124
+ inputs_embeds = reasoner.get_input_embeddings()(input_ids)
125
+
126
+ # Initialize the start index and empty tensors for accumulating processed segments
127
+ current_start_idx = 0
128
+ current_inputs_embeds = torch.empty((B, 0, hidden_size), device=device, dtype=embeds_dtype)
129
+ current_attention_mask = torch.empty((B, 0), device=device, dtype=attention_mask.dtype)
130
+ current_latents_mask = torch.empty((B, 0), device=device, dtype=torch.bool)
131
+
132
+ # Iterate over the selected augmentation points
133
+ for aug_point_idx in augmentation_indices:
134
+ # Slice the current segment of original embeddings and attention mask
135
+ segment_inputs_embeds = inputs_embeds[:, current_start_idx:aug_point_idx]
136
+ segment_attention_mask = attention_mask[:, current_start_idx:aug_point_idx]
137
+ segment_latents_mask = torch.zeros((B, segment_inputs_embeds.size(1)), device=device, dtype=torch.bool)
138
+
139
+ # Concatenate the current segment to the accumulated embeddings and masks
140
+ current_inputs_embeds = torch.cat([current_inputs_embeds, segment_inputs_embeds], dim=1)
141
+ current_attention_mask = torch.cat([current_attention_mask, segment_attention_mask], dim=1)
142
+ current_position_ids = self._generate_position_ids(current_attention_mask)
143
+ current_latents_mask = torch.cat([current_latents_mask, segment_latents_mask], dim=1)
144
+
145
+ # Map reasoner embeddings to weaver embeddings for augmentation
146
+ weaver_inputs_embeds = self.reasoner_to_weaver(current_inputs_embeds)
147
+
148
+ # Determine whether this point is the end of the prompt (prompt augmentation)
149
+ is_prompt_end_aug = (labels[:, aug_point_idx] != -100).all() and (labels[:, aug_point_idx-1] == -100).all().item()
150
+
151
+ # Depending on type, use weaver to augment prompt or inference
152
+ if is_prompt_end_aug:
153
+ weaver_hidden_states, attn_mask, pos_ids = weaver.augment_prompt(
154
+ weaver_inputs_embeds, current_attention_mask, current_position_ids
155
+ )
156
+ else:
157
+ weaver_hidden_states, attn_mask, pos_ids = weaver.augment_inference(
158
+ weaver_inputs_embeds, current_attention_mask, current_position_ids
159
+ )
160
+
161
+ # Map weaver hidden states back to reasoner embeddings
162
+ latent_inputs_embeds = self.weaver_to_reasoner(weaver_hidden_states)
163
+
164
+ # Update accumulated embeddings and masks with the newly augmented segment
165
+ current_inputs_embeds = torch.cat([current_inputs_embeds, latent_inputs_embeds], dim=1)
166
+ current_attention_mask = torch.cat([current_attention_mask, attn_mask], dim=1)
167
+ current_start_idx = aug_point_idx
168
+
169
+ # Update latent mask for the newly added latent embeddings
170
+ latent_mask = torch.ones((B, latent_inputs_embeds.size(1)), device=device, dtype=torch.bool)
171
+ current_latents_mask = torch.cat([current_latents_mask, latent_mask], dim=1)
172
+
173
+ # Process the remaining segment after the last augmentation point
174
+ remaining_inputs_embeds = inputs_embeds[:, current_start_idx:]
175
+ remaining_attention_mask = attention_mask[:, current_start_idx:]
176
+ latent_mask = torch.zeros((B, remaining_attention_mask.size(1)), device=device, dtype=torch.bool)
177
+
178
+ current_inputs_embeds = torch.cat([current_inputs_embeds, remaining_inputs_embeds], dim=1)
179
+ current_attention_mask = torch.cat([current_attention_mask, remaining_attention_mask], dim=1)
180
+ current_position_ids = self._generate_position_ids(current_attention_mask)
181
+ current_latents_mask = torch.cat([current_latents_mask, latent_mask], dim=1)
182
+
183
+ reasoner_outputs = reasoner(
184
+ inputs_embeds=current_inputs_embeds,
185
+ attention_mask=current_attention_mask,
186
+ position_ids=current_position_ids
187
+ )
188
+ logits = reasoner_outputs.logits
189
+
190
+ # Identify valid positions in logits (positions that should contribute to loss)
191
+ shifted = torch.zeros_like(current_latents_mask)
192
+ shifted[:, :-1] = current_latents_mask[:, 1:]
193
+ valid_mask = ~shifted
194
+
195
+ valid_logits = logits[valid_mask].view(logits.size(0), -1, logits.size(2))
196
+ # assert shifted.sum() == current_latents_mask.sum()
197
+ # assert valid_logits.shape[:2] == input_ids.shape
198
+ return valid_logits
199
+
200
+ def _instructional_forward(
201
+ self,
202
+ input_ids: torch.Tensor,
203
+ attention_mask: torch.Tensor,
204
+ labels: torch.Tensor,
205
+ **kwargs
206
+ ) -> tuple[torch.FloatTensor, torch.LongTensor]:
207
+ """
208
+ Forward pass for single-turn instructional data (no multi-turn conversation required).
209
+
210
+ This method is used for instruction-following tasks (SFT), where the input
211
+ consists of a single instruction and the corresponding labels. It directly
212
+ delegates to the single-turn forward method `_forward`.
213
+
214
+ Args:
215
+ input_ids (torch.Tensor): Tensor of shape (batch_size, seq_len) containing input token IDs.
216
+ attention_mask (torch.Tensor): Tensor indicating padding positions.
217
+ labels (torch.Tensor): Tensor containing the target labels for supervised fine-tuning.
218
+ **kwargs: Additional keyword arguments passed to `_forward`.
219
+
220
+ Returns:
221
+ tuple[torch.Tensor, torch.Tensor]:
222
+ - logits: The output logits from the model for each input token.
223
+ - labels: The same as input labels, used for loss computation.
224
+ """
225
+ # raise RuntimeError()
226
+ logits = self._forward(input_ids, attention_mask, labels, **kwargs)
227
+ # For Instruction SFT, labels remain the same as input
228
+ return logits, labels
229
+
230
+ def _conversational_forward(
231
+ self,
232
+ input_ids: torch.Tensor,
233
+ attention_mask: torch.Tensor,
234
+ labels: torch.Tensor,
235
+ **kwargs
236
+ ) -> tuple[torch.FloatTensor, torch.LongTensor]:
237
+ """
238
+ Forward pass for conversational (multi-turn) data.
239
+
240
+ Multi-turn forward is constructed by sequentially calling the single-turn forward
241
+ for each conversation turn. Latents inserted in turn i-1 are not visible to turn i.
242
+
243
+ Args:
244
+ input_ids (torch.Tensor): Input token IDs, shape (1, seq_len). Batch size must be 1.
245
+ attention_mask (torch.Tensor): Attention mask for input tokens.
246
+ labels (torch.Tensor): Target labels for supervised fine-tuning (-100 for ignore positions).
247
+ **kwargs: Additional arguments passed to `_forward`.
248
+
249
+ Returns:
250
+ tuple[torch.Tensor, torch.Tensor]:
251
+ - all_logits: Logits for the entire sequence, with zeros for unsupervised positions.
252
+ - all_labels: Labels for the entire sequence, with -100 for unsupervised positions.
253
+ """
254
+ assert input_ids.shape[0] == 1, "Conversational SFT currently only supports batch_size = 1"
255
+ seq_len = input_ids.shape[1]
256
+ vocab_size = self.config.vocab_size
257
+ device = input_ids.device
258
+
259
+ # Identify single-turn segments within the conversation based on labels
260
+ label_row = labels[0]
261
+ should_supervise = label_row != -100
262
+ if not should_supervise.any():
263
+ raise ValueError("At least one completion segment is required")
264
+
265
+ # Compute the start and end indices of valid supervised segments
266
+ valid_mask = should_supervise.int()
267
+ diff = torch.diff(torch.cat([torch.tensor([0], device=device), valid_mask]))
268
+ valid_starts = (diff == 1).nonzero(as_tuple=True)[0].tolist() # Transition 0 -> 1
269
+ ends = (diff == -1).nonzero(as_tuple=True)[0].tolist() # Transition 1 -> 0
270
+ if len(ends) < len(valid_starts):
271
+ ends.append(seq_len) # 自动补充最后一个 token 的 (index + 1) 作为最后一个序列的末尾
272
+ assert len(valid_starts) == len(ends)
273
+
274
+ # Build triplets (start of previous segment, start of supervised segment, end of supervised segment)
275
+ triplets = []
276
+ start = 0
277
+ for s, e in zip(valid_starts, ends):
278
+ triplets.append((start, s, e))
279
+ start = e
280
+
281
+ # If there are more segments than allowed, randomly select self.max_prompt_aug_num segments
282
+ if len(triplets) <= self.config.max_prompt_aug_num:
283
+ select_turns = [1] * len(triplets)
284
+ else:
285
+ triplets_num = len(triplets)
286
+ selected_indices = set(random.sample(range(triplets_num), self.config.max_prompt_aug_num))
287
+ select_turns = [1 if i in selected_indices else 0 for i in range(triplets_num)]
288
+
289
+ # Initialize tensors to store logits and labels for the entire sequence
290
+ all_logits = torch.zeros(1, seq_len, vocab_size, device=device)
291
+ all_labels = torch.full((1, seq_len), -100, device=device)
292
+
293
+ # Loop over each conversation turn and perform single-turn forward if supervised
294
+ for triplet, should_supervise in zip(triplets, select_turns):
295
+ start, valid_start, end = triplet
296
+ if should_supervise:
297
+ cur_input_ids = input_ids[0, :end].unsqueeze(0)
298
+ cur_attention = attention_mask[0, :end].unsqueeze(0)
299
+ # cur_labels only used for _forward, does not represent the true supervision range
300
+ # cur_labels = labels[0, :end].clone().unsqueeze(0)
301
+ # cur_labels[0, :valid_start] = -100 # Mask tokens before supervision start
302
+ cur_labels = torch.full((1, end), -100, device=device)
303
+ cur_labels[0, valid_start:end] = labels[0, valid_start:end]
304
+
305
+ # Single-turn forward for the current conversation segment
306
+ logits = self._forward(cur_input_ids, cur_attention, cur_labels, **kwargs)
307
+
308
+ # Update overall logits and labels with the results of this segment
309
+ all_logits[0, start:end, :] = logits[0, start:end, :]
310
+ all_labels[0, start:end] = labels[0, start:end]
311
+
312
+ # Return logits and labels:
313
+ # - supervised positions retain computed logits and original labels
314
+ # - unsupervised positions have logits = 0 and labels = -100
315
+ return all_logits, all_labels
316
+
317
+ def forward(
318
+ self,
319
+ input_ids: torch.Tensor,
320
+ attention_mask: torch.Tensor,
321
+ labels: torch.Tensor,
322
+ **kwargs
323
+ ) -> MemGenOutputWithPast:
324
+ tokenizer = self.tokenizer
325
+
326
+ # Ensure labels are provided, required for training the reasoning processor
327
+ assert labels is not None, "Reasoning Processor requires input labels for training"
328
+
329
+ # Determine whether the input is single-turn (instruction) or multi-turn (conversation)
330
+ labels = self._postprocess_assistant_labels(input_ids, labels, tokenizer)
331
+
332
+ # Use only the first data sample of each dataset to determine the model state
333
+ if self.state is None:
334
+ self.state = MemGenModel.CONVERSATION_STATE if self._is_conversation(input_ids, tokenizer) else MemGenModel.INSTRUCTION_STATE
335
+
336
+ if self.state == MemGenModel.INSTRUCTION_STATE:
337
+ forward_func = self._instructional_forward
338
+ elif self.state == MemGenModel.CONVERSATION_STATE:
339
+ forward_func = self._conversational_forward
340
+ else:
341
+ raise RuntimeError(f"Unexpected model state: {self.state}")
342
+
343
+ batch_size = 1 # Currently process one sequence per batch
344
+ iter_num = input_ids.size(0) // batch_size
345
+
346
+ # Forward pass per batch
347
+ logits, supervised_labels = [], []
348
+ for i in range(iter_num):
349
+ batch_input_ids = input_ids[i * batch_size: (i + 1) * batch_size]
350
+ batch_attention_mask = attention_mask[i * batch_size: (i + 1) * batch_size]
351
+ batch_labels = labels[i * batch_size: (i + 1) * batch_size]
352
+
353
+ # Call the appropriate forward function (instruction or conversation)
354
+ batch_logits, batch_supervised_labels = forward_func(
355
+ input_ids=batch_input_ids,
356
+ attention_mask=batch_attention_mask,
357
+ labels=batch_labels,
358
+ **kwargs
359
+ )
360
+ logits.append(batch_logits)
361
+ supervised_labels.append(batch_supervised_labels)
362
+
363
+ # Concatenate results from all batches
364
+ all_logits = torch.concat(logits, dim=0)
365
+ all_labels = torch.concat(supervised_labels, dim=0)
366
+
367
+ # Compute causal language modeling loss (shifted by one)
368
+ shift_logits = all_logits[..., :-1, :].contiguous()
369
+ shift_labels = all_labels[..., 1:].contiguous()
370
+ # assert shift_logits.shape[:-1] == shift_labels.shape
371
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
372
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
373
+
374
+ # Return model outputs
375
+ outputs = MemGenOutputWithPast(loss=loss, logits=all_logits)
376
+ outputs.supervised_labels = all_labels # Positions in input_ids that are supervised
377
+ return outputs
378
+
379
+ # @torch.no_grad()
380
+ # def generate(
381
+ # self,
382
+ # input_ids: torch.Tensor,
383
+ # attention_mask: torch.Tensor,
384
+ # generation_config: GenerationConfig = None,
385
+ # return_augmentation_mask: bool = False,
386
+ # **kwargs
387
+ # ) -> Union[torch.LongTensor, tuple[torch.LongTensor, torch.LongTensor]]:
388
+
389
+ # tokenizer = self.tokenizer
390
+ # reasoner = self.reasoner
391
+ # weaver = self.weaver
392
+ # max_augment_num = self.config.max_inference_aug_num
393
+ # invalid_token_id = -100
394
+
395
+ # # preproecess inputs
396
+ # input_ids = input_ids.to(self.device)
397
+ # attention_mask = attention_mask.to(self.device)
398
+ # max_new_tokens = generation_config.max_new_tokens
399
+ # pad_token_id = tokenizer.pad_token_id
400
+ # eos_token_id = tokenizer.eos_token_id
401
+ # prompt_len = input_ids.size(1)
402
+
403
+ # inputs_embeds = reasoner.get_input_embeddings()(input_ids)
404
+ # B, _, hidden_size = inputs_embeds.shape
405
+ # device = inputs_embeds.device
406
+
407
+ # # --- generation loop ---
408
+ # current_inputs_embeds = inputs_embeds
409
+ # current_attention_mask = attention_mask
410
+ # current_position_ids = self._generate_position_ids(current_attention_mask)
411
+ # current_input_ids = input_ids
412
+ # current_cache: DynamicCache = None
413
+
414
+ # # Generation Loop Initialization
415
+ # sentence_augment_count = torch.zeros(B, dtype=torch.int, device=device)
416
+
417
+ # # NOTE - Whether to call the trigger and insert latent memory before generating the token at this position
418
+ # # - augmentation_pos[b][i] == -100: For the b-th sequence, no augmentation was sampled before generating the i-th token
419
+ # # - augmentation_pos[b][i] == 0: For the b-th sequence, augmentation was sampled before generating the i-th token, but the trigger decided NOT to insert latent memory
420
+ # # - augmentation_pos[b][i] == 1: For the b-th sequence, augmentation was sampled before generating the i-th token, and the trigger decided to insert latent memory
421
+ # augmentation_pos = torch.full((B, max_new_tokens), fill_value=invalid_token_id, device=device)
422
+
423
+ # generation_config = GenerationConfig(
424
+ # do_sample=False,
425
+ # pad_token_id=pad_token_id,
426
+ # eos_token_id=eos_token_id,
427
+ # use_cache=False,
428
+ # max_new_tokens=max_new_tokens
429
+ # )
430
+ # # Perform generation for the remaining tokens using the reasoner
431
+ # generated = reasoner.generate(
432
+ # inputs_embeds=current_inputs_embeds,
433
+ # attention_mask=current_attention_mask,
434
+ # generation_config=generation_config
435
+ # )
436
+ # current_input_ids = torch.cat([current_input_ids, generated], dim=1)
437
+
438
+ # # postprocess
439
+ # new_generated_len = current_input_ids.size(1) - prompt_len
440
+ # augmentation_pos = augmentation_pos[:, :new_generated_len]
441
+
442
+ # self._check_generate(
443
+ # current_input_ids[:, prompt_len:],
444
+ # augmentation_pos
445
+ # )
446
+
447
+ # if return_augmentation_mask:
448
+ # return (current_input_ids, augmentation_pos)
449
+ # else:
450
+ # return current_input_ids
451
+
452
+ @torch.no_grad()
453
+ def generate(
454
+ self,
455
+ input_ids: torch.Tensor,
456
+ attention_mask: torch.Tensor,
457
+ generation_config: GenerationConfig = None,
458
+ return_augmentation_mask: bool = False,
459
+ **kwargs
460
+ ) -> Union[torch.LongTensor, tuple[torch.LongTensor, torch.LongTensor]]:
461
+
462
+ tokenizer = self.tokenizer
463
+ reasoner = self.reasoner
464
+ weaver = self.weaver
465
+ max_augment_num = self.config.max_inference_aug_num
466
+ invalid_token_id = -100
467
+
468
+ # preproecess inputs
469
+ input_ids = input_ids.to(self.device)
470
+ attention_mask = attention_mask.to(self.device)
471
+ max_new_tokens = generation_config.max_new_tokens
472
+ pad_token_id = tokenizer.pad_token_id
473
+ eos_token_id = tokenizer.eos_token_id
474
+ prompt_len = input_ids.size(1)
475
+
476
+ inputs_embeds = reasoner.get_input_embeddings()(input_ids)
477
+ B, _, hidden_size = inputs_embeds.shape
478
+ device = inputs_embeds.device
479
+
480
+ # --- generation loop ---
481
+ current_inputs_embeds = inputs_embeds
482
+ current_attention_mask = attention_mask
483
+ current_position_ids = self._generate_position_ids(current_attention_mask)
484
+ current_input_ids = input_ids
485
+ current_cache: DynamicCache = None
486
+
487
+ # Generation Loop Initialization
488
+ sentence_augment_count = torch.zeros(B, dtype=torch.int, device=device)
489
+
490
+ # NOTE - Whether to call the trigger and insert latent memory before generating the token at this position
491
+ # - augmentation_pos[b][i] == -100: For the b-th sequence, no augmentation was sampled before generating the i-th token
492
+ # - augmentation_pos[b][i] == 0: For the b-th sequence, augmentation was sampled before generating the i-th token, but the trigger decided NOT to insert latent memory
493
+ # - augmentation_pos[b][i] == 1: For the b-th sequence, augmentation was sampled before generating the i-th token, and the trigger decided to insert latent memory
494
+ augmentation_pos = torch.full((B, max_new_tokens), fill_value=invalid_token_id, device=device)
495
+
496
+ for i in range(max_new_tokens):
497
+
498
+ assert current_inputs_embeds.shape[:2] == current_attention_mask.shape == current_position_ids.shape
499
+ augment_decision = self._should_augment(
500
+ current_input_ids,
501
+ sentence_augment_count=sentence_augment_count,
502
+ do_sample=generation_config.trigger_do_sample,
503
+ temperature=generation_config.temperature,
504
+ is_prompt=(i==0)
505
+ )
506
+ augmentation_pos[:, i] = augment_decision
507
+ augment_indices = torch.where(augment_decision == 1)[0]
508
+
509
+ # If there are sentences to augment, apply augmentation; others remain with left padding
510
+ if len(augment_indices) > 0:
511
+ # Increment the augmentation count for sentences that are being augmented
512
+ if i != 0:
513
+ sentence_augment_count[augment_indices] += 1
514
+
515
+ # Select embeddings, attention masks, and position IDs for sentences to be augmented
516
+ candidate_inputs_embeds = current_inputs_embeds[augment_indices]
517
+ candidate_attention_mask = current_attention_mask[augment_indices]
518
+ candidate_position_ids = current_position_ids[augment_indices]
519
+
520
+ # Perform inference augmentation using the weaver
521
+ weaver_inputs_embeds = self.reasoner_to_weaver(candidate_inputs_embeds)
522
+ if i == 0:
523
+ weaver_hidden_states, attn_mask, _ = weaver.augment_prompt(
524
+ weaver_inputs_embeds, candidate_attention_mask, candidate_position_ids
525
+ )
526
+ else:
527
+ weaver_hidden_states, attn_mask, _ = weaver.augment_inference(
528
+ weaver_inputs_embeds, candidate_attention_mask, candidate_position_ids
529
+ )
530
+ latent_inputs_embeds = self.weaver_to_reasoner(weaver_hidden_states)
531
+
532
+ candidate_inputs_embeds = torch.cat([candidate_inputs_embeds, latent_inputs_embeds], dim=1)
533
+ candidate_attention_mask = torch.cat([candidate_attention_mask, attn_mask], dim=1)
534
+
535
+ # Create a single merged tensor for all sequences
536
+ new_len = candidate_inputs_embeds.size(1)
537
+ merged_inputs_embeds = torch.zeros((B, new_len, hidden_size), device=device, dtype=current_inputs_embeds.dtype)
538
+ merged_attention_mask = torch.zeros((B, new_len), device=device, dtype=current_attention_mask.dtype)
539
+
540
+ # Directly place augmented and non-augmented sequences
541
+ merged_inputs_embeds[augment_indices] = candidate_inputs_embeds
542
+ merged_attention_mask[augment_indices] = candidate_attention_mask
543
+
544
+ # Non-augmented sequences now include both -100 and 0
545
+ non_augment_indices = torch.where(augment_decision != 1)[0]
546
+ if len(non_augment_indices) > 0:
547
+ # dynamic left padding
548
+ non_aug_inputs_embeds = current_inputs_embeds[non_augment_indices]
549
+ non_aug_attention_mask = current_attention_mask[non_augment_indices]
550
+ pad_len = weaver.prompt_latents_num if i == 0 else weaver.inference_latents_num
551
+ non_aug_inputs_embeds, non_aug_attention_mask, _ = self._left_pad(
552
+ non_aug_inputs_embeds, non_aug_attention_mask, None, pad_len
553
+ )
554
+
555
+ merged_inputs_embeds[non_augment_indices] = non_aug_inputs_embeds
556
+ merged_attention_mask[non_augment_indices] = non_aug_attention_mask
557
+
558
+ current_inputs_embeds = merged_inputs_embeds
559
+ current_attention_mask = merged_attention_mask
560
+ current_position_ids = self._generate_position_ids(current_attention_mask)
561
+ current_cache = None
562
+
563
+ # Check if all sequences have reached the maximum number of augmentations
564
+ if (sentence_augment_count >= max_augment_num).all():
565
+ # Adjust the remaining generation length
566
+ generation_config_continue = GenerationConfig(
567
+ do_sample=generation_config.weaver_do_sample,
568
+ pad_token_id=pad_token_id,
569
+ eos_token_id=eos_token_id,
570
+ use_cache=False,
571
+ max_new_tokens=max_new_tokens-i
572
+ )
573
+ # Perform generation for the remaining tokens using the reasoner
574
+ generated = reasoner.generate(
575
+ inputs_embeds=current_inputs_embeds,
576
+ attention_mask=current_attention_mask,
577
+ generation_config=generation_config_continue
578
+ )
579
+ current_input_ids = torch.cat([current_input_ids, generated], dim=1)
580
+ break
581
+
582
+ if current_cache is not None:
583
+ assert current_inputs_embeds.size(1) == current_cache.get_seq_length() + 1
584
+ reasoner_inputs_embeds = current_inputs_embeds[:, -1:]
585
+ reasoner_position_ids = current_position_ids[:, -1:]
586
+ else:
587
+ reasoner_inputs_embeds = current_inputs_embeds
588
+ reasoner_position_ids = current_position_ids
589
+
590
+ outputs = reasoner(
591
+ inputs_embeds=reasoner_inputs_embeds,
592
+ attention_mask=current_attention_mask,
593
+ position_ids=reasoner_position_ids,
594
+ output_hidden_states=False,
595
+ use_cache=True,
596
+ past_key_values=current_cache
597
+ )
598
+ current_inputs_embeds, current_attention_mask, current_position_ids, current_input_ids = self._append_one_step(
599
+ outputs,
600
+ current_inputs_embeds,
601
+ current_attention_mask,
602
+ current_position_ids,
603
+ current_input_ids,
604
+ do_sample=generation_config.weaver_do_sample,
605
+ temperature=generation_config.temperature
606
+ )
607
+ current_cache = outputs.past_key_values
608
+
609
+ # If all sequences in the batch have already generated an EOS token, stop early
610
+ if (current_input_ids[:, -1] == eos_token_id).all():
611
+ break
612
+
613
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
614
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
615
+ del outputs
616
+
617
+ # postprocess
618
+ new_generated_len = current_input_ids.size(1) - prompt_len
619
+ augmentation_pos = augmentation_pos[:, :new_generated_len]
620
+
621
+ self._check_generate(
622
+ current_input_ids[:, prompt_len:],
623
+ augmentation_pos
624
+ )
625
+
626
+ if return_augmentation_mask:
627
+ return (current_input_ids, augmentation_pos)
628
+ else:
629
+ return current_input_ids
630
+
631
+ @classmethod
632
+ def from_config(cls, config_dict: dict):
633
+ # base LLM
634
+ model_name = config_dict.get("model_name")
635
+
636
+ # max augment numbers
637
+ max_prompt_aug_num = config_dict.get("max_prompt_aug_num", 1)
638
+ max_inference_aug_num = config_dict.get("max_inference_aug_num", 5)
639
+
640
+ # weaver configs
641
+ weaver_config = config_dict.get("weaver", {})
642
+ prompt_latents_len = weaver_config.get("prompt_latents_len", 8)
643
+ inference_latents_len = weaver_config.get("inference_latents_len", 8)
644
+ weaver_lora_config_dict = weaver_config.get("lora_config", None)
645
+ weaver_model_name = weaver_config.get("model_name", None)
646
+
647
+ # trigger configs
648
+ trigger_config = config_dict.get("trigger", {})
649
+ trigger_active = trigger_config.get("active", False)
650
+ trigger_lora_config_dict = trigger_config.get("lora_config", None)
651
+ trigger_model_name = trigger_config.get("model_name", None)
652
+
653
+ # build MemGenConfig
654
+ from transformers import AutoConfig
655
+ memgen_config = AutoConfig.from_pretrained(model_name)
656
+ memgen_config = MemGenConfig.from_pretrained(
657
+ model_name,
658
+ max_prompt_aug_num=max_prompt_aug_num,
659
+ max_inference_aug_num=max_inference_aug_num,
660
+ prompt_latents_len=prompt_latents_len,
661
+ inference_latents_len=inference_latents_len,
662
+ weaver_lora_config=weaver_lora_config_dict,
663
+ trigger_active=trigger_active,
664
+ trigger_lora_config=trigger_lora_config_dict
665
+ )
666
+
667
+ # load pretrained base models
668
+ base_tokenizer = AutoTokenizer.from_pretrained(model_name)
669
+ reasoner_base_model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
670
+ weaver_base_model = AutoModelForCausalLM.from_pretrained(weaver_model_name, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
671
+ trigger_base_model = AutoModelForCausalLM.from_pretrained(trigger_model_name, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
672
+
673
+ # instantiate MemGen Model
674
+ load_model_path = config_dict.get("load_model_path", None)
675
+
676
+ if not load_model_path:
677
+ model = cls(
678
+ config=memgen_config,
679
+ base_tokenizer=base_tokenizer,
680
+ reasoner_base_model=reasoner_base_model,
681
+ weaver_base_model=weaver_base_model,
682
+ trigger_base_model=trigger_base_model
683
+ )
684
+ else:
685
+ model = cls.from_pretrained(
686
+ load_model_path,
687
+ config=memgen_config,
688
+ base_tokenizer=base_tokenizer,
689
+ reasoner_base_model=reasoner_base_model,
690
+ weaver_base_model=weaver_base_model,
691
+ trigger_base_model=trigger_base_model
692
+ )
693
+
694
+ return model
695
+
696
+ def save_pretrained(self, save_directory: str, **kwargs):
697
+ os.makedirs(save_directory, exist_ok=True)
698
+
699
+ self.config.save_pretrained(save_directory)
700
+
701
+ torch.save(
702
+ {
703
+ "reasoner_to_weaver": self.reasoner_to_weaver.state_dict(),
704
+ "weaver_to_reasoner": self.weaver_to_reasoner.state_dict(),
705
+ },
706
+ os.path.join(save_directory, "projs.bin"),
707
+ )
708
+
709
+ torch.save(
710
+ {
711
+ "prompt_query_latents": self.weaver.prompt_query_latents.data,
712
+ "inference_query_latents": self.weaver.inference_query_latents.data,
713
+ "prompt_latent_ln": self.weaver.prompt_latent_ln.state_dict(),
714
+ "inference_latent_ln": self.weaver.inference_latent_ln.state_dict(),
715
+ "prompt_latent_scale": self.weaver.prompt_latent_scale.data,
716
+ "inference_latent_scale": self.weaver.inference_latent_scale.data,
717
+ },
718
+ os.path.join(save_directory, "weaver.bin"),
719
+ )
720
+
721
+ torch.save(
722
+ {
723
+ "output_layer": self.trigger.output_layer.state_dict(),
724
+ },
725
+ os.path.join(save_directory, "trigger.bin"),
726
+ )
727
+
728
+ self.weaver.model.save_pretrained(os.path.join(save_directory, "weaver"))
729
+ self.trigger.model.save_pretrained(os.path.join(save_directory, "trigger"))
730
+
731
+
732
+ @classmethod
733
+ def from_pretrained(
734
+ cls,
735
+ load_directory: str,
736
+ *,
737
+ config,
738
+ base_tokenizer,
739
+ reasoner_base_model,
740
+ weaver_base_model,
741
+ trigger_base_model,
742
+ ):
743
+ model = cls(
744
+ config=config,
745
+ base_tokenizer=base_tokenizer,
746
+ reasoner_base_model=reasoner_base_model,
747
+ weaver_base_model=weaver_base_model,
748
+ trigger_base_model=trigger_base_model,
749
+ )
750
+
751
+ proj_path = os.path.join(load_directory, "projs.bin")
752
+ proj_state = torch.load(proj_path, map_location="cpu")
753
+ model.reasoner_to_weaver.load_state_dict(proj_state["reasoner_to_weaver"])
754
+ model.weaver_to_reasoner.load_state_dict(proj_state["weaver_to_reasoner"])
755
+
756
+ weaver_path = os.path.join(load_directory, "weaver.bin")
757
+ weaver_state = torch.load(weaver_path, map_location="cpu")
758
+ model.weaver.prompt_query_latents.data.copy_(weaver_state["prompt_query_latents"])
759
+ model.weaver.inference_query_latents.data.copy_(weaver_state["inference_query_latents"])
760
+ model.weaver.prompt_latent_ln.load_state_dict(weaver_state["prompt_latent_ln"])
761
+ model.weaver.inference_latent_ln.load_state_dict(weaver_state["inference_latent_ln"])
762
+ model.weaver.prompt_latent_scale.data.copy_(weaver_state["prompt_latent_scale"])
763
+ model.weaver.inference_latent_scale.data.copy_(weaver_state["inference_latent_scale"])
764
+
765
+ trigger_path = os.path.join(load_directory, "trigger.bin")
766
+ trigger_state = torch.load(trigger_path, map_location="cpu")
767
+ model.trigger.output_layer.load_state_dict(trigger_state["output_layer"])
768
+
769
+ model.weaver.model = PeftModel.from_pretrained(
770
+ model.weaver.model.base_model,
771
+ os.path.join(load_directory, "weaver", "weaver"),
772
+ adapter_name=MemGenWeaver.adapter_name,
773
+ )
774
+ model.weaver.model.set_adapter(MemGenWeaver.adapter_name)
775
+
776
+ model.trigger.model = PeftModel.from_pretrained(
777
+ model.trigger.model.base_model,
778
+ os.path.join(load_directory, "trigger", "trigger"),
779
+ adapter_name=MemGenTrigger.adapter_name,
780
+ )
781
+ model.trigger.model.set_adapter(MemGenTrigger.adapter_name)
782
+
783
+ logging.info("##### MemGen from Pretrained #####")
784
+ log_trainable_params(model)
785
+
786
+ return model
787
+
MemGen-main/memgen/model/modeling_utils.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import logging
3
+ import os
4
+ from typing import Optional, Literal, Set
5
+
6
+ from peft import PeftModel, LoraConfig
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from transformers import PreTrainedTokenizerBase
10
+ from transformers.generation.utils import GenerationMixin
11
+ from transformers.modeling_outputs import CausalLMOutputWithPast
12
+ from transformers.modeling_utils import PreTrainedModel
13
+
14
+ from memgen.model.trigger import MemGenTrigger
15
+ from memgen.model.weaver import MemGenWeaver
16
+ from memgen.utils import (
17
+ CONVERSATION_TEMPLATE,
18
+ fix_model_parameters,
19
+ open_model_parameters
20
+ )
21
+
22
+ @dataclass
23
+ class MemGenOutputWithPast(CausalLMOutputWithPast):
24
+ supervised_labels: Optional[torch.LongTensor] = None
25
+
26
+ class MemGenLoraSwitchMixin:
27
+
28
+ def _insert_lora_adapters(
29
+ self,
30
+ weaver_model: PreTrainedModel,
31
+ weaver_lora_config: dict,
32
+ trigger_model: PreTrainedModel,
33
+ trigger_lora_config: dict
34
+ ) -> tuple[PeftModel, PeftModel]:
35
+ # insert lora adapters into weaver and trigger
36
+ weaver_lora_config = LoraConfig(**weaver_lora_config)
37
+ trigger_lora_config = LoraConfig(**trigger_lora_config)
38
+
39
+ weaver_model_with_lora = PeftModel(
40
+ weaver_model, weaver_lora_config, adapter_name=MemGenWeaver.adapter_name
41
+ )
42
+ trigger_model_with_lora = PeftModel(
43
+ trigger_model, trigger_lora_config, adapter_name=MemGenTrigger.adapter_name
44
+ )
45
+
46
+ return weaver_model_with_lora, trigger_model_with_lora
47
+
48
+ def fix_component(self, name: Literal["weaver", "trigger"]):
49
+ # frozen parameters of weaver or trigger
50
+ component = getattr(self, name)
51
+ fix_model_parameters(component)
52
+ if name == "weaver":
53
+ fix_model_parameters(self.weaver_to_reasoner)
54
+ fix_model_parameters(self.reasoner_to_weaver)
55
+
56
+ def open_component(self, name: Literal["weaver", "trigger"]):
57
+ # open parameters of weaver or trigger
58
+ component = getattr(self, name)
59
+ open_model_parameters(component)
60
+ if name == "weaver":
61
+ open_model_parameters(self.weaver_to_reasoner)
62
+ open_model_parameters(self.reasoner_to_weaver)
63
+
64
+ fix_model_parameters(component.model.base_model) # only finetune the lora adapters of the specific component
65
+
66
+ for n, p in component.model.named_parameters():
67
+ if "lora_A" in n or "lora_B" in n:
68
+ if name in n:
69
+ assert p.requires_grad, f"{n} should be trainable"
70
+ else:
71
+ assert not p.requires_grad, f"{n} should be frozen"
72
+
73
+
74
+ class MemGenGenerationMixin(GenerationMixin):
75
+
76
+ def _get_next_token(
77
+ self,
78
+ next_token_logits: torch.Tensor,
79
+ do_sample: bool,
80
+ temperature: Optional[float] = 0.0
81
+ ) -> torch.Tensor:
82
+ if len(next_token_logits.shape) != 2:
83
+ raise ValueError("Input logits must be a 2D tensor [batch_size, vocab_size]")
84
+
85
+ if do_sample and temperature != 0: # Apply temperature scaling and sample from the resulting probability distribution
86
+ probs = F.softmax(next_token_logits / temperature, dim=-1)
87
+ return torch.multinomial(probs, num_samples=1)
88
+ else: # Greedy decoding: pick the token with the highest probability
89
+ return torch.argmax(next_token_logits, dim=-1, keepdim=True)
90
+
91
+ def _generate_position_ids(self, attention_mask: torch.Tensor) -> torch.Tensor:
92
+ position_ids = (attention_mask.cumsum(-1) - 1).clamp(min=0)
93
+ position_ids.masked_fill_(attention_mask == 0, 0)
94
+ return position_ids
95
+
96
+ def _is_conversation(self, input_ids: torch.Tensor, tokenizer) -> bool:
97
+ # if the input_ids has more than one <|im_start|>assistant\n, then it will be considered as a conversation
98
+ if len(input_ids.shape) != 2:
99
+ raise ValueError("input_ids must be a 2D tensor of shape (batch_size, seq_len)")
100
+
101
+ seq = input_ids[0].tolist()
102
+
103
+ im_start_ids = tokenizer.encode("<|im_start|>", add_special_tokens=False)
104
+ assistant_ids = tokenizer.encode("assistant", add_special_tokens=False)
105
+
106
+ target_seq = im_start_ids + assistant_ids
107
+
108
+ count = 0
109
+ for i in range(len(seq) - len(target_seq) + 1):
110
+ if seq[i:i+len(target_seq)] == target_seq:
111
+ count += 1
112
+
113
+ return count > 1
114
+
115
+
116
+ def _postprocess_assistant_labels(
117
+ self,
118
+ input_ids: torch.Tensor,
119
+ labels: torch.Tensor,
120
+ tokenizer
121
+ ) -> torch.Tensor:
122
+ if tokenizer.chat_template != CONVERSATION_TEMPLATE:
123
+ raise ValueError(
124
+ "Invalid tokenizer.chat_template detected.\n"
125
+ f"Expected:\n{CONVERSATION_TEMPLATE}\n\n"
126
+ f"Got:\n{tokenizer.chat_template}\n\n"
127
+ "Please ensure that you are using the correct conversation template."
128
+ )
129
+
130
+ # Encode the token sequence for "<|im_start|>assistant\n"
131
+ pattern_ids: list[int] = tokenizer.encode("<|im_start|>assistant\n", add_special_tokens=False)
132
+
133
+ batch_size, seq_len = input_ids.shape
134
+ new_labels = labels.clone()
135
+
136
+ for b in range(batch_size):
137
+ seq = input_ids[b].tolist()
138
+ for i in range(len(seq) - len(pattern_ids) + 1):
139
+ # Mask positions matching the pattern
140
+ if seq[i : i + len(pattern_ids)] == pattern_ids:
141
+ new_labels[b, i : i + len(pattern_ids)] = -100
142
+
143
+ return new_labels
144
+
145
+ def _get_delimiter_token_ids(self, tokenizer, delimiters: list[str]) -> Set[int]:
146
+ """预计算 delimiter 对应的 token ids (在 __init__ 后调用一次)"""
147
+ delimiter_token_ids = set()
148
+ for d in delimiters:
149
+ ids = tokenizer.encode(d, add_special_tokens=False)
150
+ delimiter_token_ids.update(ids)
151
+ return delimiter_token_ids
152
+
153
+ def _check_ends_with_delimiter(
154
+ self, input_ids: torch.Tensor, tokenizer, delimiters: list[str]
155
+ ) -> torch.Tensor:
156
+ """检查每个序列的最后一个 token 是否是 delimiter token (O(1) 每序列,无 decode)"""
157
+ batch_size = input_ids.size(0)
158
+ device = input_ids.device
159
+
160
+ # 获取最后一个有效 token (跳过 padding)
161
+ pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
162
+ mask = input_ids != pad_token_id
163
+ last_positions = mask.sum(dim=1).clamp(min=1) - 1
164
+ last_tokens = input_ids[torch.arange(batch_size, device=device), last_positions]
165
+
166
+ # 预计算并缓存 delimiter token ids tensor (只执行一次)
167
+ cache_key = '_delimiter_token_tensor'
168
+ if not hasattr(self, cache_key):
169
+ token_ids = self._get_delimiter_token_ids(tokenizer, delimiters)
170
+ setattr(self, cache_key, torch.tensor(list(token_ids), device=device))
171
+
172
+ delimiter_tensor = getattr(self, cache_key)
173
+ is_delimiter = (last_tokens.unsqueeze(1) == delimiter_tensor).any(dim=1)
174
+
175
+ return is_delimiter.unsqueeze(1)
176
+
177
+ def _select_augment_points_after_delimiter(
178
+ self,
179
+ input_ids: torch.Tensor,
180
+ labels: torch.Tensor,
181
+ delimiters: list[str],
182
+ tokenizer: PreTrainedTokenizerBase,
183
+ max_num: int = 10,
184
+ ) -> list[int]:
185
+
186
+ assert input_ids.shape == labels.shape
187
+ B, seq_len = input_ids.size(0), input_ids.size(1)
188
+
189
+ prompt_augment_idx = []
190
+ inference_augment_idx = []
191
+
192
+ for i in range(1, seq_len): # Skip the first token and last token for augmentation
193
+ # Detect the boundary between prompt and label for prompt augmentation
194
+ if (labels[:, i] != -100).all() and (labels[:, i - 1] == -100).all():
195
+ prompt_augment_idx.append(i)
196
+
197
+ # Detect valid label regions for inference augmentation
198
+ elif (labels[:, i] != -100).all() and (labels[:, i - 1] != -100).all():
199
+ batch_tokens_before_i = input_ids[:, :i]
200
+ # Fast token-level check (no decode)
201
+ if self._check_ends_with_delimiter(batch_tokens_before_i, tokenizer, delimiters).any():
202
+ inference_augment_idx.append(i)
203
+
204
+ # Ensure exactly one prompt augmentation point exists for single-turn processing
205
+ if len(prompt_augment_idx) != 1:
206
+ logging.error("❌ Unexpected number of prompt augment indices: %s", prompt_augment_idx)
207
+ logging.error("The inference_augment_idx: %s", inference_augment_idx)
208
+ logging.error("Batch size = %d, seq_len = %d", B, seq_len)
209
+
210
+ for b in range(B):
211
+ ids = input_ids[b].tolist()
212
+ labs = labels[b].tolist()
213
+ toks = tokenizer.convert_ids_to_tokens(ids)
214
+
215
+ logging.error("---- Sample %d ----", b)
216
+ logging.error("Decoded text:\n%s", tokenizer.decode(ids, skip_special_tokens=False))
217
+
218
+ vis = []
219
+ for t, l in zip(toks, labs):
220
+ tag = "MASK" if l == -100 else "LAB"
221
+ vis.append(f"{t}<{tag}>")
222
+
223
+ logging.error("Token-level view:\n%s", " ".join(vis))
224
+
225
+ boundaries = []
226
+ for i in range(1, seq_len):
227
+ if labs[i] != -100 and labs[i - 1] == -100:
228
+ boundaries.append(i)
229
+ logging.error("Detected prompt→label boundaries at positions: %s", boundaries)
230
+ raise ValueError("Single-turn forward must have exactly one prompt augment index")
231
+
232
+ final_points = prompt_augment_idx[:1]
233
+
234
+ # Limit the number of inference augmentation points to max_num
235
+ if len(inference_augment_idx) > max_num:
236
+ inference_augment_idx = inference_augment_idx[:max_num]
237
+
238
+ final_points.extend(inference_augment_idx)
239
+
240
+ if len(final_points) == 0:
241
+ raise RuntimeError("No valid augmentation points found")
242
+
243
+ final_points.sort()
244
+ return final_points
245
+
246
+ @torch.no_grad()
247
+ def _should_augment(
248
+ self,
249
+ input_ids: torch.LongTensor,
250
+ sentence_augment_count: torch.LongTensor,
251
+ do_sample: bool,
252
+ temperature: float,
253
+ is_prompt: bool = False
254
+ ) -> torch.LongTensor:
255
+
256
+ tokenizer = self.tokenizer
257
+ delimiters = self.delimiters
258
+ trigger = self.trigger
259
+ max_augment_num = self.config.max_inference_aug_num
260
+
261
+ batch_size = input_ids.size(0)
262
+
263
+ if is_prompt:
264
+ attention_mask = (input_ids != tokenizer.pad_token_id).long()
265
+ position_ids = self._generate_position_ids(attention_mask)
266
+ aug_vector = torch.zeros((batch_size,), dtype=torch.long, device=input_ids.device)
267
+ trigger_indices = (aug_vector != -100).nonzero(as_tuple=True)[0]
268
+
269
+ else:
270
+ attention_mask = (input_ids != tokenizer.pad_token_id).long()
271
+ position_ids = self._generate_position_ids(attention_mask)
272
+ aug_vector = torch.full((batch_size,), -100, dtype=torch.long, device=input_ids.device)
273
+ ends_with_delimiters = self._check_ends_with_delimiter(input_ids, tokenizer, delimiters).squeeze(1)
274
+ aug_vector[ends_with_delimiters] = 0
275
+ over_limit = (sentence_augment_count >= max_augment_num)
276
+ aug_vector[over_limit] = -100
277
+ trigger_indices = (aug_vector != -100).nonzero(as_tuple=True)[0]
278
+
279
+ if trigger_indices.numel() > 0:
280
+ trigger_logits = trigger(
281
+ input_ids=input_ids[trigger_indices],
282
+ attention_mask=attention_mask[trigger_indices],
283
+ position_ids=position_ids[trigger_indices]
284
+ )
285
+ last_token_logits = trigger_logits[:, -1] # [batch, 2]
286
+
287
+ next_tokens = self._get_next_token(
288
+ last_token_logits,
289
+ do_sample=do_sample,
290
+ temperature=temperature
291
+ ).view(-1)
292
+
293
+ aug_vector[trigger_indices] = next_tokens
294
+
295
+ return aug_vector
296
+
297
+
298
+ @torch.no_grad()
299
+ def _append_one_step(
300
+ self,
301
+ reasoner_outputs,
302
+ current_inputs_embeds: torch.Tensor,
303
+ current_attention_mask: torch.Tensor,
304
+ current_position_ids: torch.Tensor,
305
+ current_input_ids: torch.Tensor,
306
+ do_sample: bool,
307
+ temperature: float
308
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
309
+ B = current_inputs_embeds.size(0)
310
+
311
+ # Append next token
312
+ next_token_logits = reasoner_outputs.logits[:, -1]
313
+ next_token_ids = self._get_next_token(next_token_logits, do_sample=do_sample, temperature=temperature)
314
+ current_input_ids = torch.cat([current_input_ids, next_token_ids], dim=1)
315
+
316
+ # Append next token embeds
317
+ next_token_embeds = self.reasoner.get_input_embeddings()(next_token_ids)
318
+ current_inputs_embeds = torch.cat([current_inputs_embeds, next_token_embeds], dim=1)
319
+
320
+ # Append attention mask
321
+ attn_mask = torch.ones((B, 1), dtype=current_attention_mask.dtype, device=current_attention_mask.device)
322
+ current_attention_mask = torch.cat([current_attention_mask, attn_mask], dim=1)
323
+
324
+ # Append position ids
325
+ next_position_id = current_position_ids[:, -1:] + 1
326
+ current_position_ids = torch.cat([current_position_ids, next_position_id], dim=1)
327
+
328
+ return current_inputs_embeds, current_attention_mask, current_position_ids, current_input_ids
329
+
330
+
331
+ @torch.no_grad()
332
+ def _left_pad(
333
+ self,
334
+ input_embeds: torch.FloatTensor,
335
+ attention_mask: torch.LongTensor,
336
+ position_ids: torch.LongTensor,
337
+ pad_num: int
338
+ ) -> tuple[torch.FloatTensor, torch.LongTensor, torch.LongTensor]:
339
+
340
+ if input_embeds is not None:
341
+ B, L, D = input_embeds.shape
342
+ pad_embeds = torch.zeros((B, pad_num, D), dtype=input_embeds.dtype, device=input_embeds.device)
343
+ input_embeds = torch.cat([pad_embeds, input_embeds], dim=1) # [B, pad_num + L, D]
344
+
345
+ if attention_mask is not None:
346
+ B = attention_mask.size(0)
347
+ pad_mask = torch.zeros((B, pad_num), dtype=attention_mask.dtype, device=attention_mask.device)
348
+ attention_mask = torch.cat([pad_mask, attention_mask], dim=1) # [B, pad_num + L]
349
+
350
+ if position_ids is not None:
351
+ B = position_ids.size(0)
352
+ pad_pos = torch.zeros((B, pad_num), dtype=position_ids.dtype, device=position_ids.device)
353
+ position_ids = torch.cat([pad_pos, position_ids], dim=1) # [B, pad_num + L]
354
+
355
+ return input_embeds, attention_mask, position_ids
356
+
357
+ @torch.no_grad()
358
+ def _left_clip_pad_tokens(
359
+ self, inputs_embeds: torch.FloatTensor, attention_mask: torch.LongTensor, position_ids: torch.LongTensor
360
+ ) -> tuple[torch.FloatTensor, torch.LongTensor, torch.LongTensor]:
361
+
362
+ B, L, D = inputs_embeds.shape
363
+
364
+ # Find the index of the first non-padding token in each sequence
365
+ first_nonpad_idx = []
366
+ for b in range(B):
367
+ nonzero = (attention_mask[b] != 0).nonzero(as_tuple=True)[0]
368
+ if len(nonzero) == 0:
369
+ # Entire row is padding; can potentially trim the whole sequence
370
+ first_nonpad_idx.append(L)
371
+ else:
372
+ first_nonpad_idx.append(nonzero[0].item())
373
+
374
+ # Determine the minimum number of left-padding tokens across the batch
375
+ min_pad = min(first_nonpad_idx)
376
+
377
+ # If no padding on the left, return original tensors
378
+ if min_pad == 0:
379
+ return inputs_embeds, attention_mask, position_ids
380
+
381
+ # Trim the left-padding from all sequences in the batch
382
+ inputs_embeds = inputs_embeds[:, min_pad:, :]
383
+ attention_mask = attention_mask[:, min_pad:]
384
+ position_ids = position_ids[:, min_pad:]
385
+
386
+ return inputs_embeds, attention_mask, position_ids
387
+
388
+ @torch.no_grad()
389
+ def _check_generate(self, input_ids: torch.LongTensor, augmentation_pos: torch.LongTensor):
390
+ """检查 augmentation_pos[b][i] == 1 的位置, input_ids[b][:i] (不包括第 i 位) 对应的字符串是否以 delimiters 结尾
391
+ 仅在 DEBUG_MODE 下启用,避免训练时的性能开销
392
+ """
393
+ # 仅在 DEBUG 模式下执行验证,避免训练时的大量 decode 开销
394
+ if os.environ.get('DEBUG_MODE', '').lower() != 'true':
395
+ return
396
+
397
+ delimiters = self.delimiters
398
+ tokenizer = self.tokenizer
399
+
400
+ B, L = input_ids.shape
401
+ assert augmentation_pos.shape == input_ids.shape
402
+
403
+ for b in range(B):
404
+ for i in range(1, L):
405
+ is_augment_point = augmentation_pos[b, i].item()
406
+
407
+ if is_augment_point == -100:
408
+ continue
409
+
410
+ if is_augment_point == 1 or is_augment_point == 0:
411
+ prefix_input_ids = input_ids[b, :i].unsqueeze(0)
412
+
413
+ ends_with_delimiter = self._check_ends_with_delimiter(
414
+ prefix_input_ids, tokenizer, delimiters
415
+ ).item()
416
+
417
+ if not ends_with_delimiter:
418
+ decoded_prefix = tokenizer.decode(prefix_input_ids.squeeze(0), skip_special_tokens=False)
419
+
420
+ raise ValueError(
421
+ f"Augmentation position error at batch {b}, index {i}. "
422
+ f"augmentation_pos is 1, but the prefix does NOT end with a delimiter.\n"
423
+ f"Prefix: '...{decoded_prefix[-50:]}'\n"
424
+ f"Delimiters: {delimiters}"
425
+ )
426
+ else:
427
+ raise ValueError(
428
+ f"Invalid value in augmentation_pos at batch {b}, index {i}: {is_augment_point}. "
429
+ "Expected 1, 0, or -100."
430
+ )
MemGen-main/memgen/model/trigger.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from peft import PeftModel
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+
6
+ class MemGenTrigger(nn.Module):
7
+ adapter_name = "trigger"
8
+
9
+ def __init__(
10
+ self,
11
+ model: PeftModel,
12
+ active: bool,
13
+ ):
14
+ super().__init__()
15
+
16
+ self.active = active
17
+ self.model = model
18
+ self.output_layer = nn.Linear(model.base_model.config.hidden_size, 2)
19
+
20
+ def forward(
21
+ self,
22
+ input_ids: torch.LongTensor,
23
+ attention_mask: torch.LongTensor,
24
+ position_ids: torch.Tensor
25
+ ) -> torch.FloatTensor:
26
+
27
+ if self.active:
28
+ outputs = self.model(
29
+ input_ids=input_ids,
30
+ attention_mask=attention_mask,
31
+ position_ids=position_ids,
32
+ output_hidden_states=True,
33
+ )
34
+ hidden_states = outputs.hidden_states[-1]
35
+ logits = self.output_layer(hidden_states)
36
+
37
+ else:
38
+ batch_size, seq_len = input_ids.shape
39
+ logits = torch.zeros(batch_size, seq_len, 2, device=input_ids.device) # logits: [batch_size, seq_len, 2]
40
+ logits[..., 1] = 1.0
41
+
42
+ return logits
43
+
44
+
45
+
MemGen-main/memgen/model/weaver.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from peft import PeftModel
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+
6
+ class MemGenWeaver(nn.Module):
7
+
8
+ adapter_name = "weaver"
9
+
10
+ def __init__(
11
+ self,
12
+ model: PeftModel,
13
+ prompt_latents_len: int,
14
+ inference_latents_len: int,
15
+ ):
16
+ super().__init__()
17
+
18
+ self.model = model
19
+ hidden_size = model.base_model.config.hidden_size
20
+
21
+ # prompt augmentation
22
+ self.prompt_query_latents = nn.Parameter(
23
+ torch.randn(prompt_latents_len, hidden_size),
24
+ requires_grad=True
25
+ )
26
+
27
+ # inference augmentation
28
+ self.inference_query_latents = nn.Parameter(
29
+ torch.randn(inference_latents_len, hidden_size),
30
+ requires_grad=True
31
+ )
32
+
33
+ # latent normalization + scale
34
+ self.prompt_latent_ln = nn.LayerNorm(hidden_size)
35
+ self.inference_latent_ln = nn.LayerNorm(hidden_size)
36
+ self.prompt_latent_scale = nn.Parameter(torch.ones(1))
37
+ self.inference_latent_scale = nn.Parameter(torch.ones(1))
38
+
39
+ @property
40
+ def prompt_latents_num(self) -> int:
41
+ return self.prompt_query_latents.size(0)
42
+
43
+ @property
44
+ def inference_latents_num(self) -> int:
45
+ return self.inference_query_latents.size(0)
46
+
47
+ @property
48
+ def device(self):
49
+ assert self.prompt_query_latents.device == self.inference_query_latents.device
50
+ return self.prompt_query_latents.device
51
+
52
+ def _augment(
53
+ self,
54
+ latents: torch.Tensor,
55
+ latent_ln: nn.LayerNorm,
56
+ latent_scale: torch.Tensor,
57
+ inputs_embeds: torch.Tensor,
58
+ attention_mask: torch.Tensor,
59
+ position_ids: torch.Tensor
60
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
61
+
62
+ batch_size = attention_mask.shape[0]
63
+ latents_num = latents.size(0)
64
+
65
+ # normalize + scale
66
+ latents = latent_ln(latents) * latent_scale
67
+ latents = latents.unsqueeze(0).repeat(batch_size, 1, 1)
68
+
69
+ # inputs_embeds
70
+ inputs_embeds = torch.cat([inputs_embeds, latents], dim=1)
71
+
72
+ # attention_mask: (B, L_total)
73
+ latents_mask = torch.ones(latents.shape[:-1], dtype=attention_mask.dtype, device=attention_mask.device)
74
+ attention_mask = torch.cat([attention_mask, latents_mask], dim=1)
75
+
76
+ # get position ids
77
+ last_position_ids = position_ids.max(dim=1)[0]
78
+ latents_relative_positions = torch.arange(latents_num, device=attention_mask.device)
79
+ latents_position_ids = last_position_ids.unsqueeze(1) + latents_relative_positions + 1
80
+ position_ids = torch.cat([position_ids.long(), latents_position_ids.long()], dim=1)
81
+
82
+ # the processor only outputs the hidden states
83
+ assert inputs_embeds.shape[:2] == attention_mask.shape == position_ids.shape
84
+
85
+ outputs = self.model(
86
+ inputs_embeds=inputs_embeds,
87
+ attention_mask=attention_mask,
88
+ position_ids=position_ids,
89
+ output_hidden_states=True,
90
+ )
91
+ hidden_states = outputs.hidden_states[-1]
92
+ latents_hidden_states = hidden_states[:, -latents_num:, :]
93
+
94
+ return latents_hidden_states, latents_mask, latents_position_ids
95
+
96
+ def augment_prompt(
97
+ self,
98
+ inputs_embeds: torch.Tensor,
99
+ attention_mask: torch.Tensor,
100
+ position_ids: torch.Tensor
101
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
102
+ return self._augment(
103
+ latents=self.prompt_query_latents,
104
+ latent_ln=self.prompt_latent_ln,
105
+ latent_scale=self.prompt_latent_scale,
106
+ inputs_embeds=inputs_embeds,
107
+ attention_mask=attention_mask,
108
+ position_ids=position_ids
109
+ )
110
+
111
+
112
+ def augment_inference(
113
+ self,
114
+ inputs_embeds: torch.Tensor,
115
+ attention_mask: torch.Tensor,
116
+ position_ids: torch.Tensor
117
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
118
+ return self._augment(
119
+ latents=self.inference_query_latents,
120
+ latent_ln=self.inference_latent_ln,
121
+ latent_scale=self.inference_latent_scale,
122
+ inputs_embeds=inputs_embeds,
123
+ attention_mask=attention_mask,
124
+ position_ids=position_ids
125
+ )
MemGen-main/memgen/runner.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+
4
+ from accelerate import Accelerator
5
+ from datasets import Dataset
6
+ import torch
7
+ from torch.utils.data import DataLoader
8
+ from tqdm import tqdm
9
+ from trl import SFTTrainer, SFTConfig, GRPOConfig
10
+ from trl.models import unwrap_model_for_generation
11
+
12
+ from data import (
13
+ BaseBuilder,
14
+ )
15
+ from interactions.base_interaction import (
16
+ InteractionConfig,
17
+ InteractionManager,
18
+ InteractionDataProto
19
+ )
20
+ from interactions.singleturn_interaction import SingleTurnInteractionManager
21
+ from interactions.multiturn_interaction import MultiTurnInteractionManager
22
+
23
+ from memgen.model.modeling_memgen import MemGenModel
24
+ from memgen.trainer.weaver_grpo_trainer import WeaverGRPOTrainer
25
+ from memgen.trainer.trigger_grpo_trainer import TriggerGRPOTrainer
26
+ from memgen.utils import (
27
+ StaticEvalRecorder,
28
+ DynamicEvalRecorder,
29
+ create_tensorboard,
30
+ log_trainable_params,
31
+ gather_objects
32
+ )
33
+
34
+
35
+ class MemGenRunner:
36
+
37
+ def __init__(
38
+ self,
39
+ model: MemGenModel,
40
+ data_builder: BaseBuilder,
41
+ config: dict,
42
+ working_dir: str,
43
+ ):
44
+ # parse configs
45
+ self.config = config
46
+ self.working_dir = working_dir
47
+
48
+ self._parse_configs(config.get("run"))
49
+
50
+ # parse model
51
+ self.processing_class = model.tokenizer
52
+ self.model = model
53
+
54
+ # initialize envs and generation managers
55
+ self.dataset_dict = data_builder.get_dataset_dict()
56
+ self.env_cls = data_builder.get_env_cls()
57
+ self.env = self.env_cls(config.get("dataset"))
58
+
59
+ # partition datasets
60
+ self.weaver_train_dataset, self.trigger_train_dataset = self._parse_train_dataset(self.dataset_dict["train"])
61
+ self.weaver_valid_dataset, self.trigger_valid_dataset = self._parse_valid_dataset(self.dataset_dict["valid"])
62
+ self.test_dataset = self.dataset_dict["test"]
63
+
64
+ self.weaver_train_dataset = self._filter_dataset(self.weaver_train_dataset)
65
+ self.trigger_train_dataset = self._filter_dataset(self.trigger_train_dataset)
66
+ self.weaver_valid_dataset = self._filter_dataset(self.weaver_valid_dataset)
67
+ self.trigger_valid_dataset = self._filter_dataset(self.trigger_valid_dataset)
68
+
69
+ # initialize generation manager
70
+ if self.env_cls.ENV_CARD == "STATIC":
71
+ self.inter_cls = SingleTurnInteractionManager
72
+ elif self.env_cls.ENV_CARD == "DYNAMIC":
73
+ self.inter_cls = MultiTurnInteractionManager
74
+ else:
75
+ raise ValueError("Unsupported environment type.")
76
+
77
+ self.generation_manager: InteractionManager = self.inter_cls(
78
+ self.processing_class, self.model, self.interaction_config
79
+ )
80
+
81
+ def _parse_train_dataset(self, train_dataset: Dataset) -> tuple[Dataset, Dataset]:
82
+ # use half size of the datatset to train the trigger
83
+ trigger_trainset_size = min(len(train_dataset) // 3, len(train_dataset))
84
+ rand_indices = random.sample(range(len(train_dataset)), trigger_trainset_size)
85
+ return train_dataset, train_dataset.select(rand_indices)
86
+
87
+ def _parse_valid_dataset(self, valid_dataset: Dataset) -> tuple[Dataset, Dataset]:
88
+
89
+ trigger_validset_size = min(len(valid_dataset) // 3, len(valid_dataset))
90
+ rand_indices = random.sample(range(len(valid_dataset)), trigger_validset_size)
91
+ return valid_dataset, valid_dataset.select(rand_indices)
92
+
93
+ def _filter_dataset(self, dataset: Dataset) -> Dataset:
94
+ tokenizer = self.processing_class
95
+
96
+ # Determine max length based on training mode
97
+ max_len = 1024
98
+ if self.train_weaver and self.train_weaver_method == "sft":
99
+ max_len = self.weaver_sft_training_args.max_length
100
+ elif self.train_weaver and self.train_weaver_method == "grpo":
101
+ max_len = self.weaver_grpo_training_args.max_prompt_length
102
+ elif self.train_trigger and self.train_trigger_method == "grpo":
103
+ max_len = self.trigger_grpo_training_args.max_prompt_length
104
+ else:
105
+ raise ValueError("Wrong training mode.")
106
+
107
+ # Function to filter out samples exceeding max length
108
+ def filter_func(sample):
109
+ if "prompt" in sample and sample["prompt"] is not None:
110
+ prompt = tokenizer.apply_chat_template(sample["prompt"], tokenize=True)
111
+ return len(prompt) < max_len
112
+ elif "messages" in sample and sample["messages"] is not None:
113
+ conversation = tokenizer.apply_chat_template(sample["messages"][:2], tokenize=True)
114
+ return len(conversation) < max_len
115
+ return True
116
+
117
+ # Apply filtering
118
+ dataset = dataset.filter(filter_func)
119
+
120
+ return dataset
121
+
122
+ # ===== train weaver =====
123
+ def _create_weaver_trainer(self):
124
+
125
+ # SFT Trainer
126
+ if self.train_weaver_method == "sft":
127
+
128
+ weaver_trainer = SFTTrainer(
129
+ model=self.model,
130
+ args=self.weaver_sft_training_args,
131
+ train_dataset=self.weaver_train_dataset,
132
+ eval_dataset=self.weaver_valid_dataset,
133
+ processing_class=self.processing_class,
134
+ )
135
+
136
+ # GRPO Trainer
137
+ elif self.train_weaver_method == 'grpo':
138
+ self.weaver_grpo_training_args.do_eval = False
139
+ self.weaver_grpo_training_args.eval_strategy = 'no'
140
+ self.generation_manager.generation_config.weaver_do_sample = True
141
+ self.generation_manager.generation_config.trigger_do_sample = False
142
+ self.generation_manager.generation_config.temperature = self.weaver_grpo_training_args.temperature
143
+ self.generation_manager.generation_config.max_new_tokens = self.weaver_grpo_training_args.max_completion_length
144
+
145
+ # self.weaver_train_dataset = self.weaver_train_dataset.select(range(1600))
146
+
147
+ weaver_trainer = WeaverGRPOTrainer(
148
+ model=self.model,
149
+ reward_funcs=[self.env_cls.compute_reward],
150
+ args=self.weaver_grpo_training_args,
151
+ train_dataset=self.weaver_train_dataset,
152
+ eval_dataset=self.weaver_valid_dataset,
153
+ processing_class=self.processing_class,
154
+ # --- add env into trainer ---
155
+ env_class=self.env_cls,
156
+ env_main_config=self.config.get("dataset"),
157
+ generation_manager=self.generation_manager,
158
+ )
159
+ else:
160
+ raise ValueError("Unsupported weaver training method.")
161
+
162
+ return weaver_trainer
163
+
164
+ # ===== train trigger =====
165
+ def _create_trigger_trainer(self):
166
+
167
+ if self.train_trigger_method == "grpo":
168
+ self.trigger_grpo_training_args.do_eval = False
169
+ self.trigger_grpo_training_args.eval_strategy = 'no'
170
+
171
+ self.generation_manager.generation_config.trigger_do_sample = True
172
+ self.generation_manager.generation_config.weaver_do_sample = False
173
+ self.generation_manager.generation_config.temperature = self.weaver_grpo_training_args.temperature
174
+ self.generation_manager.generation_config.max_new_tokens = self.weaver_grpo_training_args.max_completion_length
175
+
176
+ trigger_trainer = TriggerGRPOTrainer(
177
+ model=self.model,
178
+ processing_class=self.processing_class,
179
+ train_dataset=self.trigger_train_dataset,
180
+ eval_dataset=self.trigger_valid_dataset,
181
+ reward_funcs=[self.env_cls.compute_reward],
182
+ args=self.trigger_grpo_training_args
183
+ )
184
+ else:
185
+ raise ValueError("Unsupported trigger training method.")
186
+
187
+ return trigger_trainer
188
+
189
+ # ===== train weaver/trigger =====
190
+ def train(self):
191
+
192
+ if self.train_weaver:
193
+ trainer = self._create_weaver_trainer()
194
+ self.model.fix_component('trigger')
195
+
196
+ if self.train_trigger:
197
+ trainer = self._create_trigger_trainer()
198
+ self.model.fix_component('weaver')
199
+
200
+ log_trainable_params(self.model)
201
+
202
+ try:
203
+ trainer.train()
204
+ trainer.save_model()
205
+ except RuntimeError as e:
206
+ # 检查是否是 OOM 相关的错误
207
+ if "OOM" in str(e) or "out of memory" in str(e).lower():
208
+ logging.error(f"[Runner] Training stopped due to OOM: {e}")
209
+ # 尝试最后一次保存
210
+ try:
211
+ oom_dir = os.path.join(self.working_dir, "model_oom_final")
212
+ logging.info(f"[Runner] Attempting to save final checkpoint to {oom_dir}")
213
+ trainer.save_model(oom_dir)
214
+ logging.info(f"[Runner] Final checkpoint saved successfully")
215
+ except Exception as save_e:
216
+ logging.error(f"[Runner] Failed to save final checkpoint: {save_e}")
217
+ raise
218
+ else:
219
+ # 非 OOM 错误,直接抛出
220
+ raise
221
+
222
+
223
+ # ===== evaluate =====
224
+ def evaluate(self):
225
+ self.model = self.model.to(torch.bfloat16)
226
+
227
+ evaluate_func_mapping = {
228
+ "STATIC": self._static_evaluate,
229
+ "DYNAMIC": self._dynamic_evaluate
230
+ }
231
+ evaluate_func = evaluate_func_mapping.get(self.env.ENV_CARD)
232
+ if evaluate_func is None:
233
+ raise ValueError("The env has unrecogonized ENV_CARD attribute")
234
+
235
+ return evaluate_func()
236
+
237
+ def _static_evaluate(self):
238
+
239
+ accelerator = Accelerator()
240
+
241
+ if accelerator.is_main_process:
242
+ writer = create_tensorboard(save_dir=self.working_dir)
243
+ save_file = os.path.join(self.interaction_config.output_dir, "answer.json")
244
+ recorder = StaticEvalRecorder(
245
+ compute_metrics=[self.env_cls.compute_reward],
246
+ writer=writer,
247
+ log_file=save_file
248
+ )
249
+ else:
250
+ writer = None
251
+ recorder = None
252
+
253
+ batch_size = self.interaction_config.batch_size
254
+
255
+ test_dataloader = accelerator.prepare(DataLoader(
256
+ dataset=self.test_dataset,
257
+ batch_size=batch_size,
258
+ shuffle=False,
259
+ collate_fn=lambda batch: batch
260
+ ))
261
+
262
+ model_wrapped = accelerator.prepare_model(model=self.model, evaluation_mode=True)
263
+ model_wrapped.eval()
264
+
265
+ for test_batch in tqdm(test_dataloader, disable=not accelerator.is_main_process):
266
+ with unwrap_model_for_generation(model_wrapped, accelerator) as unwrapped_model:
267
+ prompts = [x["prompt"] for x in test_batch]
268
+ prompt_inputs = self.processing_class.apply_chat_template(
269
+ prompts,
270
+ add_generation_prompt=True,
271
+ return_tensors="pt",
272
+ padding=True,
273
+ padding_side="left",
274
+ add_special_tokens=True,
275
+ return_dict=True
276
+ )
277
+ prompt_ids, prompt_mask = prompt_inputs["input_ids"], prompt_inputs["attention_mask"]
278
+ gen_batch = InteractionDataProto()
279
+ gen_batch.batch["input_ids"] = prompt_ids.to(accelerator.device)
280
+ gen_batch.batch["attention_mask"] = prompt_mask.to(accelerator.device)
281
+ gen_batch.no_tensor_batch["initial_prompts"] = prompts
282
+
283
+ self.generation_manager.actor_rollout_wg = unwrapped_model
284
+ gen_output = self.generation_manager.run_agent_loop(gen_batch)
285
+
286
+ completion_ids = gen_output.batch["responses"]
287
+ completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
288
+
289
+ # only main rank can write the json
290
+ local_completions = completions
291
+ local_batches = test_batch
292
+
293
+ all_completions = gather_objects(local_completions)
294
+ all_batches = gather_objects(local_batches)
295
+
296
+ if accelerator.is_main_process:
297
+ for comps, batch in zip(all_completions, all_batches):
298
+ recorder.record_batch(comps, batch)
299
+
300
+ accelerator.wait_for_everyone()
301
+
302
+ if accelerator.is_main_process:
303
+ recorder.finalize()
304
+ writer.close()
305
+
306
+ def _dynamic_evaluate(self):
307
+
308
+ def _set_batch_envs(batch: list) -> tuple[list[str], list[str], list]: # batch set envs
309
+ system_prompts, init_user_prompts, envs = [], [], []
310
+ for task_config in batch:
311
+ env = self.env_cls(self.config.get("dataset"))
312
+ system_prompt, init_user_prompt = env.set_env(task_config)
313
+
314
+ system_prompts.append(system_prompt)
315
+ init_user_prompts.append(init_user_prompt)
316
+ envs.append(env)
317
+
318
+ return system_prompts, init_user_prompts, envs
319
+
320
+ def _build_data_proto(
321
+ system_prompts: list[str], init_user_prompts: list[str], envs: list
322
+ ) -> InteractionDataProto:
323
+ messages = []
324
+ for system_prmopt, init_user_prompt in zip(system_prompts, init_user_prompts):
325
+ system_message = {"role": "system", "content": system_prmopt}
326
+ user_message = {"role": "user", "content": init_user_prompt}
327
+ init_messages = [system_message, user_message]
328
+ messages.append(init_messages)
329
+
330
+ data_proto = InteractionDataProto()
331
+ data_proto.no_tensor_batch["init_prompts"] = messages
332
+ data_proto.no_tensor_batch["envs"] = envs
333
+
334
+ return data_proto
335
+
336
+ # ===== body =====
337
+ accelerator = Accelerator()
338
+
339
+ if accelerator.is_main_process:
340
+ writer = create_tensorboard(save_dir=self.working_dir)
341
+ save_file = os.path.join(self.interaction_config.output_dir, "conversations.txt")
342
+ recorder = DynamicEvalRecorder(writer=writer, log_file=save_file)
343
+ else:
344
+ writer = None
345
+ recorder = None
346
+
347
+ batch_size = self.interaction_config.batch_size
348
+
349
+ # prepare dataset and dataloader
350
+ test_dataloader = accelerator.prepare(DataLoader(
351
+ dataset=self.test_dataset,
352
+ batch_size=batch_size,
353
+ shuffle=False,
354
+ collate_fn=lambda batch: batch # use the identity function
355
+ ))
356
+
357
+ # prepare model
358
+ model_wrapped = accelerator.prepare_model(model=self.model, evaluation_mode=True)
359
+ model_wrapped.eval()
360
+
361
+ # batch generate
362
+ for step, test_batch in tqdm(enumerate(test_dataloader), desc="Evaluation"):
363
+ with unwrap_model_for_generation(
364
+ model_wrapped, accelerator
365
+ ) as unwrapped_model:
366
+ system_prompts, init_user_prompts, envs = _set_batch_envs(test_batch)
367
+ input_data_proto = _build_data_proto(system_prompts, init_user_prompts, envs)
368
+
369
+ self.generation_manager.actor_rollout_wg = unwrapped_model
370
+ outputs: InteractionDataProto = self.generation_manager.run_agent_loop(input_data_proto)
371
+
372
+ inter_histories = outputs.no_tensor_batch["inter_histories"]
373
+ inter_context = self.processing_class.apply_chat_template(inter_histories, tokenize=False)
374
+
375
+ # calculate batch rewards
376
+ rewards = []
377
+ for env in input_data_proto.no_tensor_batch["envs"]:
378
+ reward = env.feedback()
379
+ rewards.append(reward)
380
+
381
+ all_contexts = gather_objects(inter_context)
382
+ all_rewards = gather_objects(rewards)
383
+
384
+ if accelerator.is_main_process:
385
+ for conts, rs in zip(all_contexts, all_rewards):
386
+ recorder.record_batch(conts, rs)
387
+
388
+ accelerator.wait_for_everyone()
389
+
390
+ if accelerator.is_main_process:
391
+ recorder.finalize()
392
+ writer.close()
393
+
394
+ def _parse_configs(self, configs):
395
+
396
+ self.train_weaver = configs.get("train_weaver", True)
397
+ self.train_trigger = configs.get("train_trigger", False)
398
+
399
+ # --- Parse weaver training args ---
400
+ self.train_weaver_method = configs.get("train_weaver_method", "sft")
401
+ if self.train_weaver_method not in ["sft", "grpo"]:
402
+ raise ValueError("Unsupported weaver training method.")
403
+
404
+ # parse weaver sft training args
405
+ weaver_config = configs.get("weaver", dict())
406
+ weaver_sft_config = weaver_config.get("sft", dict())
407
+ self.weaver_sft_training_args = SFTConfig(**weaver_sft_config)
408
+
409
+ # parse weaver grpo training args
410
+ weaver_grpo_config = weaver_config.get("grpo", dict())
411
+ self.weaver_grpo_training_args = GRPOConfig(**weaver_grpo_config)
412
+
413
+ # --- Parse trigger training args ---
414
+ trigger_config = configs.get("trigger", dict())
415
+ self.train_trigger_method = configs.get("train_trigger_method", "grpo")
416
+ if self.train_trigger_method not in ["grpo"]:
417
+ raise ValueError("Unsupported trigger training method.")
418
+
419
+ trigger_grpo_config = trigger_config.get("grpo", dict())
420
+ self.trigger_grpo_training_args = GRPOConfig(**trigger_grpo_config)
421
+
422
+ # --- update training args ---
423
+ updated_args = {
424
+ "output_dir": os.path.join(self.working_dir, "model"),
425
+ "logging_dir": os.path.join(self.working_dir, "run"),
426
+ "save_strategy": "no"
427
+ }
428
+ for k, v in updated_args.items():
429
+ setattr(self.weaver_sft_training_args, k, v)
430
+ setattr(self.weaver_grpo_training_args, k, v)
431
+ setattr(self.trigger_grpo_training_args, k, v)
432
+
433
+ # --- parse interaction args ---
434
+ interaction_configs = configs.get("interaction", {})
435
+ self.interaction_config = InteractionConfig(
436
+ max_turns=interaction_configs.get("max_turns", 30),
437
+ max_start_length=interaction_configs.get("max_start_length", 1024),
438
+ max_prompt_length=interaction_configs.get("max_prompt_length", 4096),
439
+ max_response_length=interaction_configs.get("max_response_length", 512),
440
+ max_obs_length=interaction_configs.get("max_obs_length", 512),
441
+ temperature=interaction_configs.get("temperature", 0.0),
442
+ batch_size=interaction_configs.get("batch_size", 32),
443
+ output_dir=os.path.join(self.working_dir, "evaluate"),
444
+ weaver_do_sample=interaction_configs.get("weaver_do_sample", False),
445
+ trigger_do_sample=interaction_configs.get("trigger_do_sample", False),
446
+ )
MemGen-main/memgen/trainer/__init__.py ADDED
File without changes
MemGen-main/memgen/trainer/trigger_grpo_trainer.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from trl import GRPOTrainer, GRPOConfig
2
+ from trl.data_utils import maybe_apply_chat_template
3
+ from trl.models import unwrap_model_for_generation, create_reference_model
4
+ from trl.trainer.utils import selective_log_softmax
5
+ from transformers import (
6
+ PreTrainedModel,
7
+ PreTrainedTokenizerBase,
8
+ TrainerCallback
9
+ )
10
+ from peft import PeftConfig
11
+
12
+ from typing import Union, Callable, Optional, Any
13
+ from contextlib import nullcontext
14
+ import torch
15
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
16
+ from torch.utils.data import Dataset
17
+ from accelerate.utils import gather_object
18
+
19
+ from interactions.base_interaction import InteractionDataProto
20
+ from interactions.tensor_utils import TensorHelper, TensorConfig
21
+
22
+ from memgen.trainer.utils import (
23
+ nanstd,
24
+ nanmax,
25
+ nanmin,
26
+ generate_position_ids
27
+ )
28
+ from memgen.model.modeling_memgen import MemGenModel
29
+
30
+ RewardFunc = Union[str, PreTrainedModel, Callable[[list, list], list[float]]]
31
+
32
+ class TriggerGRPOTrainer(GRPOTrainer):
33
+ def __init__(
34
+ self,
35
+ model: MemGenModel,
36
+ processing_class: PreTrainedTokenizerBase,
37
+ train_dataset: Dataset,
38
+ eval_dataset: Dataset,
39
+ reward_funcs: Union[RewardFunc, list[RewardFunc]],
40
+ reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None,
41
+ args: Optional[GRPOConfig] = None,
42
+ callbacks: Optional[list[TrainerCallback]] = None,
43
+ optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
44
+ peft_config: Optional[PeftConfig] = None,
45
+ ):
46
+ # NOTE - Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
47
+ # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
48
+ # self.model_accepts_loss_kwargs to False to enable scaling.
49
+ self.model_accepts_loss_kwargs = False
50
+
51
+ super().__init__(
52
+ model=model,
53
+ args=args,
54
+ reward_funcs=reward_funcs,
55
+ reward_processing_classes=reward_processing_classes,
56
+ train_dataset=train_dataset,
57
+ eval_dataset=eval_dataset,
58
+ processing_class=processing_class,
59
+ callbacks=callbacks,
60
+ optimizers=optimizers,
61
+ peft_config=peft_config
62
+ )
63
+
64
+ # If PEFT configuration is not provided, create a reference model based on the initial model.
65
+ ref_model = create_reference_model(model.trigger)
66
+ self.ref_model = self.accelerator.prepare_model(ref_model, evaluation_mode=True)
67
+ self.tensor_fn = TensorHelper(TensorConfig(
68
+ pad_token_id=self.processing_class.pad_token_id,
69
+ max_prompt_length=self.max_prompt_length,
70
+ max_obs_length=None,
71
+ max_start_length=None
72
+ ))
73
+
74
+ def _set_signature_columns_if_needed(self):
75
+ # NOTE - If `self.args.remove_unused_columns` is True, non-signature columns are removed.
76
+ # By default, this method sets `self._signature_columns` to the model's expected inputs.
77
+ # In LatentProcessorSFTTrainer, we preprocess data, so using the model's signature columns doesn't work.
78
+ # Instead, we set them to the columns expected by the `training_step` method, hence the override.
79
+ pass
80
+
81
+ def _get_per_token_logps(
82
+ self,
83
+ model,
84
+ input_ids: torch.LongTensor,
85
+ attention_mask: torch.LongTensor,
86
+ augmentation_mask: torch.LongTensor
87
+ ) -> torch.Tensor:
88
+ prompt_len = attention_mask.size(1) - augmentation_mask.size(1)
89
+
90
+ assert input_ids.shape == attention_mask.shape
91
+ position_ids = generate_position_ids(attention_mask)
92
+ augmentation_logits = model.trigger(
93
+ input_ids=input_ids,
94
+ attention_mask=attention_mask,
95
+ position_ids=position_ids
96
+ )
97
+ clipped_logits = augmentation_logits[:, prompt_len - 1 : -1]
98
+ assert clipped_logits.shape[:-1] == augmentation_mask.shape
99
+
100
+ temp_mask = augmentation_mask.clone()
101
+ augmentation_valid_mask = (temp_mask == -100).clone()
102
+
103
+ temp_mask[augmentation_valid_mask] = 0
104
+ logps = selective_log_softmax(clipped_logits, temp_mask)
105
+ logps[augmentation_valid_mask] = 0
106
+
107
+ return logps
108
+
109
+ def _generate_and_score_completions(
110
+ self, inputs: list[dict[str, Union[torch.Tensor, Any]]]
111
+ ) -> dict[str, Union[torch.Tensor, Any]]:
112
+
113
+ device = self.accelerator.device
114
+ mode = "train" if self.model.training else "eval"
115
+
116
+ prompts = [x["prompt"] for x in inputs]
117
+ invalid_augmentation_id = -100
118
+
119
+ # modified: pop those keys for generation
120
+ batch_gen_keys = []
121
+ if "prompt" in inputs[0]: # text-based raw prompt
122
+ batch_gen_keys.append("prompt")
123
+ if "tools_kwargs" in inputs[0]: # tool-integrated
124
+ batch_gen_keys.append("tools_kwargs")
125
+ if "interaction_kwargs" in inputs[0]: # interaction args
126
+ batch_gen_keys.append("interaction_kwargs")
127
+ if "agent_name" in inputs[0]: # agent name
128
+ batch_gen_keys.append("agent_name")
129
+ if "env" in inputs[0]:
130
+ batch_gen_keys.append("env")
131
+
132
+ # build generation batch
133
+ gen_batch = InteractionDataProto()
134
+ for key in batch_gen_keys:
135
+ gen_batch.no_tensor_batch[key] = [x[key] for x in inputs]
136
+
137
+ prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
138
+ prompt_inputs = self.processing_class(
139
+ text=prompts_text, return_tensors="pt", padding=True, padding_side="left", add_special_tokens=False
140
+ )
141
+
142
+ prompt_ids, prompt_mask = prompt_inputs["input_ids"], prompt_inputs["attention_mask"]
143
+ if self.max_prompt_length is not None:
144
+ prompt_ids = prompt_ids[:, -self.max_prompt_length :]
145
+ prompt_mask = prompt_mask[:, -self.max_prompt_length :]
146
+
147
+ gen_batch.batch["input_ids"] = prompt_ids.to(device)
148
+ gen_batch.batch["attention_mask"] = prompt_mask.to(device)
149
+
150
+ # Regular generation path
151
+ with unwrap_model_for_generation(
152
+ self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
153
+ ) as unwrapped_model:
154
+ with (
155
+ FSDP.summon_full_params(self.model_wrapped, recurse=False)
156
+ if self.is_fsdp_enabled
157
+ else nullcontext()
158
+ ):
159
+ prompt_ids = gen_batch.batch["input_ids"]
160
+ prompt_mask = gen_batch.batch["attention_mask"]
161
+ prompt_completion_ids, augmentation_mask = unwrapped_model.generate(
162
+ prompt_ids, prompt_mask, generation_config=self.generation_config, return_augmentation_mask=True
163
+ )
164
+ # Compute prompt length and extract completion ids
165
+ prompt_length = prompt_ids.size(1)
166
+ prompt_ids = prompt_completion_ids[:, :prompt_length]
167
+ completion_ids = prompt_completion_ids[:, prompt_length:]
168
+ assert completion_ids.shape == augmentation_mask.shape
169
+
170
+ # Mask everything after the first EOS token
171
+ is_eos = completion_ids == self.processing_class.eos_token_id
172
+ eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
173
+ eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
174
+ sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
175
+ completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
176
+ completion_ids = torch.where(
177
+ completion_mask.bool(),
178
+ completion_ids,
179
+ torch.full_like(completion_ids, self.processing_class.eos_token_id)
180
+ )
181
+
182
+ augmentation_valid_mask = completion_mask * (augmentation_mask != invalid_augmentation_id)
183
+ augmentation_mask = torch.where(
184
+ augmentation_valid_mask.bool(),
185
+ augmentation_mask,
186
+ torch.full_like(augmentation_mask, invalid_augmentation_id)
187
+ )
188
+
189
+ # If a truncation-based output strategy is used,
190
+ # then for any sequence that has not generated an EOS token, its loss will be ignored during computation.
191
+ if self.mask_truncated_completions:
192
+ truncated_completions = ~is_eos.any(dim=1)
193
+ completion_mask = completion_mask * (~truncated_completions).unsqueeze(1).int()
194
+
195
+ # Concatenate prompt_mask with completion_mask for logit computation
196
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P + C)
197
+
198
+ with torch.no_grad():
199
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
200
+ # old_per_token_logps == per_token_logps, so we can skip it's computation here, and use
201
+ # per_token_logps.detach() instead.
202
+ if self.num_iterations > 1 or self.args.steps_per_generation > self.args.gradient_accumulation_steps:
203
+ old_per_token_logps = self._get_per_token_logps(
204
+ self.model.trigger, prompt_completion_ids, attention_mask, augmentation_mask
205
+ )
206
+ else:
207
+ old_per_token_logps = None
208
+
209
+ # Compute the per-token log probabilities for the reference model
210
+ if self.beta != 0.0:
211
+ if self.ref_model is not None:
212
+ ref_per_token_logps = self._get_per_token_logps(
213
+ self.ref_model, prompt_completion_ids, attention_mask, augmentation_mask
214
+ )
215
+ else:
216
+ with self.accelerator.unwrap_model(self.model).disable_adapter():
217
+ ref_per_token_logps = self._get_per_token_logps(
218
+ self.model.trigger, prompt_completion_ids, attention_mask, augmentation_mask
219
+ )
220
+ else:
221
+ ref_per_token_logps = None
222
+
223
+ # Decode the generated completions
224
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
225
+ completions = completions_text
226
+
227
+ for i in range(len(inputs)):
228
+ inputs[i]["augmentation_mask"] = augmentation_mask[i]
229
+
230
+ # Convert tensor to a list of lists of token IDs. This will be passed to the reward function, avoiding the need
231
+ # to re-tokenize completions if the reward is computed from tokens.
232
+ completion_ids_list = [
233
+ [id.item() for id, m in zip(row, mask_row) if m] for row, mask_row in zip(completion_ids, completion_mask)
234
+ ]
235
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
236
+
237
+ # Apply weights to each reward function's output and sum
238
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
239
+
240
+ # Compute grouped-wise rewards
241
+ mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
242
+ std_grouped_rewards = rewards.view(-1, self.num_generations).std(dim=1)
243
+ is_std_zero = torch.isclose(std_grouped_rewards, torch.zeros_like(std_grouped_rewards))
244
+
245
+ # Normalize the rewards to compute the advantages
246
+ mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
247
+ std_grouped_rewards = std_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
248
+ advantages = rewards - mean_grouped_rewards
249
+ if self.scale_rewards:
250
+ advantages = advantages / (std_grouped_rewards + 1e-4)
251
+
252
+ # Slice to keep only the local part of the data
253
+ process_slice = slice(
254
+ self.accelerator.process_index * len(prompts),
255
+ (self.accelerator.process_index + 1) * len(prompts),
256
+ )
257
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
258
+ advantages = advantages[process_slice]
259
+
260
+ # Log the metrics
261
+ if mode == "train":
262
+ self.state.num_input_tokens_seen += self.accelerator.gather(attention_mask.sum()).sum().item()
263
+ self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
264
+
265
+ # Log completion lengths, mean, min, max
266
+ completion_lengths = completion_mask.sum(1)
267
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
268
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
269
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
270
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
271
+
272
+ # Log augmentation lengths, mean, min, max
273
+ augmentation_lengths = (augmentation_mask == 1).sum(dim=1)
274
+ agg_augmentation_lengths = self.accelerator.gather(augmentation_lengths)
275
+ self._metrics[mode]["augmentations/mean_length"].append(agg_augmentation_lengths.float().mean().item())
276
+ self._metrics[mode]["augmentations/min_length"].append(agg_augmentation_lengths.float().min().item())
277
+ self._metrics[mode]["augmentations/max_length"].append(agg_augmentation_lengths.float().max().item())
278
+
279
+ # Identify sequences that terminated with EOS and log their lengths
280
+ agg_terminated_with_eos = self.accelerator.gather(is_eos.any(dim=1))
281
+ term_completion_lengths = agg_completion_lengths[agg_terminated_with_eos]
282
+ clipped_completions_ratio = 1 - len(term_completion_lengths) / len(agg_completion_lengths)
283
+ self._metrics[mode]["completions/clipped_ratio"].append(clipped_completions_ratio)
284
+ if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found
285
+ term_completion_lengths = torch.zeros(1, device=device)
286
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
287
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
288
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
289
+
290
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
291
+ for i, reward_func_name in enumerate(self.reward_func_names):
292
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
293
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
294
+ std_rewards = nanstd(rewards_per_func[:, i]).item()
295
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_rewards)
296
+ self._metrics[mode]["reward"].append(mean_grouped_rewards.mean().item())
297
+ self._metrics[mode]["reward_std"].append(std_grouped_rewards.mean().item())
298
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
299
+
300
+ # Log prompt and completion texts
301
+ self._logs["prompt"].extend(gather_object(prompts_text))
302
+ self._logs["completion"].extend(gather_object(completions_text))
303
+ for i, name in enumerate(self.reward_func_names):
304
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
305
+ self._logs["advantages"].extend(all_process_advantages.tolist())
306
+
307
+ return {
308
+ "prompt_ids": prompt_ids,
309
+ "prompt_mask": prompt_mask,
310
+ "completion_ids": completion_ids,
311
+ "completion_mask": completion_mask,
312
+ "augmentation_mask": augmentation_mask,
313
+ "advantages": advantages,
314
+ "old_per_token_logps": old_per_token_logps,
315
+ "ref_per_token_logps": ref_per_token_logps,
316
+ }
317
+
318
+ def _compute_loss(self, model, inputs):
319
+ # Compute the per-token log probabilities for the model
320
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
321
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
322
+ augmentation_mask = inputs["augmentation_mask"]
323
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
324
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
325
+
326
+ per_token_logps = self._get_per_token_logps(model, input_ids, attention_mask, augmentation_mask)
327
+
328
+ # Compute the KL divergence between the model and the reference model
329
+ if self.beta != 0.0:
330
+ ref_per_token_logps = inputs["ref_per_token_logps"]
331
+ per_token_kl = (
332
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
333
+ )
334
+
335
+ # Compute the loss
336
+ advantages = inputs["advantages"]
337
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
338
+ # old_per_token_logps == per_token_logps, so we can skip it's computation
339
+ # (see _generate_and_score_completions) and use per_token_logps.detach() instead.
340
+ old_per_token_logps = (
341
+ per_token_logps.detach() if inputs["old_per_token_logps"] is None else inputs["old_per_token_logps"]
342
+ )
343
+ coef_1 = torch.exp(per_token_logps - old_per_token_logps)
344
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
345
+
346
+ # Two-sided clipping
347
+ if self.args.delta is not None:
348
+ coef_1 = torch.clamp(coef_1, max=self.args.delta)
349
+
350
+ per_token_loss1 = coef_1 * advantages.unsqueeze(1)
351
+ per_token_loss2 = coef_2 * advantages.unsqueeze(1)
352
+ per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
353
+ if self.beta != 0.0:
354
+ per_token_loss = per_token_loss + self.beta * per_token_kl
355
+
356
+ augmentation_valid_mask = (augmentation_mask != -100)
357
+ if self.loss_type == "grpo":
358
+ loss = ((per_token_loss * augmentation_valid_mask).sum(-1) / augmentation_valid_mask.sum(-1).clamp(min=1.0)).mean()
359
+ elif self.loss_type == "bnpo":
360
+ loss = (per_token_loss * augmentation_valid_mask).sum() / augmentation_valid_mask.sum().clamp(min=1.0)
361
+ elif self.loss_type == "dr_grpo":
362
+ loss = (per_token_loss * augmentation_valid_mask).sum() / (augmentation_valid_mask.size(0) * self.max_completion_length)
363
+ else:
364
+ raise ValueError(f"Unknown loss type: {self.loss_type}")
365
+
366
+ # Log the metrics
367
+ mode = "train" if self.model.training else "eval"
368
+
369
+ if self.beta != 0.0:
370
+ mean_kl = (per_token_kl * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
371
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
372
+
373
+ # Compute the clipped probability ratios
374
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0)
375
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0)
376
+ is_region_clipped = is_low_clipped | is_high_clipped
377
+
378
+ low_clip = (is_low_clipped * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
379
+ high_clip = (is_high_clipped * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
380
+ clip_ratio = (is_region_clipped * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
381
+
382
+ gathered_low_clip = self.accelerator.gather(low_clip)
383
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
384
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
385
+ gathered_high_clip = self.accelerator.gather(high_clip)
386
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
387
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
388
+ gathered_clip_ratio = self.accelerator.gather(clip_ratio)
389
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
390
+ return loss
MemGen-main/memgen/trainer/utils.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ # torch.nanstd doesn't exist, so we define it here
4
+ def nanstd(tensor: torch.Tensor) -> torch.Tensor:
5
+ """
6
+ Compute the standard deviation of a tensor, ignoring NaNs. This function only supports 1D tensors.
7
+
8
+ Args:
9
+ tensor (`torch.Tensor`):
10
+ Input tensor of shape `(N,)`.
11
+
12
+ Returns:
13
+ `torch.Tensor`:
14
+ Standard deviation of the tensor, ignoring NaNs.
15
+ """
16
+ variance = torch.nanmean((tensor - torch.nanmean(tensor, keepdim=True)) ** 2) # Compute variance ignoring NaNs
17
+ count = torch.sum(~torch.isnan(tensor)) # Count of non-NaN values
18
+ variance *= count / (count - 1) # Bessel's correction
19
+ return torch.sqrt(variance)
20
+
21
+ def nanmax(tensor: torch.Tensor) -> torch.Tensor:
22
+ """
23
+ Compute the maximum value of a tensor, ignoring NaNs. This function only supports 1D tensors.
24
+
25
+ Args:
26
+ tensor (`torch.Tensor`): Input tensor of shape `(N,)`.
27
+
28
+ Returns:
29
+ `torch.Tensor`: Maximum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN.
30
+ """
31
+ if torch.isnan(tensor).all():
32
+ return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device)
33
+ return torch.max(tensor[~torch.isnan(tensor)])
34
+
35
+ def nanmin(tensor: torch.Tensor) -> torch.Tensor:
36
+ """
37
+ Compute the minimum value of a tensor, ignoring NaNs. This function only supports 1D tensors.
38
+
39
+ Args:
40
+ tensor (`torch.Tensor`): Input tensor of shape `(N,)`.
41
+
42
+ Returns:
43
+ `torch.Tensor`: Minimum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN.
44
+ """
45
+ if torch.isnan(tensor).all():
46
+ return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device)
47
+ return torch.min(tensor[~torch.isnan(tensor)])
48
+
49
+ def generate_position_ids(attention_mask):
50
+ position_ids = (attention_mask.cumsum(-1) - 1).clamp(min=0)
51
+ position_ids.masked_fill_(attention_mask == 0, 0)
52
+ return position_ids
MemGen-main/memgen/trainer/weaver_grpo_trainer.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import nullcontext
2
+ import logging
3
+ import os
4
+ from typing import Any, Callable, Optional, Union
5
+
6
+ import torch
7
+ from accelerate.utils import gather_object
8
+ from datasets import Dataset, IterableDataset
9
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
10
+ from transformers import (
11
+ PreTrainedModel,
12
+ PreTrainedTokenizerBase,
13
+ ProcessorMixin,
14
+ TrainerCallback,
15
+ )
16
+ from transformers.utils import is_peft_available
17
+ from trl import GRPOTrainer, GRPOConfig
18
+ from trl.trainer.utils import selective_log_softmax
19
+ from trl.data_utils import maybe_apply_chat_template
20
+ from trl.models import unwrap_model_for_generation
21
+ if is_peft_available():
22
+ from peft import PeftConfig
23
+
24
+ from interactions.base_interaction import (
25
+ InteractionManager, InteractionDataProto
26
+ )
27
+ from data.base_env import StaticEnv, DynamicEnv
28
+
29
+ from .utils import (
30
+ nanstd, nanmax, nanmin
31
+ )
32
+ from ..model.modeling_memgen import MemGenModel
33
+
34
+ # What we call a reward function is a callable that takes a list of prompts and completions and returns a list of
35
+ # rewards. When it's a string, it's a model ID, so it's loaded as a pretrained model.
36
+ RewardFunc = Union[str, PreTrainedModel, Callable[[list, list], list[float]]]
37
+
38
+ class WeaverGRPOTrainer(GRPOTrainer):
39
+
40
+ def __init__(
41
+ self,
42
+ model: MemGenModel,
43
+ reward_funcs: Union[RewardFunc, list[RewardFunc]],
44
+ args: Optional[GRPOConfig] = None,
45
+ train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
46
+ eval_dataset: Optional[Union[Dataset, IterableDataset, dict[str, Union[Dataset, IterableDataset]]]] = None,
47
+ processing_class: Optional[Union[PreTrainedTokenizerBase, ProcessorMixin]] = None,
48
+ reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None,
49
+ callbacks: Optional[list[TrainerCallback]] = None,
50
+ optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
51
+ peft_config: Optional["PeftConfig"] = None,
52
+ env_class = None, # env main class
53
+ env_main_config = None, # configs to initialize an env object
54
+ generation_manager: InteractionManager = None # manage the interaction between agent and env
55
+ ):
56
+ super().__init__(
57
+ model,
58
+ reward_funcs,
59
+ args,
60
+ train_dataset,
61
+ eval_dataset,
62
+ processing_class,
63
+ reward_processing_classes,
64
+ callbacks,
65
+ optimizers,
66
+ peft_config
67
+ )
68
+
69
+ self.env_class = env_class
70
+ self.env_main_config = env_main_config
71
+ self.generation_manager = generation_manager
72
+
73
+ self.generation_manager.config.max_prompt_length
74
+
75
+ # assert self.max_prompt_length == generation_manager.config.max_start_length
76
+ # assert self.max_completion_length == generation_manager.config.max_response_length
77
+ # assert self.temperature == generation_manager.config.temperature
78
+
79
+ def _build_multiturn_envs(self, inputs: list[dict[str, Union[torch.Tensor, Any]]]) -> tuple[list[list[dict]], list]:
80
+ init_messages, envs = [], []
81
+
82
+ for task_config in inputs:
83
+ env: DynamicEnv = self.env_class(self.env_main_config)
84
+ system_prompt, init_user_prompt = env.set_env(task_config)
85
+
86
+ system_message = {"role": "system", "content": system_prompt}
87
+ init_user_message = {"role": "user", "content": init_user_prompt}
88
+
89
+ init_messages.append([system_message, init_user_message])
90
+ envs.append(env)
91
+
92
+ return init_messages, envs
93
+
94
+ def _get_per_token_logps(
95
+ self, model,
96
+ input_ids: torch.Tensor,
97
+ attention_mask: torch.Tensor,
98
+ labels: torch.Tensor,
99
+ logits_to_keep: int,
100
+ batch_size: int = None
101
+ ) -> torch.Tensor:
102
+ batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak
103
+ all_logps = []
104
+ supervise_masks = []
105
+ for start in range(0, input_ids.size(0), batch_size):
106
+ input_ids_batch = input_ids[start : start + batch_size]
107
+ attention_mask_batch = attention_mask[start : start + batch_size]
108
+
109
+ # Build model inputs - check if the model supports logits_to_keep (some models and VLMs don't)
110
+ model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch, "labels": labels}
111
+
112
+ # Only add logits_to_keep if the model supports it
113
+ if "logits_to_keep" in self.model_kwarg_keys:
114
+ # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
115
+ model_inputs["logits_to_keep"] = logits_to_keep + 1
116
+
117
+ outputs = model(**model_inputs)
118
+ logits = outputs.logits
119
+ labels = outputs.supervised_labels
120
+
121
+ # Exclude the last value: it corresponds to the next token pred
122
+ logits = logits[:, :-1, :] # (B, L-1, H)
123
+ # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op.
124
+ logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H)
125
+ # Divide logits by sampling temperature.
126
+ # See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details
127
+ logits = logits / self.temperature
128
+
129
+ completion_ids = input_ids_batch[:, -logits_to_keep:]
130
+ logps = selective_log_softmax(logits, completion_ids) # compute logprobs
131
+ all_logps.append(logps)
132
+
133
+ labels = labels[:, -logits_to_keep:]
134
+ mask = (labels != -100).long()
135
+ supervise_masks.append(mask)
136
+
137
+ logps = torch.cat(all_logps, dim=0)
138
+ masks = torch.cat(supervise_masks, dim=0)
139
+ return logps, masks
140
+
141
+
142
+ # NOTE - currently we only deal with text input and leave multimodal as a feature work
143
+ def _generate_and_score_completions(
144
+ self, inputs: list[dict[str, Union[torch.Tensor, Any]]] # batch_size * num_generations
145
+ ) -> dict[str, Union[torch.Tensor, Any]]:
146
+
147
+ device = self.accelerator.device
148
+ mode = "train" if self.model.training else "eval"
149
+
150
+ # build no-tensor part
151
+ batch_gen_keys = []
152
+ if "prompt" in inputs[0]: # text-based raw prompt
153
+ batch_gen_keys.append("prompt")
154
+ if "tools_kwargs" in inputs[0]: # tool-integrated
155
+ batch_gen_keys.append("tools_kwargs")
156
+ if "interaction_kwargs" in inputs[0]: # interaction args
157
+ batch_gen_keys.append("interaction_kwargs")
158
+ if "agent_name" in inputs[0]: # agent name
159
+ batch_gen_keys.append("agent_name")
160
+
161
+ gen_batch = InteractionDataProto()
162
+ for key in batch_gen_keys:
163
+ gen_batch.no_tensor_batch[key] = [x[key] for x in inputs]
164
+
165
+ # Single-turn env
166
+ if issubclass(self.env_class, StaticEnv):
167
+ prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
168
+ prompt_inputs = self.processing_class(
169
+ text=prompts_text, return_tensors="pt", padding=True, padding_side="left", add_special_tokens=False
170
+ )
171
+
172
+ prompts, prompt_mask = prompt_inputs["input_ids"].to(device), prompt_inputs["attention_mask"].to(device)
173
+ if self.max_prompt_length is not None:
174
+ prompts = prompts[:, -self.max_prompt_length :]
175
+ prompt_mask = prompt_mask[:, -self.max_prompt_length :]
176
+
177
+ gen_batch.batch["input_ids"] = prompts
178
+ gen_batch.batch["attention_mask"] = prompt_mask
179
+ # Multi-turn env
180
+ elif issubclass(self.env_class, DynamicEnv):
181
+ init_prompts, envs = self._build_multiturn_envs(inputs)
182
+ gen_batch.no_tensor_batch["init_prompts"] = init_prompts
183
+ gen_batch.no_tensor_batch["envs"] = envs
184
+
185
+ for example, env in zip(inputs, envs):
186
+ example["envs"] = env
187
+ else:
188
+ raise ValueError("Unsupported environment type")
189
+
190
+ # Regular generation path
191
+ with unwrap_model_for_generation(
192
+ self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
193
+ ) as unwrapped_model:
194
+ with (
195
+ FSDP.summon_full_params(self.model_wrapped, recurse=False)
196
+ if self.is_fsdp_enabled
197
+ else nullcontext()
198
+ ):
199
+ # Use GenerationManager to coordinate the interaction between the agent and the environment
200
+ self.generation_manager.actor_rollout_wg = unwrapped_model
201
+ final_gen_batch_output = self.generation_manager.run_agent_loop(gen_batch=gen_batch)
202
+
203
+ # parse outputs
204
+ prompts = final_gen_batch_output.batch["prompts"].to(device) # prompt ids
205
+ completion_ids = final_gen_batch_output.batch["responses"].to(device) # completion ids
206
+ prompt_completion_ids = final_gen_batch_output.batch["input_ids"].to(device) # prompt and completion ids
207
+ attention_mask = final_gen_batch_output.batch["attention_mask"].to(device) # attention_mask on prompt and response
208
+ prompt_mask = attention_mask[:, :prompts.size(1)]
209
+ completion_mask = final_gen_batch_output.batch["info_mask"][:, prompts.size(1):].to(device)
210
+ is_eos = completion_ids == self.eos_token_id
211
+ assert completion_ids.shape == completion_mask.shape
212
+
213
+ # Construct labels: Supervise only the agent response portion.
214
+ prompt_labels = torch.full(prompt_mask.shape, -100, device=device)
215
+ completion_labels = torch.where(completion_mask == 1, completion_ids, -100)
216
+ labels = torch.cat([prompt_labels, completion_labels], dim=1)
217
+
218
+ # Convert tensor to a list of lists of token IDs. This will be passed to the reward function, avoiding the need
219
+ # to re-tokenize completions if the reward is computed from tokens.
220
+ completion_ids_list = [
221
+ [id.item() for id, m in zip(row, mask_row) if m] for row, mask_row in zip(completion_ids, completion_mask)
222
+ ]
223
+
224
+ # Sum along sequence dimension (dim=1) to get completion length per sequence, used for logging
225
+ completion_lengths = completion_mask.sum(1)
226
+
227
+ logits_to_keep = completion_mask.size(1)
228
+
229
+ # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
230
+ if self.mask_truncated_completions:
231
+ truncated_completions = ~is_eos.any(dim=1)
232
+ completion_mask = completion_mask * (~truncated_completions).unsqueeze(1).int()
233
+
234
+ with torch.no_grad():
235
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
236
+ # old_per_token_logps == per_token_logps, so we can skip it's computation here, and use
237
+ # per_token_logps.detach() instead.
238
+ if self.num_iterations > 1 or self.args.steps_per_generation > self.args.gradient_accumulation_steps:
239
+ old_per_token_logps, old_supervise_mask = self._get_per_token_logps(
240
+ self.model, prompt_completion_ids, attention_mask, labels, logits_to_keep
241
+ )
242
+ else:
243
+ old_per_token_logps, old_supervise_mask = None, None
244
+
245
+ # Compute the per-token log probabilities for the reference model
246
+ if self.beta != 0.0:
247
+ if self.ref_model is not None:
248
+ ref_per_token_logps, ref_supervise_mask = self._get_per_token_logps(
249
+ self.ref_model, prompt_completion_ids, attention_mask, labels, logits_to_keep
250
+ )
251
+ else:
252
+ with self.accelerator.unwrap_model(self.model).disable_adapter():
253
+ ref_per_token_logps, ref_supervise_mask = self._get_per_token_logps(
254
+ self.model, prompt_completion_ids, attention_mask, labels, logits_to_keep
255
+ )
256
+ else:
257
+ ref_per_token_logps, ref_supervise_mask = None, None
258
+
259
+ # Decode the generated completions
260
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
261
+ completions = completions_text
262
+
263
+ # compute rewards
264
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
265
+
266
+ # Apply weights to each reward function's output and sum
267
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
268
+
269
+ # Compute grouped-wise rewards
270
+ mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
271
+ std_grouped_rewards = rewards.view(-1, self.num_generations).std(dim=1)
272
+ is_std_zero = torch.isclose(std_grouped_rewards, torch.zeros_like(std_grouped_rewards))
273
+
274
+ # Normalize the rewards to compute the advantages
275
+ mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
276
+ std_grouped_rewards = std_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
277
+ advantages = rewards - mean_grouped_rewards
278
+ if self.scale_rewards:
279
+ advantages = advantages / (std_grouped_rewards + 1e-4)
280
+
281
+ # Slice to keep only the local part of the data
282
+ process_slice = slice(
283
+ self.accelerator.process_index * len(prompts),
284
+ (self.accelerator.process_index + 1) * len(prompts),
285
+ )
286
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
287
+ advantages = advantages[process_slice]
288
+
289
+ # Log the metrics
290
+ if mode == "train":
291
+ self.state.num_input_tokens_seen += self.accelerator.gather(attention_mask.sum()).sum().item()
292
+ self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
293
+
294
+ # Log completion lengths, mean, min, max
295
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
296
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
297
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
298
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
299
+
300
+ # Identify sequences that terminated with EOS and log their lengths
301
+ agg_terminated_with_eos = self.accelerator.gather(is_eos.any(dim=1))
302
+ term_completion_lengths = agg_completion_lengths[agg_terminated_with_eos]
303
+ clipped_completions_ratio = 1 - len(term_completion_lengths) / len(agg_completion_lengths)
304
+ self._metrics[mode]["completions/clipped_ratio"].append(clipped_completions_ratio)
305
+ if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found
306
+ term_completion_lengths = torch.zeros(1, device=device)
307
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
308
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
309
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
310
+
311
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
312
+ for i, reward_func_name in enumerate(self.reward_func_names):
313
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
314
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
315
+ std_rewards = nanstd(rewards_per_func[:, i]).item()
316
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_rewards)
317
+ self._metrics[mode]["reward"].append(mean_grouped_rewards.mean().item())
318
+ self._metrics[mode]["reward_std"].append(std_grouped_rewards.mean().item())
319
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
320
+
321
+ # Log prompt and completion texts
322
+ # self._logs["prompt"].extend(gather_object(prompts_text))
323
+ self._logs["completion"].extend(gather_object(completions_text))
324
+ for i, name in enumerate(self.reward_func_names):
325
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
326
+ self._logs["advantages"].extend(all_process_advantages.tolist())
327
+
328
+ return {
329
+ "prompt_ids": prompts,
330
+ "prompt_mask": prompt_mask,
331
+ "completion_ids": completion_ids,
332
+ "completion_mask": completion_mask,
333
+ "advantages": advantages,
334
+ "old_per_token_logps": old_per_token_logps,
335
+ "old_supervise_mask": old_supervise_mask,
336
+ "ref_per_token_logps": ref_per_token_logps,
337
+ "ref_supervise_mask": ref_supervise_mask
338
+ }
339
+
340
+
341
+ def _compute_loss(self, model, inputs):
342
+ device = self.accelerator.device
343
+
344
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
345
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
346
+ old_supervise_mask, ref_supervise_mask = inputs["old_supervise_mask"], inputs["ref_supervise_mask"]
347
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
348
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
349
+
350
+ prompt_labels = torch.full(prompt_mask.shape, -100, device=device)
351
+ completion_labels = torch.where(completion_mask == 1, completion_ids, -100)
352
+ labels = torch.cat([prompt_labels, completion_labels], dim=1)
353
+ logits_to_keep = completion_labels.size(1)
354
+
355
+ assert prompt_ids.shape == prompt_mask.shape
356
+ assert completion_ids.shape == completion_mask.shape
357
+ assert input_ids.shape == attention_mask.shape == labels.shape
358
+ per_token_logps, supervise_mask = self._get_per_token_logps(model, input_ids, attention_mask, labels, logits_to_keep)
359
+
360
+ # Compute the KL divergence between the model and the reference model
361
+ if self.beta != 0.0:
362
+ ref_per_token_logps = inputs["ref_per_token_logps"]
363
+ per_token_kl = (
364
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
365
+ )
366
+
367
+ # Compute the loss
368
+ advantages = inputs["advantages"]
369
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
370
+ # old_per_token_logps == per_token_logps, so we can skip it's computation
371
+ # (see _generate_and_score_completions) and use per_token_logps.detach() instead.
372
+ old_per_token_logps = (
373
+ per_token_logps.detach() if inputs["old_per_token_logps"] is None else inputs["old_per_token_logps"]
374
+ )
375
+ coef_1 = torch.exp(per_token_logps - old_per_token_logps)
376
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
377
+
378
+ # Two-sided clipping
379
+ if self.args.delta is not None:
380
+ coef_1 = torch.clamp(coef_1, max=self.args.delta)
381
+
382
+ per_token_loss1 = coef_1 * advantages.unsqueeze(1)
383
+ per_token_loss2 = coef_2 * advantages.unsqueeze(1)
384
+ per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
385
+ if self.beta != 0.0:
386
+ per_token_loss = per_token_loss + self.beta * per_token_kl
387
+
388
+ if old_supervise_mask is None:
389
+ old_supervise_mask = supervise_mask
390
+ if ref_supervise_mask is None:
391
+ ref_supervise_mask = supervise_mask
392
+ # Consistency check: The positions that are supervised must be a subset of the completion mask.
393
+ assert (
394
+ torch.all(supervise_mask <= completion_mask) and
395
+ torch.all(old_supervise_mask <= completion_mask) and
396
+ torch.all(ref_supervise_mask <= completion_mask)
397
+ )
398
+ supervised_mask = completion_mask * supervise_mask * old_supervise_mask * ref_supervise_mask
399
+
400
+ if self.loss_type == "grpo":
401
+ loss = ((per_token_loss * supervised_mask).sum(-1) / supervised_mask.sum(-1).clamp(min=1.0)).mean()
402
+ elif self.loss_type == "bnpo":
403
+ loss = (per_token_loss * supervised_mask).sum() / supervised_mask.sum().clamp(min=1.0)
404
+ elif self.loss_type == "dr_grpo":
405
+ loss = (per_token_loss * supervised_mask).sum() / (supervised_mask.size(0) * self.max_completion_length)
406
+ else:
407
+ raise ValueError(f"Unknown loss type: {self.loss_type}")
408
+
409
+ # Log the metrics
410
+ mode = "train" if self.model.training else "eval"
411
+
412
+ if self.beta != 0.0:
413
+ mean_kl = (per_token_kl * supervised_mask).sum() / supervised_mask.sum()
414
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
415
+
416
+ # Compute the clipped probability ratios
417
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0)
418
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0)
419
+ is_region_clipped = is_low_clipped | is_high_clipped
420
+
421
+ low_clip = (is_low_clipped * supervised_mask).sum() / supervised_mask.sum()
422
+ high_clip = (is_high_clipped * supervised_mask).sum() / supervised_mask.sum()
423
+ clip_ratio = (is_region_clipped * supervised_mask).sum() / supervised_mask.sum()
424
+
425
+ gathered_low_clip = self.accelerator.gather(low_clip)
426
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
427
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
428
+ gathered_high_clip = self.accelerator.gather(high_clip)
429
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
430
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
431
+ gathered_clip_ratio = self.accelerator.gather(clip_ratio)
432
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
433
+ return loss
434
+
435
+ def training_step(self, model, inputs, num_items_in_batch=None):
436
+ """
437
+ 重写 training_step 以捕获 OOM 异常并保存 checkpoint
438
+ """
439
+ try:
440
+ # 调用父类的 training_step
441
+ loss = super().training_step(model, inputs, num_items_in_batch)
442
+ return loss
443
+ except torch.cuda.OutOfMemoryError as e:
444
+ # OOM 发生时保存 checkpoint
445
+ logging.error(f"[OOM] CUDA OutOfMemoryError occurred at step {self.state.global_step}")
446
+ logging.error(f"[OOM] Error message: {str(e)}")
447
+
448
+ # 清理缓存以释放内存
449
+ torch.cuda.empty_cache()
450
+
451
+ # 保存 emergency checkpoint
452
+ oom_ckpt_dir = os.path.join(self.args.output_dir, f"oom_checkpoint_step_{self.state.global_step}")
453
+ logging.info(f"[OOM] Saving emergency checkpoint to {oom_ckpt_dir}")
454
+
455
+ try:
456
+ self.save_model(oom_ckpt_dir)
457
+ logging.info(f"[OOM] Emergency checkpoint saved successfully")
458
+ except Exception as save_error:
459
+ logging.error(f"[OOM] Failed to save checkpoint: {save_error}")
460
+
461
+ # 重新抛出异常,让训练停止
462
+ raise RuntimeError(
463
+ f"Training stopped due to OOM at step {self.state.global_step}. "
464
+ f"Emergency checkpoint saved to {oom_ckpt_dir}. "
465
+ f"You can resume training from this checkpoint."
466
+ ) from e
MemGen-main/memgen/utils.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ import glob
3
+ import json
4
+ import logging
5
+ import os
6
+ import shutil
7
+ from typing import Optional, Callable, Dict, List
8
+
9
+ from safetensors import safe_open
10
+ import torch.nn as nn
11
+ from torch.utils.tensorboard import SummaryWriter
12
+
13
+
14
+ # ===== chat template =====
15
+
16
+ # from https://huggingface.co/HuggingFaceTB/SmolLM3-3B/blob/main/chat_template.jinja
17
+ CONVERSATION_TEMPLATE = r"""
18
+ {# ───── main loop ───── #}
19
+ {%- for message in messages -%}
20
+ {%- set content = message.content if message.content is string else "" -%}
21
+ {%- if (message.role == "user") or (message.role == "system") -%}
22
+ {{ "<|im_start|>" + message.role + "\n" + content + "<|im_end|>\n" }}
23
+ {%- elif message.role == "assistant" -%}
24
+ {%- generation -%}
25
+ {{ "<|im_start|>assistant\n" + content + "<|im_end|>\n" }}
26
+ {%- endgeneration -%}
27
+ {%- elif message.role == "tool" -%}
28
+ {{ "<|im_start|>" + "user\n" + content + "<|im_end|>\n" }}
29
+ {%- endif -%}
30
+ {%- endfor -%}
31
+ {# ───── generation prompt ───── #}
32
+ {%- if add_generation_prompt -%}
33
+ {{ "<|im_start|>assistant\n" }}
34
+ {%- endif -%}
35
+ """.strip()
36
+
37
+ # ===== torch part =====
38
+ def load_state_dict_from_safetensor(model_path) -> Dict:
39
+ """Load a safetensor file from the given path and return a state_dict.
40
+
41
+ Args:
42
+ model_path (str): Path to the safetensor file.
43
+
44
+ Returns:
45
+ Dict[str, torch.Tensor]: A dictionary of model parameters,
46
+ where keys are parameter names and values are corresponding tensors.
47
+ """
48
+ model_state_dict = {}
49
+ with safe_open(model_path, framework="pt") as f:
50
+ for key in f.keys():
51
+ model_state_dict[key] = f.get_tensor(key)
52
+ return model_state_dict
53
+
54
+ def fix_model_parameters(model: nn.Module):
55
+ """Freeze all parameters of the given model.
56
+
57
+ Args:
58
+ model (nn.Module): The PyTorch model whose parameters will be frozen.
59
+ """
60
+ for parameter in model.parameters():
61
+ parameter.requires_grad = False
62
+
63
+ def open_model_parameters(model: nn.Module):
64
+ """Unfreeze all parameters of the given model.
65
+
66
+ Args:
67
+ model (nn.Module): The PyTorch model whose parameters will be unfrozen.
68
+ """
69
+ for parameter in model.parameters():
70
+ parameter.requires_grad = True
71
+
72
+ def log_trainable_params(model: nn.Module):
73
+ """Log all trainable parameters of the given model.
74
+
75
+ Args:
76
+ model (nn.Module): The PyTorch model to inspect.
77
+ """
78
+ logging.info("Trainable parameters in the model:")
79
+ for name, param in model.named_parameters():
80
+ if param.requires_grad:
81
+ logging.info(f" {name}: {param.numel()} params, shape={param.shape}")
82
+
83
+
84
+
85
+ # ===== Eval Part =====
86
+ @dataclass
87
+ class StaticEvalRecorder:
88
+ compute_metrics: List[Callable[[str, str, str], float]] = field(default_factory=list)
89
+ log_file: Optional[str] = None
90
+ writer: Optional[object] = None
91
+
92
+ # Internal storage
93
+ metric_sums: Dict[str, float] = field(init=False)
94
+ metric_counts: Dict[str, int] = field(init=False)
95
+
96
+ def __post_init__(self):
97
+ self.metric_sums = {metric.__name__: 0.0 for metric in self.compute_metrics}
98
+ self.metric_counts = {metric.__name__: 0 for metric in self.compute_metrics}
99
+ if self.log_file:
100
+ os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
101
+ with open(self.log_file, 'w') as f:
102
+ f.write('') # Clear file
103
+
104
+ def record_batch(self, completions: List[str], examples: List[Dict]):
105
+ """Record results for a batch of model outputs.
106
+
107
+ Args:
108
+ completions (List[str]): The model's answers (outputs).
109
+ examples (List[Dict]): Each completion's corresponding question and related attributes.
110
+ Each example is expected to contain the keys: "prompt" and "solution".
111
+ """
112
+ # Extract all keys from the first example
113
+ keys = [key for key in examples[0]]
114
+ # Build kwargs for metrics computation (one list per field)
115
+ reward_kwargs = {key: [example[key] for example in examples] for key in keys}
116
+ reward_kwargs['completions'] = completions
117
+
118
+ # Compute all metrics in batch
119
+ batched_results = {}
120
+ for metric in self.compute_metrics: # iterate over each metric function
121
+ metric_name = metric.__name__ # use function name as metric name
122
+ batched_scores = metric(**reward_kwargs) # compute scores for the entire batch
123
+ batched_results[metric_name] = batched_scores
124
+
125
+ # Record experiment results for each example
126
+ for i, (completion, example) in enumerate(zip(completions, examples)):
127
+ # Collect the metric results for this specific example
128
+ metrics_result = {
129
+ metric_name: batched_results[metric_name][i]
130
+ for metric_name in batched_results
131
+ }
132
+
133
+ # Update running totals for metrics
134
+ for metric_name, score in metrics_result.items():
135
+ self.metric_sums[metric_name] += score
136
+ self.metric_counts[metric_name] += 1
137
+
138
+ # Create a log record with prompt, solution, completion, and metrics
139
+ prompt = example.get("prompt", "")
140
+ solution = example.get("solution", "")
141
+ record = {
142
+ 'prompt': prompt,
143
+ 'solution': solution,
144
+ 'completion': completion,
145
+ 'metrics': metrics_result
146
+ }
147
+
148
+ # Write the record into a log file (if available)
149
+ if self.log_file:
150
+ with open(self.log_file, 'a') as f:
151
+ f.write(json.dumps(record, ensure_ascii=False) + '\n')
152
+
153
+ # Update TensorBoard metrics (if writer is available)
154
+ if self.writer:
155
+ mean_metrics = self.get_mean_metrics() # get average metrics across all data so far
156
+ for name, value in mean_metrics.items():
157
+ self.writer.add_scalar(name, value, global_step=self.metric_counts[name])
158
+
159
+
160
+ def get_mean_metrics(self) -> Dict[str, float]:
161
+ return {
162
+ name: (self.metric_sums[name] / self.metric_counts[name]) if self.metric_counts[name] > 0 else 0.0
163
+ for name in self.metric_sums
164
+ }
165
+
166
+ def finalize(self):
167
+ mean_metrics = self.get_mean_metrics()
168
+ final_record = {
169
+ 'summary_metrics': mean_metrics
170
+ }
171
+
172
+ if self.log_file:
173
+ with open(self.log_file, 'a', encoding='utf-8') as f:
174
+ f.write(json.dumps(final_record, ensure_ascii=False) + '\n')
175
+
176
+ if self.writer:
177
+ mean_metrics = self.get_mean_metrics()
178
+ for name, value in mean_metrics.items():
179
+ self.writer.add_scalar(name + "_final", value, global_step=self.metric_counts[name])
180
+
181
+
182
+ @dataclass
183
+ class DynamicEvalRecorder:
184
+ log_file: Optional[str] = None # path to the txt log file
185
+ writer: object = field(default=None) # TensorBoard SummaryWriter
186
+
187
+ def __post_init__(self):
188
+ if self.log_file is None:
189
+ raise ValueError("log_file path must be provided")
190
+
191
+ # Ensure the directory for the log file exists
192
+ os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
193
+ self.logger = logging.getLogger("DynamicEvalRecorder")
194
+
195
+ # Internal counters
196
+ self._total_reward = 0.0
197
+ self._count = 0
198
+
199
+ # Initialize the file (clear previous content if any)
200
+ with open(self.log_file, "w", encoding="utf-8") as f:
201
+ f.write("DynamicEvalRecorder Log\n\n")
202
+
203
+ def record_batch(self, conversations: List[str], rewards: List[float]):
204
+ """Record a batch of conversations and their associated rewards.
205
+
206
+ Args:
207
+ conversations (List[str]): List of conversation texts.
208
+ rewards (List[float]): List of reward values corresponding to conversations.
209
+ """
210
+ if len(conversations) != len(rewards):
211
+ raise ValueError("conversations and rewards must have the same length")
212
+
213
+ # Append batch results to the log file
214
+ with open(self.log_file, "a", encoding="utf-8") as f:
215
+ for conv, rew in zip(conversations, rewards):
216
+ f.write(f"Conversation:\n{conv}\n")
217
+ f.write(f"Reward: {rew:.4f}\n")
218
+ f.write("-" * 40 + "\n")
219
+
220
+ # Update statistics
221
+ self._total_reward += rew
222
+ self._count += 1
223
+
224
+ # Compute running average reward
225
+ avg_reward = self._total_reward / self._count if self._count > 0 else 0.0
226
+
227
+ # Write running average to TensorBoard
228
+ if self.writer is not None:
229
+ self.writer.add_scalar("reward/avg", avg_reward, self._count)
230
+
231
+ # Log summary info
232
+ self.logger.info(f"Recorded {len(conversations)} items, avg_reward={avg_reward:.4f}")
233
+
234
+ def finalize(self):
235
+ """Finalize evaluation: write final average reward to both log file and TensorBoard."""
236
+ # Compute final average reward
237
+ avg_reward = self._total_reward / self._count if self._count > 0 else 0.0
238
+
239
+ # Append final result to log file
240
+ with open(self.log_file, "a", encoding="utf-8") as f:
241
+ f.write("\nFinal Results\n")
242
+ f.write("=" * 40 + "\n")
243
+ f.write(f"Average Reward: {avg_reward:.4f}\n")
244
+
245
+ # Write final result to TensorBoard
246
+ if self.writer:
247
+ self.writer.add_scalar("ave_reward_final", avg_reward, global_step=self._count)
248
+
249
+
250
+ # --- helper functions ---
251
+ def create_tensorboard(save_dir: str):
252
+ log_dir = os.path.join(save_dir, "runs")
253
+ writer = SummaryWriter(log_dir=log_dir)
254
+ return writer
255
+
256
+ def remove_trainer_checkpoints(trainer_output_dir):
257
+ ckpt_paths = glob.glob(os.path.join(trainer_output_dir, "checkpoint-*"))
258
+ for ckpt in ckpt_paths:
259
+ shutil.rmtree(ckpt, ignore_errors=True)
260
+
261
+ import torch.distributed as dist
262
+
263
+ def gather_objects(obj):
264
+ if not dist.is_initialized():
265
+ return obj
266
+ gathered = [None for _ in range(dist.get_world_size())]
267
+ dist.all_gather_object(gathered, obj)
268
+ return gathered
MemGen-main/scripts/eval.sh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
9
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
10
+ export NCCL_DEBUG=INFO
11
+ export NCCL_IB_DISABLE=1
12
+ export NCCL_P2P_DISABLE=1
13
+ export NCCL_ASYNC_DISABLE=1
14
+
15
+ # options:
16
+ # - Qwen/Qwen2.5-1.5B-Instruct
17
+ # - HuggingFaceTB/SmolLM3-3B
18
+ REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
20
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
21
+ TRIGGER_ACTIVE=False
22
+
23
+
24
+ # Dataset configs
25
+ DATASET_NAME="kodcode" # gsm8k, gpqa, kodcode, triviaqa
26
+
27
+ # MemGen configs
28
+
29
+ # Augmentation configs:
30
+ # - For gsm8k, gpqa, kodcode: MAX_PROMPT_AUG_NUM=1, MAX_INFERENCE_AUG_NUM=5
31
+ # - For triviaqa: MAX_PROMPT_AUG_NUM=8, MAX_INFERENCE_AUG_NUM=0
32
+ MAX_PROMPT_AUG_NUM=1
33
+ MAX_INFERENCE_AUG_NUM=0
34
+ PROMPT_LATENTS_LEN=16
35
+ INFERENCE_LATENTS_LEN=16
36
+
37
+ BATCH_SIZE=4
38
+
39
+ # Trained model path:
40
+ # - Must point to a checkpoint file ending with .safetensors (e.g. <output_dir>/model.safetensors)
41
+ # - Required when evaluating the model
42
+ LOAD_MODEL_PATH=""
43
+
44
+ # evaluate
45
+ python -m accelerate.commands.launch \
46
+ --config_file=configs/zero2.yaml \
47
+ --num_processes=${NUM_GPUS} \
48
+ main.py \
49
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
50
+ --options \
51
+ model.model_name ${REASONER_MODEL} \
52
+ model.load_model_path ${LOAD_MODEL_PATH} \
53
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
54
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
55
+ model.weaver.model_name ${WEAVER_MODEL} \
56
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
57
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
58
+ model.trigger.model_name ${TRIGGER_MODEL} \
59
+ model.trigger.active ${TRIGGER_ACTIVE} \
60
+ run.mode evaluate \
61
+ run.interaction.batch_size ${BATCH_SIZE} \
62
+ run.interaction.temperature 0.0 \
63
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/eval/qwen2_5_gsm8k_grpo.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
17
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ TRIGGER_ACTIVE=False
20
+
21
+ DATASET_NAME="gsm8k"
22
+
23
+ MAX_PROMPT_AUG_NUM=1
24
+ MAX_INFERENCE_AUG_NUM=0
25
+ PROMPT_LATENTS_LEN=8
26
+ INFERENCE_LATENTS_LEN=8
27
+
28
+ BATCH_SIZE=4
29
+
30
+ LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/gsm8k/weaver-grpo/pn=1_pl=8_in=0_il=8"
31
+
32
+ # evaluate
33
+ python -m accelerate.commands.launch \
34
+ --config_file=configs/zero2.yaml \
35
+ --num_processes=${NUM_GPUS} \
36
+ main.py \
37
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
38
+ --options \
39
+ model.model_name ${REASONER_MODEL} \
40
+ model.load_model_path ${LOAD_MODEL_PATH} \
41
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
42
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
43
+ model.weaver.model_name ${WEAVER_MODEL} \
44
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
45
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
46
+ model.trigger.model_name ${TRIGGER_MODEL} \
47
+ model.trigger.active ${TRIGGER_ACTIVE} \
48
+ run.mode evaluate \
49
+ run.interaction.batch_size ${BATCH_SIZE} \
50
+ run.interaction.temperature 0.0 \
51
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/eval/qwen2_5_gsm8k_sft.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
17
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ TRIGGER_ACTIVE=False
20
+
21
+ DATASET_NAME="gsm8k"
22
+
23
+ MAX_PROMPT_AUG_NUM=1
24
+ MAX_INFERENCE_AUG_NUM=3
25
+ PROMPT_LATENTS_LEN=8
26
+ INFERENCE_LATENTS_LEN=8
27
+
28
+ BATCH_SIZE=4
29
+
30
+ LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/gsm8k/weaver-sft/pn=1_pl=8_in=3_il=8"
31
+
32
+ # evaluate
33
+ python -m accelerate.commands.launch \
34
+ --config_file=configs/zero2.yaml \
35
+ --num_processes=${NUM_GPUS} \
36
+ main.py \
37
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
38
+ --options \
39
+ model.model_name ${REASONER_MODEL} \
40
+ model.load_model_path ${LOAD_MODEL_PATH} \
41
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
42
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
43
+ model.weaver.model_name ${WEAVER_MODEL} \
44
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
45
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
46
+ model.trigger.model_name ${TRIGGER_MODEL} \
47
+ model.trigger.active ${TRIGGER_ACTIVE} \
48
+ run.mode evaluate \
49
+ run.interaction.batch_size ${BATCH_SIZE} \
50
+ run.interaction.temperature 0.0 \
51
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/eval/qwen2_5_kodcode_grpo.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
17
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ TRIGGER_ACTIVE=False
20
+
21
+ DATASET_NAME="kodcode"
22
+
23
+ MAX_PROMPT_AUG_NUM=1
24
+ MAX_INFERENCE_AUG_NUM=0
25
+ PROMPT_LATENTS_LEN=8
26
+ INFERENCE_LATENTS_LEN=8
27
+
28
+ BATCH_SIZE=4
29
+
30
+ LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/kodcode/weaver-grpo/pn=1_pl=8_in=0_il=8"
31
+
32
+ # evaluate
33
+ python -m accelerate.commands.launch \
34
+ --config_file=configs/zero2.yaml \
35
+ --num_processes=${NUM_GPUS} \
36
+ main.py \
37
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
38
+ --options \
39
+ model.model_name ${REASONER_MODEL} \
40
+ model.load_model_path ${LOAD_MODEL_PATH} \
41
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
42
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
43
+ model.weaver.model_name ${WEAVER_MODEL} \
44
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
45
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
46
+ model.trigger.model_name ${TRIGGER_MODEL} \
47
+ model.trigger.active ${TRIGGER_ACTIVE} \
48
+ run.mode evaluate \
49
+ run.interaction.batch_size ${BATCH_SIZE} \
50
+ run.interaction.temperature 0.0 \
51
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/eval/qwen2_5_kodcode_sft.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
17
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ TRIGGER_ACTIVE=False
20
+
21
+ DATASET_NAME="kodcode"
22
+
23
+ MAX_PROMPT_AUG_NUM=1
24
+ MAX_INFERENCE_AUG_NUM=5
25
+ PROMPT_LATENTS_LEN=4
26
+ INFERENCE_LATENTS_LEN=4
27
+
28
+ BATCH_SIZE=4
29
+
30
+ LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/kodcode/weaver-sft/pn=1_pl=4_in=5_il=4"
31
+
32
+ # evaluate
33
+ python -m accelerate.commands.launch \
34
+ --config_file=configs/zero2.yaml \
35
+ --num_processes=${NUM_GPUS} \
36
+ main.py \
37
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
38
+ --options \
39
+ model.model_name ${REASONER_MODEL} \
40
+ model.load_model_path ${LOAD_MODEL_PATH} \
41
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
42
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
43
+ model.weaver.model_name ${WEAVER_MODEL} \
44
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
45
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
46
+ model.trigger.model_name ${TRIGGER_MODEL} \
47
+ model.trigger.active ${TRIGGER_ACTIVE} \
48
+ run.mode evaluate \
49
+ run.interaction.batch_size ${BATCH_SIZE} \
50
+ run.interaction.temperature 0.0 \
51
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/eval/qwen2_5_triviaqa.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
17
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ TRIGGER_ACTIVE=False
20
+
21
+ DATASET_NAME="triviaqa"
22
+
23
+ MAX_PROMPT_AUG_NUM=8
24
+ MAX_INFERENCE_AUG_NUM=0
25
+ PROMPT_LATENTS_LEN=8
26
+ INFERENCE_LATENTS_LEN=8
27
+
28
+ BATCH_SIZE=4
29
+
30
+ LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/triviaqa/weaver-sft/pn=8_pl=8_in=0_il=8"
31
+
32
+ # evaluate
33
+ python -m accelerate.commands.launch \
34
+ --config_file=configs/zero2.yaml \
35
+ --num_processes=${NUM_GPUS} \
36
+ main.py \
37
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
38
+ --options \
39
+ model.model_name ${REASONER_MODEL} \
40
+ model.load_model_path ${LOAD_MODEL_PATH} \
41
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
42
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
43
+ model.weaver.model_name ${WEAVER_MODEL} \
44
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
45
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
46
+ model.trigger.model_name ${TRIGGER_MODEL} \
47
+ model.trigger.active ${TRIGGER_ACTIVE} \
48
+ run.mode evaluate \
49
+ run.interaction.batch_size ${BATCH_SIZE} \
50
+ run.interaction.temperature 0.0 \
51
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/eval/smollm_kodcode.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="HuggingFaceTB/SmolLM3-3B"
17
+ WEAVER_MODEL="HuggingFaceTB/SmolLM3-3B"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ TRIGGER_ACTIVE=False
20
+
21
+ DATASET_NAME="kodcode"
22
+
23
+ MAX_PROMPT_AUG_NUM=1
24
+ MAX_INFERENCE_AUG_NUM=5
25
+ PROMPT_LATENTS_LEN=4
26
+ INFERENCE_LATENTS_LEN=4
27
+
28
+ BATCH_SIZE=4
29
+
30
+ LOAD_MODEL_PATH="MemGen/SmolLM3-3B/kodcode/weaver-sft/pn=1_pl=4_in=5_il=4"
31
+
32
+ python -m accelerate.commands.launch \
33
+ --config_file=configs/zero2.yaml \
34
+ --num_processes=${NUM_GPUS} \
35
+ main.py \
36
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
37
+ --options \
38
+ model.model_name ${REASONER_MODEL} \
39
+ model.load_model_path ${LOAD_MODEL_PATH} \
40
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
41
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
42
+ model.weaver.model_name ${WEAVER_MODEL} \
43
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
44
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
45
+ model.trigger.model_name ${TRIGGER_MODEL} \
46
+ model.trigger.active ${TRIGGER_ACTIVE} \
47
+ run.mode evaluate \
48
+ run.interaction.batch_size ${BATCH_SIZE} \
49
+ run.interaction.temperature 0.0 \
50
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/eval/smollm_triviaqa.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29508
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="HuggingFaceTB/SmolLM3-3B"
17
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+ TRIGGER_ACTIVE=False
20
+
21
+ DATASET_NAME="triviaqa"
22
+
23
+ MAX_PROMPT_AUG_NUM=8
24
+ MAX_INFERENCE_AUG_NUM=0
25
+ PROMPT_LATENTS_LEN=4
26
+ INFERENCE_LATENTS_LEN=4
27
+
28
+ BATCH_SIZE=4
29
+
30
+ LOAD_MODEL_PATH="MemGen/SmolLM3-3B/triviaqa/weaver-sft/pn=8_pl=4_in=0_il=4"
31
+
32
+ python -m accelerate.commands.launch \
33
+ --config_file=configs/zero2.yaml \
34
+ --num_processes=${NUM_GPUS} \
35
+ main.py \
36
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
37
+ --options \
38
+ model.model_name ${REASONER_MODEL} \
39
+ model.load_model_path ${LOAD_MODEL_PATH} \
40
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
41
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
42
+ model.weaver.model_name ${WEAVER_MODEL} \
43
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
44
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
45
+ model.trigger.model_name ${TRIGGER_MODEL} \
46
+ model.trigger.active ${TRIGGER_ACTIVE} \
47
+ run.mode evaluate \
48
+ run.interaction.batch_size ${BATCH_SIZE} \
49
+ run.interaction.temperature 0.0 \
50
+ run.interaction.max_response_length 1024 \
MemGen-main/scripts/train/qwen2_5_gsm8k_grpo.sh ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export DEBUG_MODE=true
4
+ export LOG_PATH="./debug_log_2b.txt"
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ export MAIN_PROCESS_PORT=29507
7
+
8
+ # 自动计算 GPU 数量
9
+ NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
10
+ echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
11
+ export NCCL_DEBUG=INFO
12
+ export NCCL_IB_DISABLE=1
13
+ export NCCL_P2P_DISABLE=1
14
+ export NCCL_ASYNC_DISABLE=1
15
+
16
+ REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
17
+ WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
18
+ TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
19
+
20
+ DATASET_NAME="gsm8k"
21
+
22
+ TRAIN_METHOD="grpo"
23
+
24
+ MAX_PROMPT_AUG_NUM=1
25
+ MAX_INFERENCE_AUG_NUM=0
26
+ PROMPT_LATENTS_LEN=8
27
+ INFERENCE_LATENTS_LEN=8
28
+
29
+ BATCH_SIZE=1
30
+
31
+ LOAD_MODEL_PATH=""
32
+
33
+
34
+ # train
35
+ python -m accelerate.commands.launch \
36
+ --config_file=configs/zero2.yaml \
37
+ --num_processes=${NUM_GPUS} \
38
+ main.py \
39
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
40
+ --options \
41
+ model.model_name ${REASONER_MODEL} \
42
+ model.load_model_path ${LOAD_MODEL_PATH} \
43
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
44
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
45
+ model.weaver.model_name ${WEAVER_MODEL} \
46
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
47
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
48
+ model.trigger.model_name ${TRIGGER_MODEL} \
49
+ model.trigger.active False \
50
+ datasets.mode ${TRAIN_METHOD} \
51
+ run.mode train \
52
+ run.train_weaver True \
53
+ run.train_trigger False \
54
+ run.train_weaver_method ${TRAIN_METHOD} \
55
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
56
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
57
+ run.weaver.sft.bf16 True \
58
+ run.weaver.sft.gradient_accumulation_steps 1 \