-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode.py
More file actions
2418 lines (1998 loc) · 89 KB
/
code.py
File metadata and controls
2418 lines (1998 loc) · 89 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
"""
完整的 Qwen2.5-Coder 模型演进与评估系统
整合模型加载、微调、评估三大功能
新增:直接大模型问答功能
"""
import gradio as gr
import torch
import json
import os
import sys
import re
import time
import threading
import subprocess
import tempfile
import logging
from datetime import datetime
from typing import Dict, List, Tuple, Optional
# 设置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# ====== 全局变量 ======
# 模型相关
model = None
tokenizer = None
device = None
# 状态标志
is_training = False
is_evaluating = False
is_generating = False
training_thread = None
evaluation_thread = None
# 结果存储
comparison_results = {}
# ====== API配置 ======
API_CONFIG = {
"qwen_32b_api_url": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
"qwen_14b_api_url": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
"api_key": "sk-1d1d9ecf1f1b446588871b3e6d5d3a30",
}
# ====== 默认配置 ======
DEFAULT_CONFIG = {
# 模型配置
"model_path": "./models/Qwen2.5-Coder-0.5B-Instruct",
"finetuned_model_path": "./models/qwen2.5-coder-0.5b-finetuned",
"human_eval_path": "./datasets/human-eval-v2-20210705.jsonl",
# 训练配置
"dataset_path": "./datasets/mbpp_text_only.jsonl", # 原始数据集路径
"training_dataset_path": "./mbpp_training_data/mbpp_training_dataset.jsonl", # 处理后训练集路径
"output_dir": "./models/qwen2.5-coder-0.5b-finetuned",
"num_epochs": 3,
"learning_rate": 2e-4,
"batch_size": 4,
"use_lora": True,
"use_4bit": False,
# 数据生成配置
"max_generate_items": 50, # 最大生成数据量
"generate_batch_size": 2, # 生成批大小
"max_retries": 3, # API重试次数
# 评估配置
"max_tasks": 20,
"max_tokens": 512,
"temperature": 0.7,
"top_p": 0.9,
# 问答配置
"max_new_tokens": 512,
"gen_temperature": 0.8,
"gen_top_p": 0.95
}
# ====== 日志收集器 ======
class LogCollector:
"""收集所有日志"""
def __init__(self):
self.logs = []
self.lock = threading.Lock()
def add_log(self, message):
with self.lock:
timestamp = datetime.now().strftime("%H:%M:%S")
self.logs.append(f"[{timestamp}] {message}")
def get_logs(self, last_n=100):
with self.lock:
return "\n".join(self.logs[-last_n:])
def clear(self):
with self.lock:
self.logs.clear()
log_collector = LogCollector()
def log(message):
"""记录日志"""
log_collector.add_log(message)
print(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")
# ====== 从generate_dataset.py复制的函数 ======
def call_qwen_api(api_url: str, prompt: str, model_name: str = "qwen2.5-coder-32b-instruct",
max_tokens: int = 1024, temperature: float = 0.7,
retries: int = 3) -> Tuple[bool, str]:
"""
调用Qwen API生成代码
"""
# 延迟导入requests
try:
import requests
except ImportError:
log(" 未安装requests库,无法调用API")
return False, "请安装requests库: pip install requests"
headers = {
"Authorization": f"Bearer {API_CONFIG['api_key']}",
"Content-Type": "application/json"
}
messages = [
{"role": "system", "content": "你是一个专业的编程助手,请生成高质量、可运行的Python代码。"},
{"role": "user", "content": prompt}
]
payload = {
"model": model_name,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": 0.9
}
for attempt in range(retries):
try:
response = requests.post(api_url, headers=headers, json=payload, timeout=60)
response.raise_for_status()
result = response.json()
generated_code = result["choices"][0]["message"]["content"]
# 提取代码块(如果有的话)
code_pattern = r"```(?:python)?\n?(.*?)```"
matches = re.findall(code_pattern, generated_code, re.DOTALL)
if matches:
generated_code = matches[0].strip()
return True, generated_code
except requests.exceptions.RequestException as e:
if attempt == retries - 1:
return False, f"API调用失败(尝试{retries}次): {str(e)}"
time.sleep(1) # 等待1秒后重试
except Exception as e:
return False, f"API处理失败: {str(e)}"
return False, "未知错误"
def validate_code_with_14b(instruct: str, code: str) -> Tuple[bool, str]:
"""
使用14B模型验证代码是否符合指令逻辑
"""
validation_prompt = f"""
请分析以下代码是否符合用户指令的逻辑要求:
用户指令:{instruct}
生成的代码:
```python
{code}
```
请从以下几个方面进行判断:
1. 代码是否完整实现了指令要求的功能
2. 代码逻辑是否正确
3. 是否有明显的逻辑错误或缺失
请用以下格式回答:
[是否通过]:是/否
[理由]:简要说明理由
"""
success, response = call_qwen_api(
API_CONFIG["qwen_14b_api_url"],
validation_prompt,
model_name="qwen2.5-coder-14b-instruct",
max_tokens=256,
temperature=0.3
)
if not success:
return False, response
# 解析响应
if "[是否通过]:是" in response or ("通过" in response and "否" not in response):
return True, response
else:
return False, response
def check_code_syntax(code: str) -> Tuple[bool, str]:
"""
检查Python代码的语法错误
"""
try:
# 添加必要的导入
full_code = "import math\nimport re\nimport heapq\nimport numpy as np\nimport collections\n" + code
# 尝试编译
compile(full_code, '<string>', 'exec')
return True, "语法检查通过"
except SyntaxError as e:
return False, f"语法错误: {str(e)}"
except Exception as e:
return False, f"代码检查错误: {str(e)}"
def extract_function_name(code: str) -> str:
"""
从代码中提取函数名
"""
# 查找第一个函数定义
pattern = r'def\s+(\w+)\s*\('
match = re.search(pattern, code)
if match:
return match.group(1)
return "unknown_function"
def run_basic_test(code: str, function_name: str) -> Tuple[bool, str]:
"""
运行基本测试:检查函数是否可以正常调用
"""
try:
# 创建临时文件
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as f:
# 添加必要的导入
f.write("import math\nimport re\nimport heapq\nimport numpy as np\nimport collections\n")
f.write(code)
f.write(f"\n\n# 基本测试\nif __name__ == '__main__':\n")
f.write(f" try:\n")
f.write(f" # 检查函数是否存在\n")
f.write(f" if '{function_name}' in dir():\n")
f.write(f" func = {function_name}\n")
f.write(f" print('函数存在,可以调用')\n")
f.write(f" else:\n")
f.write(f" print('函数不存在')\n")
f.write(f" except Exception as e:\n")
f.write(f" print(f'测试失败: {{e}}')\n")
temp_file = f.name
result = subprocess.run(
['python', temp_file],
capture_output=True,
text=True,
timeout=5
)
os.unlink(temp_file)
if result.returncode == 0 and "函数存在" in result.stdout:
return True, "基本测试通过"
else:
return False, f"基本测试失败: {result.stderr or result.stdout}"
except Exception as e:
if os.path.exists(temp_file):
os.unlink(temp_file)
return False, f"测试执行错误: {str(e)}"
def process_single_instruction(instruction: str, index: int) -> Tuple[bool, str, str]:
"""
处理单个指令,生成代码并验证
返回: (是否成功, 生成的代码, 验证结果)
"""
log(f"[{index}] 处理指令: {instruction[:80]}...")
# 步骤1: 使用32B模型生成代码
log(f"[{index}] 调用32B API生成代码...")
success, code = call_qwen_api(
API_CONFIG["qwen_32b_api_url"],
instruction,
model_name="qwen2.5-coder-32b-instruct"
)
if not success:
log(f"[{index}] 代码生成失败: {code}")
return False, "", f"代码生成失败: {code}"
# 显示生成的代码预览
code_lines = code.split('\n')
preview_lines = min(5, len(code_lines))
code_preview = '\n'.join(code_lines[:preview_lines])
log(f"[{index}] 代码生成成功")
log(f"[{index}] 代码预览(前{preview_lines}行):\n{code_preview}")
log(f"[{index}] 代码总长度: {len(code)} 字符, {len(code_lines)} 行")
# 步骤2: 语法检查
log(f"[{index}] 进行语法检查...")
syntax_ok, syntax_msg = check_code_syntax(code)
if not syntax_ok:
log(f"[{index}] {syntax_msg}")
return False, "", syntax_msg
log(f"[{index}] 语法检查通过")
# 步骤3: 逻辑验证(14B模型)
log(f"[{index}] 进行逻辑验证(14B模型)...")
logic_ok, logic_msg = validate_code_with_14b(instruction, code)
if not logic_ok:
log(f"[{index}] 逻辑验证失败: {logic_msg[:100]}")
return False, "", f"逻辑验证失败: {logic_msg[:100]}"
log(f"[{index}] 逻辑验证通过")
# 步骤4: 基本测试
log(f"[{index}] 进行基本测试...")
function_name = extract_function_name(code)
test_ok, test_msg = run_basic_test(code, function_name)
if not test_ok:
log(f"[{index}] {test_msg} (但仍保存)")
# 基本测试失败不一定意味着代码有问题,继续处理
else:
log(f"[{index}] 基本测试通过")
log(f"[{index}] 处理完成,数据对合格")
return True, code, "验证通过"
def generate_mbpp_training_data(mbpp_path: str, output_path: str, max_items: int = 50,
start_index: int = 0) -> Tuple[bool, str]:
"""
生成训练数据
"""
try:
# 导入requests(延迟导入以避免依赖问题)
try:
import requests
except ImportError:
log(" 未安装requests库,无法调用API")
return False, "请安装requests库: pip install requests"
log(f"读取数据集: {mbpp_path}")
if not os.path.exists(mbpp_path):
return False, f"数据集不存在: {mbpp_path}"
instructions = []
with open(mbpp_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and line.startswith('"') and line.endswith('"'):
# 移除引号
instruction = line[1:-1]
instructions.append(instruction)
total_instructions = len(instructions)
log(f"共读取 {total_instructions} 条指令")
# 限制处理数量
if max_items:
instructions = instructions[:max_items]
total_instructions = len(instructions)
log(f"限制处理数量为: {total_instructions}")
# 跳过已处理的
if start_index > 0:
instructions = instructions[start_index:]
log(f"从索引 {start_index} 开始处理")
if not instructions:
return True, "没有需要处理的指令"
log(f"开始处理 {len(instructions)} 条指令...")
# 处理每条指令
successful_pairs = []
for i, instruction in enumerate(instructions, start=1):
try:
success, code, validation_msg = process_single_instruction(instruction, i)
if success:
training_pair = {
"instruction": instruction,
"code": code,
"metadata": {
"index": i,
"timestamp": datetime.now().isoformat(),
"validation_result": validation_msg,
"source": "dataset_generated"
}
}
successful_pairs.append(training_pair)
log(f"[{i}] 成功生成数据对")
else:
log(f"[{i}] 数据对生成失败: {validation_msg}")
# 避免API调用过于频繁
time.sleep(0.5)
except Exception as e:
log(f"[{i}] 处理异常: {str(e)}")
# 保存训练数据
if successful_pairs:
# 确保输出目录存在
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'w', encoding='utf-8') as f:
for pair in successful_pairs:
f.write(json.dumps({
"instruction": pair["instruction"],
"code": pair["code"]
}, ensure_ascii=False) + '\n')
log(f" 训练数据生成完成: {len(successful_pairs)}/{len(instructions)} 条成功")
log(f"训练数据已保存到: {output_path}")
return True, f"成功生成 {len(successful_pairs)} 个训练数据对"
else:
return False, "未生成任何训练数据对"
except Exception as e:
return False, f"生成训练数据时出错: {str(e)}"
# ====== 模型问答功能模块 ======
def generate_code_with_local_model(instruction: str, config: Dict) -> Tuple[str, str]:
"""
使用本地加载的模型生成代码
"""
global model, tokenizer, device, is_generating
if model is None or tokenizer is None:
return " 错误: 模型未加载", "请先加载模型"
if is_generating:
return " 正在生成中,请稍候...", ""
is_generating = True
try:
log(f"开始生成代码,指令: {instruction[:100]}...")
# 准备输入
messages = [
{"role": "system", "content": "你是一个专业的Python编程助手。请根据用户指令生成正确、高效的Python代码。"},
{"role": "user", "content": instruction}
]
# 使用Qwen的聊天模板
try:
# 尝试使用tokenizer的apply_chat_template
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
except:
# 备用方案:手动构建Qwen格式
text = f"<|im_start|>system\n{messages[0]['content']}<|im_end|>\n"
text += f"<|im_start|>user\n{messages[1]['content']}<|im_end|>\n"
text += f"<|im_start|>assistant\n"
# 编码输入
inputs = tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=1024
)
# 移到设备
if device == "cuda":
inputs = {k: v.cuda() for k, v in inputs.items()}
# 生成代码
with torch.no_grad():
generated_ids = model.generate(
**inputs,
max_new_tokens=config.get("max_new_tokens", DEFAULT_CONFIG["max_new_tokens"]),
temperature=config.get("gen_temperature", DEFAULT_CONFIG["gen_temperature"]),
top_p=config.get("gen_top_p", DEFAULT_CONFIG["gen_top_p"]),
do_sample=True,
pad_token_id=tokenizer.eos_token_id,
eos_token_id=tokenizer.eos_token_id,
num_beams=1,
repetition_penalty=1.1
)
# 解码生成的代码
generated_tokens = generated_ids[0][inputs['input_ids'].shape[1]:]
generated_code = tokenizer.decode(generated_tokens, skip_special_tokens=True)
# 清理特殊标记
generated_code = generated_code.replace("<|im_end|>", "").replace("<|im_start|>", "").strip()
# 提取可能的代码块
code_pattern = r"```(?:python)?\n?(.*?)```"
matches = re.findall(code_pattern, generated_code, re.DOTALL)
if matches:
generated_code = matches[0].strip()
# 清理代码中的多余说明
lines = generated_code.split('\n')
cleaned_lines = []
in_code_block = False
for line in lines:
if line.strip().startswith('def ') or line.strip().startswith('class ') or line.strip().startswith('import ') or line.strip().startswith('from '):
in_code_block = True
if in_code_block or line.strip().startswith('#') or line.strip().startswith('"""') or line.strip().startswith("'''"):
cleaned_lines.append(line)
generated_code = '\n'.join(cleaned_lines)
log(f" 代码生成完成,长度: {len(generated_code)} 字符")
return " 代码生成成功", generated_code
except Exception as e:
error_msg = f" 生成代码时出错: {str(e)}"
log(error_msg)
return error_msg, ""
finally:
is_generating = False
def save_instruction_to_mbpp(instruction: str, mbpp_path: str = None):
"""
将指令保存到数据集(添加引号确保格式统一)
"""
try:
if mbpp_path is None:
mbpp_path = DEFAULT_CONFIG["dataset_path"]
# 确保目录存在
os.makedirs(os.path.dirname(mbpp_path), exist_ok=True)
# 清理指令:移除多余空格和换行
cleaned_instruction = instruction.strip()
# 确保指令用双引号包裹
if not (cleaned_instruction.startswith('"') and cleaned_instruction.endswith('"')):
# 转义内部的双引号
cleaned_instruction = cleaned_instruction.replace('"', '\\"')
cleaned_instruction = f'"{cleaned_instruction}"'
# 保存到文件
with open(mbpp_path, 'a', encoding='utf-8') as f:
f.write(cleaned_instruction + '\n')
log(f" 指令已保存到数据集: {cleaned_instruction[:100]}...")
return True, f"指令已保存到 {mbpp_path}"
except Exception as e:
error_msg = f" 保存指令失败: {str(e)}"
log(error_msg)
return False, error_msg
def process_instruction_with_local_model(instruction: str, temperature: float, top_p: float,
max_new_tokens: int, mbpp_path: str = None) -> Tuple[str, str, str]:
"""
处理用户指令:如果是"自我演化"则开始微调,否则生成代码并保存指令
"""
global is_training, training_thread
# 清理指令
instruction = instruction.strip()
# 检查是否为"自我演化"指令
if instruction.lower() == "自我演化":
log("检测到'自我演化'指令,开始微调流程...")
# 检查数据集是否存在
if mbpp_path is None:
mbpp_path = DEFAULT_CONFIG["dataset_path"]
if not os.path.exists(mbpp_path):
error_msg = f" 数据集不存在: {mbpp_path}"
log(error_msg)
return error_msg, "", ""
# 检查数据集大小
try:
with open(mbpp_path, 'r', encoding='utf-8') as f:
lines = sum(1 for _ in f)
except:
lines = 0
if lines == 0:
error_msg = f" 数据集为空: {mbpp_path}"
log(error_msg)
return error_msg, "", ""
log(f"数据集包含 {lines} 条指令")
# 开始微调
if is_training:
return " 训练已经在进行中...", "", ""
# 准备训练配置
train_config = {
"model_path": DEFAULT_CONFIG["model_path"],
"dataset_path": mbpp_path,
"output_dir": DEFAULT_CONFIG["output_dir"],
"num_epochs": DEFAULT_CONFIG["num_epochs"],
"learning_rate": DEFAULT_CONFIG["learning_rate"],
"batch_size": DEFAULT_CONFIG["batch_size"],
"max_generate_items": min(50, lines), # 限制生成数量
"use_lora": DEFAULT_CONFIG["use_lora"],
"use_4bit": DEFAULT_CONFIG["use_4bit"]
}
# 开始训练线程
training_thread = TrainingThread(train_config, log)
is_training = True
training_thread.start()
status_msg = f"""
开始自我演化(微调)...
使用指令: {lines} 条
输出目录: {DEFAULT_CONFIG['output_dir']}
训练轮数: {DEFAULT_CONFIG['num_epochs']}
开始时间: {datetime.now().strftime('%H:%M:%S')}
"""
log(status_msg)
return status_msg, "", ""
else:
# 正常生成代码流程
log(f"处理用户指令: {instruction[:100]}...")
# 构建配置字典
config = {
"max_new_tokens": max_new_tokens,
"gen_temperature": temperature,
"gen_top_p": top_p
}
# 生成代码
status, code = generate_code_with_local_model(instruction, config)
# 保存指令到数据集(带引号)
save_success, save_msg = save_instruction_to_mbpp(instruction, mbpp_path)
if save_success:
save_status = f" 指令已保存到数据集"
else:
save_status = f" 保存指令失败: {save_msg}"
return status, code, save_status
# ====== 模型加载模块 ======
def load_model_interface(model_path):
"""加载模型界面函数"""
global model, tokenizer, device
if not model_path or model_path.strip() == "":
model_path = DEFAULT_CONFIG["model_path"]
if not os.path.exists(model_path):
return f" 模型路径不存在: {model_path}", False
try:
log(" 开始加载模型...")
# 动态导入
from transformers import AutoTokenizer, AutoModelForCausalLM
# 加载tokenizer
tokenizer = AutoTokenizer.from_pretrained(
model_path,
local_files_only=True,
trust_remote_code=True
)
# 确定设备
device = "cuda" if torch.cuda.is_available() else "cpu"
# 加载模型
model = AutoModelForCausalLM.from_pretrained(
model_path,
local_files_only=True,
device_map="auto",
trust_remote_code=True,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
low_cpu_mem_usage=True
)
model.eval()
info = f"""
模型加载完成!
模型路径: {model_path}
使用设备: {device}
模型参数量: 约0.5B
Tokenizer: 已加载
"""
log(info)
return " 模型加载成功", True
except Exception as e:
error_msg = f" 加载模型失败: {str(e)}"
log(error_msg)
return error_msg, False
# ====== 模型训练模块 ======
class TrainingThread(threading.Thread):
"""训练线程"""
def __init__(self, config, callback=None):
super().__init__()
self.config = config
self.callback = callback
self.daemon = True
def log(self, message):
if self.callback:
self.callback(message)
log(message)
def run(self):
try:
# 步骤1: 生成训练数据
self.log("=" * 60)
self.log("第一步: 生成训练数据")
self.log("=" * 60)
# 检查是否需要生成训练数据
mbpp_path = self.config.get('dataset_path', DEFAULT_CONFIG["dataset_path"])
training_data_path = self.config.get('training_dataset_path', DEFAULT_CONFIG["training_dataset_path"])
max_generate_items = self.config.get('max_generate_items', DEFAULT_CONFIG["max_generate_items"])
# 如果训练数据不存在或需要重新生成
if not os.path.exists(training_data_path):
self.log(f"训练数据不存在,开始生成...")
self.log(f"数据集: {mbpp_path}")
self.log(f"输出路径: {training_data_path}")
self.log(f"最大生成数量: {max_generate_items}")
success, msg = generate_mbpp_training_data(
mbpp_path,
training_data_path,
max_items=max_generate_items
)
if not success:
self.log(f" 生成训练数据失败: {msg}")
return
self.log(f" {msg}")
else:
# 检查现有训练数据
with open(training_data_path, 'r', encoding='utf-8') as f:
lines = sum(1 for _ in f)
self.log(f" 使用现有训练数据: {training_data_path}")
self.log(f"现有训练样本数: {lines}")
# 步骤2: 加载模型进行微调
self.log("=" * 60)
self.log("第二步: 开始模型演进")
self.log("=" * 60)
self.log("开始导入训练库...")
# 动态导入训练所需的库
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
TrainingArguments,
Trainer,
DataCollatorForLanguageModeling,
BitsAndBytesConfig
)
from datasets import Dataset
import warnings
warnings.filterwarnings("ignore")
self.log("库导入完成")
# 加载模型
self.log(f"加载模型: {self.config['model_path']}")
global model, tokenizer, device
# 加载tokenizer
tokenizer = AutoTokenizer.from_pretrained(
self.config['model_path'],
trust_remote_code=True,
padding_side="right",
use_fast=True
)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# 确定设备
device = "cuda" if torch.cuda.is_available() else "cpu"
self.log(f"使用设备: {device}")
# 加载模型
model = AutoModelForCausalLM.from_pretrained(
self.config['model_path'],
local_files_only=True,
device_map="auto",
trust_remote_code=True,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
low_cpu_mem_usage=True
)
self.log(" 模型加载完成")
# 加载数据集
self.log(f"加载训练数据集: {training_data_path}")
data = []
try:
with open(training_data_path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
data.append(json.loads(line))
except Exception as e:
self.log(f" 加载数据集失败: {str(e)}")
return
self.log(f"数据集大小: {len(data)} 个样本")
if len(data) == 0:
self.log(" 数据集为空")
return
# 准备训练数据
self.log("准备训练数据...")
processed_data = []
for item in data[:100]: # 限制样本数量,避免内存不足
instruction = item.get("instruction", "")
code = item.get("code", "")
# 创建模型输入格式
messages = [
{"role": "system", "content": "You are a helpful AI assistant that writes Python code."},
{"role": "user", "content": instruction},
{"role": "assistant", "content": code}
]
# 使用Qwen特定的格式
text = f"<|im_start|>system\n{messages[0]['content']}<|im_end|>\n"
text += f"<|im_start|>user\n{messages[1]['content']}<|im_end|>\n"
text += f"<|im_start|>assistant\n{messages[2]['content']}<|im_end|>\n"
processed_data.append({"text": text})
# 创建数据集
dataset = Dataset.from_list(processed_data)
# 分割训练/验证集
if len(dataset) > 20:
split_dataset = dataset.train_test_split(test_size=0.1, seed=42)
train_dataset = split_dataset["train"]
eval_dataset = split_dataset["test"]
else:
train_dataset = dataset
eval_dataset = dataset.select(range(min(5, len(dataset))))
self.log(f"训练集: {len(train_dataset)}, 验证集: {len(eval_dataset)}")
# 数据预处理
def preprocess_function(examples):
return tokenizer(
examples["text"],
truncation=True,
max_length=512, # 减少长度以节省内存
padding="max_length",
)
self.log("预处理数据...")
tokenized_train = train_dataset.map(
preprocess_function,
batched=True,
remove_columns=train_dataset.column_names,
)
tokenized_eval = eval_dataset.map(
preprocess_function,
batched=True,
remove_columns=eval_dataset.column_names,
)
# 数据整理器
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False,
)
# 训练参数
training_args = TrainingArguments(
output_dir=self.config['output_dir'],
num_train_epochs=self.config['num_epochs'],
per_device_train_batch_size=self.config['batch_size'],
per_device_eval_batch_size=self.config['batch_size'],
gradient_accumulation_steps=2,
warmup_steps=50,
logging_steps=5,
save_strategy="epoch",
eval_strategy="epoch",
learning_rate=self.config['learning_rate'],
weight_decay=0.01,
fp16=False, # torch.cuda.is_available(),
push_to_hub=False,
report_to="none",
gradient_checkpointing=True,
)
# 创建Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_train,
eval_dataset=tokenized_eval,
tokenizer=tokenizer,
data_collator=data_collator,
)
# 开始训练
self.log("开始训练...")
trainer.train()
# 保存模型
self.log("保存模型...")
trainer.save_model()
tokenizer.save_pretrained(self.config['output_dir'])
self.log(" 训练完成!")
self.log(f"模型已保存到: {self.config['output_dir']}")
except ImportError as e:
self.log(f" 缺少依赖库: {str(e)}")
self.log("请运行: pip install torch transformers datasets")
except Exception as e:
self.log(f" 训练过程中出错: {str(e)}")
import traceback
self.log(traceback.format_exc())
finally:
global is_training
is_training = False
def start_training_interface(config_data):
"""开始训练界面函数"""
global is_training, training_thread
if is_training:
return " 训练已经在进行中...", False
# 更新配置
config = DEFAULT_CONFIG.copy()
config.update(config_data)
# 检查必要参数
required_fields = ["model_path", "dataset_path", "output_dir"]
for field in required_fields:
if not config.get(field):
return f" 请填写{field}", False
# 检查数据集
mbpp_path = config.get("dataset_path", DEFAULT_CONFIG["dataset_path"])
if not os.path.exists(mbpp_path):
return f" 数据集不存在: {mbpp_path}", False
# 创建输出目录
os.makedirs(config["output_dir"], exist_ok=True)
# 开始训练线程
training_thread = TrainingThread(config, log)
is_training = True
training_thread.start()
start_msg = f"""
开始模型演进任务...
第一阶段: 生成训练数据
- 数据集: {config.get('dataset_path', DEFAULT_CONFIG["dataset_path"])}
- 最大生成数量: {config.get('max_generate_items', DEFAULT_CONFIG["max_generate_items"])}
- 输出路径: {config.get('training_dataset_path', DEFAULT_CONFIG["training_dataset_path"])}
第二阶段: 模型演进
- 模型: {config['model_path']}
- 输出目录: {config['output_dir']}
- 训练轮数: {config['num_epochs']}
- 学习率: {config['learning_rate']}
- 批大小: {config['batch_size']}
训练日志将在下方显示...