-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtrain_interactive.py
More file actions
3102 lines (2548 loc) · 121 KB
/
train_interactive.py
File metadata and controls
3102 lines (2548 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Interactive GRPO Training Script
================================
GRPO
:
python train_interactive.py --config config/training_interactive.yaml
: Claude Code
: 2024-12-09
"""
import os
import sys
import re
import yaml
import argparse
import logging
import warnings
warnings.filterwarnings("ignore", message=".*Event loop is closed.*")
logging.getLogger("asyncio").setLevel(logging.CRITICAL)
import json
import time
from datetime import datetime
from pathlib import Path
from typing import Optional, List, Dict, Tuple, Any
try:
import torch # type: ignore
except Exception: # pragma: no cover
torch = None # type: ignore
try:
from transformers import AutoTokenizer, AutoModelForCausalLM # type: ignore
except Exception: # pragma: no cover
AutoTokenizer = None # type: ignore
AutoModelForCausalLM = None # type: ignore
try:
from peft import LoraConfig, get_peft_model, TaskType # type: ignore
except Exception: # pragma: no cover
LoraConfig = None # type: ignore
get_peft_model = None # type: ignore
TaskType = None # type: ignore
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from src.interactive import (
InteractiveWorkflowEnv,
create_env,
InteractiveWorkflowBuilder,
create_builder,
Trajectory,
TurnRecord,
TrajectoryRewardCalculator,
create_reward_calculator,
EfficiencyConfig,
InteractiveGRPOTrainer,
InteractiveGRPOConfig,
create_interactive_trainer,
InteractivePromptBuilder,
create_prompt_builder,
)
from src.interactive.workflow_env import EnvState
from src.interactive.operator_descriptions import get_operator_template
from typing import Tuple
def create_demo_executor(problem: str, problem_type: str = "math"):
"""executor -
AFlow executor
"""
raise NotImplementedError(
"Demo executorAFlow executor"
""
)
def setup_logging(log_dir: str, exp_name: str) -> logging.Logger:
""""""
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, f"{exp_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler()
]
)
logger = logging.getLogger("InteractiveTraining")
logger.info(f"Logging to {log_file}")
return logger
LORA_SYNC_PATH = "/tmp/vllm_lora_sync"
LORA_ADAPTER_NAME = "training_lora"
LORA_SYNC_SUCCESS = False
def set_lora_sync_path(path: str):
""" LoRA """
global LORA_SYNC_PATH
LORA_SYNC_PATH = path
def sync_lora_to_vllm(model, vllm_base_url: str = "http://localhost:8003/v1", logger=None) -> bool:
"""LoRAvLLM
verloptimizer.step()LoRA
vLLM
Args:
model: PEFTLoRA
vllm_base_url: vLLM API
logger:
Returns:
bool:
"""
import os
import shutil
import requests
if logger is None:
logger = logging.getLogger("InteractiveTraining")
try:
if not hasattr(model, 'save_pretrained') or not hasattr(model, 'peft_config'):
logger.warning("[P-verl] Model is not a PEFT model, skipping LoRA sync")
return False
if os.path.exists(LORA_SYNC_PATH):
shutil.rmtree(LORA_SYNC_PATH)
os.makedirs(LORA_SYNC_PATH, exist_ok=True)
model.save_pretrained(LORA_SYNC_PATH)
logger.info(f"[P-verl] LoRA weights saved to {LORA_SYNC_PATH}")
success = _load_lora_to_vllm(vllm_base_url, LORA_ADAPTER_NAME, LORA_SYNC_PATH, logger)
global LORA_SYNC_SUCCESS
if success:
logger.info(f"[P-verl] LoRA adapter '{LORA_ADAPTER_NAME}' synced to vLLM successfully")
LORA_SYNC_SUCCESS = True
else:
logger.warning("[P-verl] Failed to sync LoRA to vLLM, rollout will use base model")
LORA_SYNC_SUCCESS = False
return success
except Exception as e:
logger.error(f"[LoRA] sync failed: {e}")
return False
def _load_lora_to_vllm(base_url: str, lora_name: str, lora_path: str, logger) -> bool:
"""vLLM APILoRA
unload+loadload400
"""
return _try_unload_reload_lora(base_url, lora_name, lora_path, logger)
def _try_unload_reload_lora(base_url: str, lora_name: str, lora_path: str, logger) -> bool:
"""unload + loadLoRA
vLLMunloadload
"""
import requests
unload_url = base_url.rstrip('/').replace('/v1', '') + '/v1/unload_lora_adapter'
load_url = base_url.rstrip('/').replace('/v1', '') + '/v1/load_lora_adapter'
try:
requests.post(unload_url, json={"lora_name": lora_name}, timeout=30)
response = requests.post(
load_url,
json={"lora_name": lora_name, "lora_path": lora_path},
timeout=60,
)
return response.status_code == 200
except Exception as e:
logger.debug(f"[LoRA] unload/reload attempt failed: {e}")
return False
VLLM_PROCESS = None
VLLM_RESTART_INTERVAL = 5
def restart_vllm_with_lora(model, config: dict, logger) -> bool:
"""vLLMLoRA
vLLM 0.12.0LoRAAPI
vLLMon-policy
Args:
model: PEFTLoRA
config:
logger:
Returns:
bool:
"""
import subprocess
import time
import requests
import os
import shutil
global VLLM_PROCESS
base_model = config.get('base_model', '/path/to/Qwen3-8B')
port = 8003
try:
if os.path.exists(LORA_SYNC_PATH):
shutil.rmtree(LORA_SYNC_PATH)
os.makedirs(LORA_SYNC_PATH, exist_ok=True)
model.save_pretrained(LORA_SYNC_PATH)
logger.info(f"[LoRA] weights saved to {LORA_SYNC_PATH}")
logger.info("[vLLM] Stopping existing vLLM server...")
subprocess.run(
"pkill -f 'vllm.entrypoints.openai.api_server.*--port 8003'",
shell=True, capture_output=True, timeout=10
)
time.sleep(3)
logger.info("[vLLM] Starting vLLM with updated LoRA...")
cmd = [
"/data/conda_envs/colab-grpo/bin/python", "-m", "vllm.entrypoints.openai.api_server",
"--model", base_model,
"--served-model-name", "Qwen3-8B",
"--port", str(port),
"--gpu-memory-utilization", "0.85",
"--max-model-len", "16384",
"--enable-lora",
"--max-loras", "2",
"--lora-modules", f"{LORA_ADAPTER_NAME}={LORA_SYNC_PATH}",
"--trust-remote-code",
"--dtype", "bfloat16",
]
env = os.environ.copy()
env["CUDA_VISIBLE_DEVICES"] = "0"
VLLM_PROCESS = subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=env,
)
logger.info("[vLLM] Waiting for vLLM to be ready...")
for i in range(60):
time.sleep(2)
try:
resp = requests.get(f"http://localhost:{port}/v1/models", timeout=5)
if resp.status_code == 200:
models = resp.json().get("data", [])
model_ids = [m.get("id") for m in models]
if LORA_ADAPTER_NAME in model_ids:
logger.info(f"[vLLM] vLLM ready with LoRA: {model_ids}")
global LORA_SYNC_SUCCESS
LORA_SYNC_SUCCESS = True
return True
elif "Qwen3-8B" in model_ids:
logger.info(f"[vLLM] vLLM ready, waiting for LoRA... ({model_ids})")
except:
pass
logger.warning("[vLLM] vLLM restart timeout, using base model")
return False
except Exception as e:
logger.error(f"[vLLM] vLLM restart failed: {e}")
return False
def get_vllm_model_name(base_model: str, use_lora_sync: bool = False) -> str:
"""vLLM API
LoRALoRAvLLM
vLLMLoRAidbase_model
LoRA
"""
if use_lora_sync and LORA_SYNC_SUCCESS:
return LORA_ADAPTER_NAME
return base_model
# ======================= End LoRA Sync =======================
def load_config(config_path: str) -> dict:
""""""
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
return config
def load_model_and_tokenizer(config: dict, device: str, resume_path: str = None):
"""tokenizer
Args:
config:
device:
resume_path: checkpoint
"""
logger = logging.getLogger("InteractiveTraining")
if torch is None or AutoTokenizer is None or AutoModelForCausalLM is None:
raise ImportError(
"Missing training dependencies. Install `torch`, `transformers`, and `peft` "
"(see requirements.txt) to run training."
)
model_path = config['base_model']
logger.info(f"Loading model from {model_path}")
tokenizer = AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
padding_side='left',
)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
dtype = torch.bfloat16 if config.get('bf16', True) else torch.float16
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=dtype,
trust_remote_code=True,
device_map=device,
)
if config.get('use_lora', True):
if resume_path:
from peft import PeftModel
logger.info(f"Loading LoRA weights from checkpoint: {resume_path}")
model = PeftModel.from_pretrained(model, resume_path, is_trainable=True)
logger.info("✅ LoRA weights loaded from checkpoint")
else:
logger.info("Applying LoRA...")
target_modules = config.get('lora_target_modules', 'q_proj,k_proj,v_proj,o_proj').split(',')
lora_config = LoraConfig(
r=config.get('lora_rank', 64),
lora_alpha=config.get('lora_alpha', 64),
target_modules=target_modules,
lora_dropout=config.get('lora_dropout', 0.05),
task_type=TaskType.CAUSAL_LM,
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
if config.get('gradient_checkpointing', False):
model.gradient_checkpointing_enable()
if hasattr(model, 'enable_input_require_grads'):
model.enable_input_require_grads()
logger.info("✅ Gradient checkpointing enabled - ~7GB")
model.train()
return model, tokenizer
def load_dataset(data_path: str, max_samples: int = None, filter_unanswerable: bool = True) -> list:
"""
Args:
filter_unanswerable: ground_truthunanswerable (True)
"""
logger = logging.getLogger("InteractiveTraining")
data = []
skipped_unanswerable = 0
with open(data_path, 'r') as f:
for line in f:
item = json.loads(line.strip())
if filter_unanswerable:
gt = str(item.get('ground_truth', '')).strip()
if _is_unanswerable(gt):
skipped_unanswerable += 1
continue
data.append(item)
if max_samples and len(data) >= max_samples:
break
if skipped_unanswerable > 0:
logger.info(f"[Filter] Filtered {skipped_unanswerable} unanswerable samples")
logger.info(f"Loaded {len(data)} samples from {data_path}")
return data
def _load_code_public_tests_map(config: dict) -> Dict[Tuple[str, str], Dict[str, str]]:
"""Load AFlow-style public tests for code datasets.
Mapping key: (source_lower, task_id_str) -> {"test": str, "entry_point": str, "prompt": str}
"""
mapping: Dict[Tuple[str, str], Dict[str, str]] = {}
cfg = (config.get("code_public_tests", {}) or {}) if isinstance(config, dict) else {}
if not cfg:
return mapping
base_dir = Path(__file__).resolve().parent
for src, p in cfg.items():
src_l = str(src).strip().lower()
path = Path(str(p))
if not path.is_absolute():
path = (base_dir / path).resolve()
if not path.exists():
continue
try:
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
row = json.loads(line)
task_id = row.get("task_id")
if task_id is None:
continue
key = (src_l, str(task_id))
mapping[key] = {
"test": str(row.get("test") or ""),
"entry_point": str(row.get("entry_point") or ""),
"prompt": str(row.get("prompt") or ""),
}
except Exception:
continue
return mapping
def _apply_code_public_test(meta: Dict[str, Any], source: str, public_map: Dict[Tuple[str, str], Dict[str, str]]) -> Dict[str, Any]:
"""Override meta.test/entry_point using the public test map (if available)."""
if not public_map:
return dict(meta or {})
src_l = str(source or "").strip().lower()
m = dict(meta or {})
task_id = m.get("task_id")
if task_id is None:
return m
key = (src_l, str(task_id))
row = public_map.get(key)
if not row:
return m
if row.get("test"):
m["test"] = row["test"]
if row.get("entry_point"):
m["entry_point"] = row["entry_point"]
# Optional: keep prompt copy for convenience (HumanEval uses prompt+completion+test).
if src_l == "humaneval" and row.get("prompt"):
m["prompt"] = row["prompt"]
return m
def create_generate_fn(model, tokenizer, config: dict):
"""Qwen3 thinking mode vLLM API"""
gen_config = config.get('generation_config', {})
debug = bool(config.get("debug", False))
use_vllm_api = config.get('use_vllm_api', False)
vllm_base_url = config.get('vllm_base_url', 'http://localhost:8003/v1')
if use_vllm_api:
print(f"[INFO] vLLM API: {vllm_base_url}")
from openai import OpenAI
import threading
_thread_local = threading.local()
def _get_client() -> OpenAI:
client = getattr(_thread_local, "client", None)
if client is None:
client = OpenAI(
base_url=vllm_base_url,
api_key="EMPTY",
timeout=300.0,
)
_thread_local.client = client
return client
base_model_name = config.get('vllm_served_model_name') or os.path.basename(config.get('base_model', 'Qwen3-8B'))
enable_lora_sync = config.get('enable_lora_sync', False)
def _get_model_name() -> str:
return get_vllm_model_name(base_model_name, enable_lora_sync)
if enable_lora_sync:
print(f"[INFO] P-verl: LoRA: {_get_model_name()}")
def generate_vllm(prompt: str, disable_thinking: bool = False) -> str:
"""
Args:
prompt:
disable_thinking: thinking mode ( AWAITING_PROMPT )
"""
try:
import re
context_limit = int(gen_config.get("vllm_context_limit", 16384))
estimated_input_tokens = max(1, len(prompt) // 3)
reserve = 128
if disable_thinking:
desired_max_tokens = int(gen_config.get("vllm_prompt_max_tokens", 256))
enable_thinking = False
if debug:
print("[DEBUG] Thinking mode DISABLED for this call (AWAITING_PROMPT state)")
else:
desired_max_tokens = int(gen_config.get("vllm_action_max_tokens", 512))
enable_thinking = bool(gen_config.get("enable_thinking", True))
available = max(16, context_limit - estimated_input_tokens - reserve)
max_tokens = max(16, min(desired_max_tokens, available))
client = _get_client()
current_model = _get_model_name()
response = client.chat.completions.create(
model=current_model,
messages=[{"role": "user", "content": prompt}],
temperature=gen_config.get('temperature', 0.6),
max_tokens=max_tokens,
top_p=gen_config.get('top_p', 0.95),
extra_body={
"chat_template_kwargs": {"enable_thinking": enable_thinking}
},
)
result = response.choices[0].message.content
if '<think>' in result.lower():
think_match = re.search(r'<think>(.*?)</think>', result, re.DOTALL | re.IGNORECASE)
if think_match:
thinking = think_match.group(1).strip()
if debug:
preview = thinking[:300] + "..." if len(thinking) > 300 else thinking
print(f"[THINKING] {preview}")
result_after_think = re.sub(r'<think>.*?</think>\s*', '', result, flags=re.DOTALL | re.IGNORECASE)
if result_after_think.strip():
result = result_after_think
else:
incomplete = re.search(r'<think>(.*)', result, re.DOTALL | re.IGNORECASE)
if incomplete:
truncated = incomplete.group(1).strip()[:200]
if debug:
print(f"[WARNING] Thinking truncated (len={len(truncated)}), treating as Think-Only.")
result = f"<think_only>{truncated}</think_only>"
result = _truncate_after_first_action(result)
if not disable_thinking:
has_action = re.search(r'[<\[]action[>\]]', str(result), re.IGNORECASE) is not None
if not has_action:
repair_max = int(gen_config.get("vllm_repair_max_tokens", 128))
repair_max = max(16, min(repair_max, available))
repair_prompt = (
prompt
+ "\n\nIMPORTANT: Output EXACTLY ONE XML <action>...</action> now. "
+ "No <think> tags. No extra text."
)
repair_resp = client.chat.completions.create(
model=current_model,
messages=[{"role": "user", "content": repair_prompt}],
temperature=gen_config.get('temperature', 0.6),
max_tokens=repair_max,
top_p=gen_config.get('top_p', 0.95),
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
repaired = repair_resp.choices[0].message.content
repaired = _truncate_after_first_action(repaired)
if re.search(r'[<\[]action[>\]]', str(repaired), re.IGNORECASE):
result = repaired
return result
except Exception as e:
print(f"[ERROR] vLLM API: {e}")
return "<action>add</action><operator>Custom</operator><prompt>API error fallback</prompt>"
return generate_vllm
is_qwen3 = hasattr(model.config, 'model_type') and 'qwen3' in model.config.model_type.lower()
if is_qwen3:
print("[DEBUG] Detected Qwen3 model, DISABLED thinking mode to prevent truncation issues")
default_temp = 0.6
default_top_p = 0.95
default_top_k = 20
else:
default_temp = 0.3
default_top_p = 0.9
default_top_k = 50
def generate(prompt: str, disable_thinking: bool = False) -> str:
if is_qwen3 and hasattr(tokenizer, 'apply_chat_template'):
messages = [{"role": "user", "content": prompt}]
formatted_prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=(not disable_thinking)
)
inputs = tokenizer(formatted_prompt, return_tensors='pt', truncation=True, max_length=4096)
else:
inputs = tokenizer(prompt, return_tensors='pt', truncation=True, max_length=2048)
inputs = {k: v.to(model.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=gen_config.get('max_new_tokens', 2048 if is_qwen3 else 256),
temperature=gen_config.get('temperature', default_temp),
top_p=gen_config.get('top_p', default_top_p),
top_k=gen_config.get('top_k', default_top_k),
do_sample=gen_config.get('do_sample', True),
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
)
response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
if is_qwen3 and '<think>' in response:
import re
think_match = re.search(r'<think>(.*?)</think>', response, re.DOTALL)
if think_match:
thinking = think_match.group(1).strip()
print(f"[THINKING] {thinking[:200]}..." if len(thinking) > 200 else f"[THINKING] {thinking}")
response_after_think = re.sub(r'<think>.*?</think>\s*', '', response, flags=re.DOTALL)
if not response_after_think.strip() or '<action>' not in response_after_think.lower():
print(f"[WARNING] Think-Only detected! Adding marker for better feedback.")
response = f"<think_only>{thinking[:300]}</think_only>"
else:
response = response_after_think
else:
incomplete_think = re.search(r'<think>(.*)', response, re.DOTALL)
if incomplete_think:
truncated_thinking = incomplete_think.group(1).strip()[:200]
print(f"[THINKING TRUNCATED] {truncated_thinking}...")
print(f"[WARNING] Thinking truncated, treating as Think-Only.")
response = f"<think_only>{truncated_thinking}</think_only>"
response = _truncate_after_first_action(response)
return response
return generate
def _truncate_after_first_action(response: str) -> str:
""" (action + )
action action
action parallel <operators>
- </action> <action>add</action>
- “ action ” <action>
- <tag> [tag]
"""
import re
think_match = re.search(r'<think>.*?</think>\s*', response, re.DOTALL | re.IGNORECASE)
if think_match:
response = response[think_match.end():]
action_pattern = re.compile(
r'[<\[]action[>\]]\s*(add|delete|modify|set_prompt|finish)\s*[<\[]/action[>\]]',
re.IGNORECASE
)
open_action_pattern = re.compile(r'[<\[]action[>\]]', re.IGNORECASE)
structure_pattern = re.compile(
r'[<\[]structure[>\]]\s*(parallel|conditional|loop)\s*[<\[]/structure[>\]]',
re.IGNORECASE
)
first_action = action_pattern.search(response)
if not first_action:
return response
next_action_open = open_action_pattern.search(response, first_action.end())
boundary = next_action_open.start() if next_action_open else len(response)
segment = response[first_action.start():boundary]
action_type = first_action.group(1).lower()
structure_match = structure_pattern.search(segment)
structure_type = structure_match.group(1).lower() if structure_match else None
closing_tags = {
"operator": re.compile(r'(</operator>|\[/operator\])', re.IGNORECASE),
"operators": re.compile(r'(</operators>|\[/operators\])', re.IGNORECASE),
"target": re.compile(r'(</target>|\[/target\])', re.IGNORECASE),
"condition": re.compile(r'(</condition>|\[/condition\])', re.IGNORECASE),
"true": re.compile(r'(</true>|\[/true\])', re.IGNORECASE),
"false": re.compile(r'(</false>|\[/false\])', re.IGNORECASE),
"count": re.compile(r'(</count>|\[/count\])', re.IGNORECASE),
"position": re.compile(r'(</position>|\[/position\])', re.IGNORECASE),
"prompt": re.compile(r'(</prompt>|\[/prompt\])', re.IGNORECASE),
"answer": re.compile(r'(</answer>|\[/answer\])', re.IGNORECASE),
}
def _last_end(tag_name: str) -> int:
""" segment closing tag end -1"""
pat = closing_tags[tag_name]
m = None
for m in pat.finditer(segment):
pass
return m.end() if m else -1
end_in_segment = first_action.end() - first_action.start()
if action_type == "finish":
end_in_segment = max(end_in_segment, _last_end("answer"))
elif action_type == "set_prompt":
end_in_segment = max(end_in_segment, _last_end("prompt"))
elif action_type == "delete":
end_in_segment = max(end_in_segment, _last_end("target"))
elif action_type == "modify":
end_in_segment = max(end_in_segment, _last_end("target"), _last_end("operator"))
elif action_type == "add":
if structure_type == "parallel":
end_in_segment = max(end_in_segment, _last_end("operators"))
elif structure_type == "conditional":
end_in_segment = max(end_in_segment, _last_end("condition"), _last_end("true"), _last_end("false"))
elif structure_type == "loop":
end_in_segment = max(end_in_segment, _last_end("operators"), _last_end("count"))
else:
end_in_segment = max(end_in_segment, _last_end("operator"))
end_in_segment = max(end_in_segment, _last_end("position"), _last_end("prompt"))
if end_in_segment <= 0:
end_index = boundary
else:
end_index = first_action.start() + min(end_in_segment, len(segment))
return response[:end_index]
def _sanitize_feedback_for_prompt(feedback: str) -> str:
""" feedback“”
/DSL/ <action>
"""
if not feedback:
return ""
filtered_lines = []
for line in str(feedback).splitlines():
lower = line.lower()
if "<action>" in lower or "</action>" in lower:
continue
if lower.startswith("[action hint]:"):
continue
filtered_lines.append(line)
return "\n".join(filtered_lines)
def run_interactive_loop(
problem: str,
problem_type: str,
generate_fn,
prompt_builder: InteractivePromptBuilder,
max_rounds: int = 15,
verbose: bool = True,
) -> Trajectory:
""""""
logger = logging.getLogger("InteractiveTraining")
print(f"[DEBUG] run_interactive_loop started, problem={problem[:30]}...", flush=True)
executor = create_demo_executor(problem, problem_type)
print(f"[DEBUG] demo executor created", flush=True)
env = create_env(problem=problem, problem_type=problem_type, executor=executor, max_rounds=max_rounds)
print(f"[DEBUG] env created with executor", flush=True)
trajectory = Trajectory(problem=problem, problem_type=problem_type)
prompt = prompt_builder.build_initial_prompt(problem=problem, problem_type=problem_type)
print(f"[DEBUG] Initial prompt built, len={len(prompt)}", flush=True)
for round_idx in range(max_rounds):
print(f"[DEBUG] Round {round_idx+1}/{max_rounds} - generating...", flush=True)
is_awaiting_prompt = hasattr(env, 'env_state') and env.env_state == EnvState.AWAITING_PROMPT
response = generate_fn(prompt, disable_thinking=is_awaiting_prompt)
print(f"[DEBUG] Round {round_idx+1} - got response len={len(response)}", flush=True)
print(f"[RESPONSE] {response[:500]}...", flush=True)
if verbose:
logger.info(f" Round {round_idx + 1}: {response[:100]}...")
feedback, success_list, active = env.step(response)
done = not active
print(f"[FEEDBACK] success={success_list}, active={active}, feedback={feedback[:200]}...", flush=True)
turn_record = TurnRecord(
round_idx=round_idx,
model_response=response,
feedback=feedback,
success=all(success_list) if success_list else True,
dsl_snapshot=env.get_dsl(),
)
trajectory.add_turn(turn_record)
if done:
break
if hasattr(env, 'env_state') and env.env_state == EnvState.AWAITING_PROMPT:
operator_name = env.pending_operator or "Custom"
op_template = get_operator_template(operator_name)
op_description = op_template.get("description", "") if op_template else ""
prompt = prompt_builder.build_prompt_request(
problem=problem,
operator_name=operator_name,
operator_description=op_description,
context=getattr(env, "pending_prompt_context", "") or "",
problem_type=problem_type,
)
print(f"[DEBUG] Using PROMPT_REQUEST prompt for {operator_name}", flush=True)
else:
stats = env.graph.get_statistics() if hasattr(env, 'graph') else {}
prompt = prompt_builder.build_continuation_prompt(
problem=problem,
current_dsl=env.get_dsl(),
total_operators=stats.get('total_operators', 0),
unique_types=stats.get('unique_types', 0),
round_number=round_idx + 2,
max_rounds=max_rounds,
node_ids=[n.id for n in env.graph.nodes] if hasattr(env, 'graph') else [],
last_success=all(success_list) if success_list else True,
last_result=_sanitize_feedback_for_prompt(feedback),
last_message="",
problem_type=problem_type,
)
trajectory.finalize(
final_dsl=env.get_dsl(),
)
return trajectory
def demo_interactive_building(config: dict, model, tokenizer):
""""""
logger = logging.getLogger("InteractiveTraining")
print("[DEBUG] Entering demo_interactive_building", flush=True)
logger.info("=" * 60)
logger.info("Demo: Interactive Workflow Building")
logger.info("=" * 60)
print("[DEBUG] Creating generate_fn...", flush=True)
generate_fn = create_generate_fn(model, tokenizer, config)
print("[DEBUG] generate_fn created", flush=True)
prompt_builder = create_prompt_builder(compact=False)
print("[DEBUG] prompt_builder created", flush=True)
test_problems = [
{
"problem": "What is 15 * 23?",
"problem_type": "math",
},
{
"problem": "Calculate 2^10 (2 to the power of 10)",
"problem_type": "math",
},
{
"problem": "What is the sum of the first 100 natural numbers?",
"problem_type": "math",
},
{
"problem": "If a train travels at 60 km/h, how far will it travel in 2.5 hours?",
"problem_type": "reasoning",
},
]
print(f"[DEBUG] Testing {len(test_problems)} problems", flush=True)
for i, prob in enumerate(test_problems):
print(f"\n[DEBUG] === Problem {i+1} ===", flush=True)
logger.info(f"\n--- Problem {i+1}: {prob['problem'][:50]}... ---")
trajectory = run_interactive_loop(
problem=prob['problem'],
problem_type=prob['problem_type'],
generate_fn=generate_fn,
prompt_builder=prompt_builder,
max_rounds=config.get('interactive_grpo', {}).get('max_rounds', 15),
verbose=True,
)
logger.info(f"Final DSL: {trajectory.final_dsl}")
logger.info(f"Total rounds: {len(trajectory.turns)}")
logger.info(f"Turns: {len(trajectory.turns)}")
reward_calculator = create_reward_calculator(
base_reward=config.get('progressive_reward', {}).get('base_reward', -1.0),
)
reward_result = reward_calculator.compute_reward(
trajectory=trajectory,
correctness=0.5,
)
logger.info(f"Reward: {reward_result.total_reward:.4f}")
logger.info(f" - Structure: {reward_result.structure_reward:.4f}")
logger.info(f" - Correctness: {reward_result.correctness_reward:.4f}")
def demo_dataset_building(
config: dict,
model,
tokenizer,
num_problems: int = 5,
use_aflow: bool = False
):
""""""
import random
logger = logging.getLogger("InteractiveTraining")
print("[DEBUG] Entering demo_dataset_building", flush=True)
logger.info("=" * 60)
logger.info("Demo: Interactive Workflow Building (Dataset Mode)")
logger.info("=" * 60)
train_path = config.get('train_dataset', 'data/train_balanced_12k.jsonl')
print(f"[DEBUG] Loading dataset from {train_path}...", flush=True)
problems_by_source = {}
with open(train_path, 'r') as f:
for line in f:
item = json.loads(line.strip())
source = item.get('source', item.get('dataset', 'unknown'))
if source not in problems_by_source:
problems_by_source[source] = []
problems_by_source[source].append(item)
print(f"[DEBUG] Loaded problems from {len(problems_by_source)} sources", flush=True)
for src, probs in problems_by_source.items():
print(f" - {src}: {len(probs)} problems", flush=True)
random.seed(42)
test_problems = []
priority_sources = ['gsm8k', 'math']
other_sources = [s for s in problems_by_source.keys() if s not in priority_sources]
for src in priority_sources:
if src in problems_by_source:
selected = random.sample(
problems_by_source[src],
min(2, len(problems_by_source[src]))
)
for p in selected:
test_problems.append({
"problem": p.get('problem', p.get('question', '')),
"problem_type": "math",
"source": src,
"ground_truth": p.get('ground_truth', p.get('answer', '')),
})
remaining = num_problems - len(test_problems)
if remaining > 0:
for src in random.sample(other_sources, min(remaining, len(other_sources))):
if src in problems_by_source:
p = random.choice(problems_by_source[src])
ptype = "code" if src in ['humaneval', 'bigcodebench'] else "qa"
test_problems.append({
"problem": p.get('problem', p.get('question', '')),
"problem_type": ptype,
"source": src,
"ground_truth": p.get('ground_truth', p.get('answer', '')),
})
print(f"\n[DEBUG] Selected {len(test_problems)} problems for testing:", flush=True)
for i, p in enumerate(test_problems):
print(f" {i+1}. [{p['source']}] {p['problem'][:60]}...", flush=True)
print("\n[DEBUG] Creating generate_fn...", flush=True)
generate_fn = create_generate_fn(model, tokenizer, config)
prompt_builder = create_prompt_builder(compact=False)
aflow_executor = None
if use_aflow:
print("[DEBUG] Creating AFlow executor...", flush=True)