lxcxjxhx commited on
Commit
eaccc23
·
verified ·
1 Parent(s): 23e8e37

Upload hos_optimizer/train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hos_optimizer/train.py +860 -0
hos_optimizer/train.py ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HOS 模型微调模块
3
+
4
+ 提供 QLoRA 和 LoRA 微调功能,针对 8GB VRAM 场景优化。
5
+ 支持 Alpaca 和 ShareGPT 数据格式,集成 Unsloth 加速(可选)。
6
+
7
+ 主要功能:
8
+ - QLoRA 训练(4-bit 量化 + LoRA)
9
+ - LoRA 训练(全精度 + LoRA)
10
+ - 数据集加载和预处理
11
+ - 训练监控和日志
12
+ - 模型合并
13
+ """
14
+
15
+ import os
16
+ import json
17
+ import logging
18
+ import argparse
19
+ import shutil
20
+ from pathlib import Path
21
+ from typing import Dict, List, Optional, Union, Tuple
22
+ from dataclasses import dataclass, field
23
+ from datetime import datetime
24
+
25
+ import torch
26
+ from tqdm import tqdm
27
+ from transformers import (
28
+ AutoModelForCausalLM,
29
+ AutoTokenizer,
30
+ BitsAndBytesConfig,
31
+ TrainingArguments,
32
+ Trainer,
33
+ DataCollatorForSeq2Seq,
34
+ TrainerCallback,
35
+ TrainerControl,
36
+ TrainerState,
37
+ )
38
+ from peft import (
39
+ LoraConfig,
40
+ get_peft_model,
41
+ prepare_model_for_kbit_training,
42
+ TaskType,
43
+ PeftModel,
44
+ )
45
+ from datasets import load_dataset, Dataset, DatasetDict
46
+
47
+ # 尝试导入 Unsloth(可选加速)
48
+ try:
49
+ from unsloth import FastLanguageModel
50
+ UNSLOTH_AVAILABLE = True
51
+ except ImportError:
52
+ UNSLOTH_AVAILABLE = False
53
+ logging.warning("Unsloth 未安装,将使用标准训练流程。安装命令: pip install unsloth")
54
+
55
+ # 配置日志
56
+ logging.basicConfig(
57
+ level=logging.INFO,
58
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
59
+ handlers=[
60
+ logging.StreamHandler(),
61
+ logging.FileHandler('training.log', encoding='utf-8')
62
+ ]
63
+ )
64
+ logger = logging.getLogger(__name__)
65
+
66
+
67
+ @dataclass
68
+ class TrainingConfig:
69
+ """训练配置类"""
70
+
71
+ # 模型配置
72
+ model_name_or_path: str = "Qwen/Qwen2.5-0.5B"
73
+ trust_remote_code: bool = True
74
+
75
+ # 训练方法
76
+ finetuning_type: str = "qlora" # "qlora" 或 "lora"
77
+
78
+ # 数据集配置
79
+ dataset_path: str = ""
80
+ dataset_format: str = "alpaca" # "alpaca" 或 "sharegpt"
81
+ max_seq_length: int = 2048
82
+ preprocessing_num_workers: int = 4
83
+
84
+ # QLoRA 量化配置
85
+ use_4bit: bool = True
86
+ bnb_4bit_quant_type: str = "nf4"
87
+ bnb_4bit_use_double_quant: bool = True
88
+ bnb_4bit_compute_dtype: str = "bfloat16"
89
+
90
+ # LoRA 配置
91
+ lora_rank: int = 16
92
+ lora_alpha: int = 32
93
+ lora_dropout: float = 0.05
94
+ lora_target_modules: List[str] = field(default_factory=lambda: ["all"])
95
+
96
+ # 训练参数
97
+ output_dir: str = "./output"
98
+ num_train_epochs: int = 3
99
+ per_device_train_batch_size: int = 2
100
+ gradient_accumulation_steps: int = 8
101
+ learning_rate: float = 2e-4
102
+ lr_scheduler_type: str = "cosine"
103
+ warmup_ratio: float = 0.1
104
+ max_grad_norm: float = 1.0
105
+ weight_decay: float = 0.01
106
+
107
+ # 日志和保存
108
+ logging_steps: int = 10
109
+ save_steps: int = 500
110
+ save_total_limit: int = 3
111
+
112
+ # 精度配置
113
+ bf16: bool = True
114
+ fp16: bool = False
115
+
116
+ # 性能优化
117
+ gradient_checkpointing: bool = True
118
+ optim: str = "adamw_torch"
119
+
120
+ # 其他
121
+ seed: int = 42
122
+ use_unsloth: bool = True # 如果可用,使用 Unsloth 加速
123
+
124
+
125
+ class DatasetProcessor:
126
+ """数据集处理器"""
127
+
128
+ def __init__(self, tokenizer, max_seq_length: int = 2048):
129
+ """
130
+ 初始化数据集处理器
131
+
132
+ Args:
133
+ tokenizer: 分词器
134
+ max_seq_length: 最大序列长度
135
+ """
136
+ self.tokenizer = tokenizer
137
+ self.max_seq_length = max_seq_length
138
+
139
+ def format_alpaca(self, example: Dict) -> Dict:
140
+ """
141
+ 格式化 Alpaca 格式数据
142
+
143
+ Alpaca 格式: {"instruction": "...", "input": "...", "output": "..."}
144
+
145
+ Args:
146
+ example: 数据样本
147
+
148
+ Returns:
149
+ 格式化后的字典
150
+ """
151
+ instruction = example.get("instruction", "")
152
+ input_text = example.get("input", "")
153
+ output = example.get("output", "")
154
+
155
+ # 构建对话格式
156
+ if input_text:
157
+ text = f"### 指令:\n{instruction}\n\n### 输入:\n{input_text}\n\n### 回答:\n{output}"
158
+ else:
159
+ text = f"### 指令:\n{instruction}\n\n### 回答:\n{output}"
160
+
161
+ return {"text": text}
162
+
163
+ def format_sharegpt(self, example: Dict) -> Dict:
164
+ """
165
+ 格式化 ShareGPT 格式数据
166
+
167
+ ShareGPT 格式: {"conversations": [{"from": "human", "value": "..."}, {"from": "gpt", "value": "..."}]}
168
+
169
+ Args:
170
+ example: 数据样本
171
+
172
+ Returns:
173
+ 格式化后的字典
174
+ """
175
+ conversations = example.get("conversations", [])
176
+
177
+ text_parts = []
178
+ for turn in conversations:
179
+ role = turn.get("from", "")
180
+ value = turn.get("value", "")
181
+
182
+ if role == "human":
183
+ text_parts.append(f"### 用户:\n{value}")
184
+ elif role == "gpt":
185
+ text_parts.append(f"### 助手:\n{value}")
186
+
187
+ text = "\n\n".join(text_parts)
188
+ return {"text": text}
189
+
190
+ def format_messages(self, example: Dict) -> Dict:
191
+ """
192
+ 格式化 messages 格式数据(OpenAI 风格)
193
+
194
+ messages 格式: {"messages": [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
195
+
196
+ Args:
197
+ example: 数据样本
198
+
199
+ Returns:
200
+ 格式化后的字典
201
+ """
202
+ messages = example.get("messages", [])
203
+
204
+ text_parts = []
205
+ for msg in messages:
206
+ role = msg.get("role", "")
207
+ content = msg.get("content", "")
208
+
209
+ if role == "user":
210
+ text_parts.append(f"### 用户:\n{content}")
211
+ elif role == "assistant":
212
+ text_parts.append(f"### 助手:\n{content}")
213
+ elif role == "system":
214
+ text_parts.append(f"### 系统:\n{content}")
215
+
216
+ text = "\n\n".join(text_parts)
217
+ return {"text": text}
218
+
219
+ def tokenize_function(self, example: Dict) -> Dict:
220
+ """
221
+ 分词函数
222
+
223
+ Args:
224
+ example: 包含 "text" 字段的字典
225
+
226
+ Returns:
227
+ 分词后的字典
228
+ """
229
+ text = example.get("text", "")
230
+
231
+ # 分词
232
+ tokenized = self.tokenizer(
233
+ text,
234
+ truncation=True,
235
+ max_length=self.max_seq_length,
236
+ padding=False,
237
+ return_tensors=None,
238
+ )
239
+
240
+ # 设置 labels(用于语言模型训练)
241
+ tokenized["labels"] = tokenized["input_ids"].copy()
242
+
243
+ return tokenized
244
+
245
+ def process_dataset(
246
+ self,
247
+ dataset: Dataset,
248
+ dataset_format: str = "alpaca"
249
+ ) -> Dataset:
250
+ """
251
+ 处理数据集
252
+
253
+ Args:
254
+ dataset: 原始数据集
255
+ dataset_format: 数据格式 ("alpaca", "sharegpt" 或 "messages")
256
+
257
+ Returns:
258
+ 处理后的数据集
259
+ """
260
+ logger.info(f"开始处理数据集,格式: {dataset_format}")
261
+
262
+ # 格式化数据
263
+ if dataset_format == "alpaca":
264
+ format_func = self.format_alpaca
265
+ elif dataset_format == "sharegpt":
266
+ format_func = self.format_sharegpt
267
+ elif dataset_format == "messages":
268
+ format_func = self.format_messages
269
+ else:
270
+ raise ValueError(f"不支持的数据格式: {dataset_format},支持的格式: alpaca, sharegpt, messages")
271
+
272
+ # 应用格式化
273
+ dataset = dataset.map(format_func)
274
+ logger.info(f"数据格式化完成,样本数: {len(dataset)}")
275
+
276
+ # 分词
277
+ dataset = dataset.map(
278
+ self.tokenize_function,
279
+ num_proc=self.tokenizer.num_proc if hasattr(self.tokenizer, 'num_proc') else 4,
280
+ remove_columns=dataset.column_names,
281
+ desc="分词处理中"
282
+ )
283
+ logger.info(f"分词完成,有效样本数: {len(dataset)}")
284
+
285
+ return dataset
286
+
287
+
288
+ def load_and_process_dataset(
289
+ dataset_path: str,
290
+ tokenizer,
291
+ dataset_format: str = "alpaca",
292
+ max_seq_length: int = 2048,
293
+ test_size: float = 0.05
294
+ ) -> DatasetDict:
295
+ """
296
+ 加载并处理数据集
297
+
298
+ Args:
299
+ dataset_path: 数据集路径(JSON 文件)
300
+ tokenizer: 分词器
301
+ dataset_format: 数据格式 ("alpaca" 或 "sharegpt")
302
+ max_seq_length: 最大序列长度
303
+ test_size: 测试集比例
304
+
305
+ Returns:
306
+ 包含 train 和 test 的 DatasetDict
307
+ """
308
+ logger.info(f"加载数据集: {dataset_path}")
309
+
310
+ # 加载 JSON 数据
311
+ if not os.path.exists(dataset_path):
312
+ raise FileNotFoundError(f"数据集文件不存在: {dataset_path}")
313
+
314
+ dataset = load_dataset("json", data_files=dataset_path, split="train")
315
+ logger.info(f"原始数据集大小: {len(dataset)}")
316
+
317
+ # 处理数据集
318
+ processor = DatasetProcessor(tokenizer, max_seq_length)
319
+ processed_dataset = processor.process_dataset(dataset, dataset_format)
320
+
321
+ # 划分训练集和测试集
322
+ dataset_dict = processed_dataset.train_test_split(
323
+ test_size=test_size,
324
+ seed=42
325
+ )
326
+
327
+ logger.info(f"训练集大小: {len(dataset_dict['train'])}")
328
+ logger.info(f"测试集大小: {len(dataset_dict['test'])}")
329
+
330
+ return dataset_dict
331
+
332
+
333
+ def get_quantization_config(config: TrainingConfig) -> Optional[BitsAndBytesConfig]:
334
+ """
335
+ 获取量化配置
336
+
337
+ Args:
338
+ config: 训练配置
339
+
340
+ Returns:
341
+ BitsAndBytesConfig 或 None
342
+ """
343
+ if not config.use_4bit:
344
+ return None
345
+
346
+ compute_dtype = getattr(torch, config.bnb_4bit_compute_dtype)
347
+
348
+ bnb_config = BitsAndBytesConfig(
349
+ load_in_4bit=True,
350
+ bnb_4bit_quant_type=config.bnb_4bit_quant_type,
351
+ bnb_4bit_use_double_quant=config.bnb_4bit_use_double_quant,
352
+ bnb_4bit_compute_dtype=compute_dtype,
353
+ )
354
+
355
+ logger.info(f"启用 4-bit 量化: {config.bnb_4bit_quant_type}")
356
+ return bnb_config
357
+
358
+
359
+ def load_model_and_tokenizer(
360
+ config: TrainingConfig
361
+ ) -> Tuple[AutoModelForCausalLM, AutoTokenizer]:
362
+ """
363
+ 加载模型和分词器
364
+
365
+ Args:
366
+ config: 训练配置
367
+
368
+ Returns:
369
+ (模型, 分词器) 元组
370
+ """
371
+ logger.info(f"加载模型: {config.model_name_or_path}")
372
+
373
+ # 检查是否使用 Unsloth
374
+ if config.use_unsloth and UNSLOTH_AVAILABLE and config.finetuning_type == "qlora":
375
+ logger.info("使用 Unsloth 加速加载模型")
376
+ model, tokenizer = FastLanguageModel.from_pretrained(
377
+ model_name=config.model_name_or_path,
378
+ max_seq_length=config.max_seq_length,
379
+ load_in_4bit=config.use_4bit,
380
+ trust_remote_code=config.trust_remote_code,
381
+ )
382
+ return model, tokenizer
383
+
384
+ # 标准加载流程
385
+ # 获取量化配置
386
+ quantization_config = get_quantization_config(config)
387
+
388
+ # 加载分词器
389
+ tokenizer = AutoTokenizer.from_pretrained(
390
+ config.model_name_or_path,
391
+ trust_remote_code=config.trust_remote_code,
392
+ padding_side="right",
393
+ )
394
+
395
+ # 设置 pad_token
396
+ if tokenizer.pad_token is None:
397
+ tokenizer.pad_token = tokenizer.eos_token
398
+
399
+ # 加载模型
400
+ has_gpu = torch.cuda.is_available()
401
+ model_kwargs = {
402
+ "trust_remote_code": config.trust_remote_code,
403
+ }
404
+
405
+ # 只在有 GPU 时使用 device_map
406
+ if has_gpu:
407
+ model_kwargs["device_map"] = "auto"
408
+
409
+ if quantization_config is not None:
410
+ model_kwargs["quantization_config"] = quantization_config
411
+
412
+ # 根据 GPU 可用性设置 dtype
413
+ if has_gpu:
414
+ model_kwargs["dtype"] = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
415
+ else:
416
+ model_kwargs["dtype"] = torch.float32
417
+
418
+ model = AutoModelForCausalLM.from_pretrained(
419
+ config.model_name_or_path,
420
+ **model_kwargs
421
+ )
422
+
423
+ # CPU 训练时不需要移动模型
424
+ if not has_gpu:
425
+ logger.info("CPU 模式,模型保持在 CPU")
426
+ else:
427
+ logger.info(f"GPU 模式,模型已加载到 GPU")
428
+
429
+ logger.info(f"模型加载完成,参数量: {model.num_parameters() / 1e9:.2f}B")
430
+ return model, tokenizer
431
+
432
+
433
+ def get_lora_config(config: TrainingConfig) -> LoraConfig:
434
+ """
435
+ 获取 LoRA 配置
436
+
437
+ Args:
438
+ config: 训练配置
439
+
440
+ Returns:
441
+ LoraConfig
442
+ """
443
+ # 确定目标模块
444
+ if "all" in config.lora_target_modules:
445
+ # 对于 Qwen 模型,明确指定目标模块
446
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
447
+ else:
448
+ target_modules = config.lora_target_modules
449
+
450
+ lora_config = LoraConfig(
451
+ r=config.lora_rank,
452
+ lora_alpha=config.lora_alpha,
453
+ lora_dropout=config.lora_dropout,
454
+ target_modules=target_modules,
455
+ bias="none",
456
+ task_type=TaskType.CAUSAL_LM,
457
+ )
458
+
459
+ logger.info(f"LoRA 配置: rank={config.lora_rank}, alpha={config.lora_alpha}, targets={target_modules}")
460
+ return lora_config
461
+
462
+
463
+ def prepare_model_for_training(
464
+ model: AutoModelForCausalLM,
465
+ config: TrainingConfig
466
+ ) -> AutoModelForCausalLM:
467
+ """
468
+ 准备模型进行训练
469
+
470
+ Args:
471
+ model: 基础模型
472
+ config: 训练配置
473
+
474
+ Returns:
475
+ 准备好训练的模型
476
+ """
477
+ # 如果使用 4-bit 量化,需要准备模型
478
+ if config.use_4bit and config.finetuning_type == "qlora":
479
+ model = prepare_model_for_kbit_training(model)
480
+ logger.info("模型已准备用于 k-bit 训练")
481
+
482
+ # 获取 LoRA 配置
483
+ lora_config = get_lora_config(config)
484
+
485
+ # 应用 LoRA
486
+ model = get_peft_model(model, lora_config)
487
+
488
+ # 打印可训练参数
489
+ model.print_trainable_parameters()
490
+
491
+ return model
492
+
493
+
494
+ def get_training_arguments(config: TrainingConfig, dataset_size: int = 1000) -> TrainingArguments:
495
+ """
496
+ 获取训练参数
497
+
498
+ Args:
499
+ config: 训练配置
500
+ dataset_size: 数据集大小,用于估算总步数
501
+
502
+ Returns:
503
+ TrainingArguments
504
+ """
505
+ # 检测是否有 GPU
506
+ has_gpu = torch.cuda.is_available()
507
+
508
+ # 估算总步数(基于数据集大小)
509
+ steps_per_epoch = dataset_size // (config.per_device_train_batch_size * config.gradient_accumulation_steps)
510
+ total_steps = steps_per_epoch * config.num_train_epochs
511
+ warmup_steps = max(1, int(total_steps * config.warmup_ratio))
512
+
513
+ # 根据 GPU 可用性设置精度
514
+ bf16_enabled = has_gpu and torch.cuda.is_bf16_supported()
515
+ fp16_enabled = has_gpu and not bf16_enabled
516
+
517
+ training_args = TrainingArguments(
518
+ output_dir=config.output_dir,
519
+ num_train_epochs=config.num_train_epochs,
520
+ per_device_train_batch_size=config.per_device_train_batch_size,
521
+ gradient_accumulation_steps=config.gradient_accumulation_steps,
522
+ learning_rate=config.learning_rate,
523
+ lr_scheduler_type=config.lr_scheduler_type,
524
+ warmup_steps=warmup_steps,
525
+ max_grad_norm=config.max_grad_norm,
526
+ weight_decay=config.weight_decay,
527
+ logging_steps=config.logging_steps,
528
+ save_steps=config.save_steps,
529
+ save_total_limit=config.save_total_limit,
530
+ bf16=bf16_enabled,
531
+ fp16=fp16_enabled,
532
+ gradient_checkpointing=config.gradient_checkpointing if has_gpu else False,
533
+ optim=config.optim,
534
+ seed=config.seed,
535
+ report_to=[],
536
+ load_best_model_at_end=False,
537
+ remove_unused_columns=False,
538
+ )
539
+
540
+ if has_gpu:
541
+ logger.info(f"检测到 GPU,启用 GPU 加速 (bf16={bf16_enabled}, fp16={fp16_enabled})")
542
+ else:
543
+ logger.warning("未检测到 GPU,使用 CPU 训练(速度较慢)")
544
+
545
+ return training_args
546
+
547
+
548
+ class ProgressCallback(TrainerCallback):
549
+ """训练进度条回调"""
550
+
551
+ def __init__(self):
552
+ self.pbar = None
553
+
554
+ def on_train_begin(self, args, state, control, **kwargs):
555
+ """训练开始时初始化进度条"""
556
+ if state.is_world_process_zero:
557
+ total_steps = state.max_steps
558
+ self.pbar = tqdm(total=total_steps, desc="训练进度", unit="step")
559
+
560
+ def on_step_end(self, args, state, control, **kwargs):
561
+ """每个训练步骤后更新进度条"""
562
+ if self.pbar is not None and state.is_world_process_zero:
563
+ self.pbar.update(1)
564
+
565
+ # 显示当前损失和 VRAM 使用情况
566
+ if state.log_history:
567
+ last_log = state.log_history[-1]
568
+ if 'loss' in last_log:
569
+ self.pbar.set_postfix({
570
+ 'loss': f"{last_log['loss']:.4f}",
571
+ 'lr': f"{last_log.get('learning_rate', 0):.2e}"
572
+ })
573
+
574
+ def on_train_end(self, args, state, control, **kwargs):
575
+ """训练结束时关闭进度条"""
576
+ if self.pbar is not None:
577
+ self.pbar.close()
578
+
579
+
580
+ class VRAMCallback(TrainerCallback):
581
+ """VRAM 监控回调"""
582
+
583
+ def on_log(self, args, state, control, logs=None, **kwargs):
584
+ """在日志记录时输出 VRAM 使用情况"""
585
+ if torch.cuda.is_available():
586
+ gpu_memory = torch.cuda.max_memory_allocated() / (1024 ** 3)
587
+ gpu_memory_reserved = torch.cuda.memory_reserved() / (1024 ** 3)
588
+
589
+ if logs is not None:
590
+ logs["gpu_memory_gb"] = f"{gpu_memory:.2f}"
591
+ logs["gpu_memory_reserved_gb"] = f"{gpu_memory_reserved:.2f}"
592
+
593
+ if state.is_world_process_zero:
594
+ logger.info(
595
+ f"Step {state.global_step}: "
596
+ f"GPU 显存: {gpu_memory:.2f}GB, "
597
+ f"已保留: {gpu_memory_reserved:.2f}GB"
598
+ )
599
+
600
+
601
+ def train(config: TrainingConfig):
602
+ """
603
+ 执行训练
604
+
605
+ Args:
606
+ config: 训练配置
607
+ """
608
+ logger.info("=" * 60)
609
+ logger.info("开始训练流程")
610
+ logger.info("=" * 60)
611
+
612
+ # 加载模型和分词器
613
+ model, tokenizer = load_model_and_tokenizer(config)
614
+
615
+ # 加载并处理数据集
616
+ dataset_dict = load_and_process_dataset(
617
+ dataset_path=config.dataset_path,
618
+ tokenizer=tokenizer,
619
+ dataset_format=config.dataset_format,
620
+ max_seq_length=config.max_seq_length,
621
+ )
622
+
623
+ # 准备模型进行训练
624
+ model = prepare_model_for_training(model, config)
625
+
626
+ # 获取训练参数(传递数据集大小)
627
+ training_args = get_training_arguments(config, dataset_size=len(dataset_dict["train"]))
628
+ logger.info(f"训练参数: {training_args}")
629
+
630
+ # 数据整理器
631
+ data_collator = DataCollatorForSeq2Seq(
632
+ tokenizer=tokenizer,
633
+ padding=True,
634
+ return_tensors="pt",
635
+ )
636
+
637
+ # 创建 Trainer
638
+ trainer = Trainer(
639
+ model=model,
640
+ args=training_args,
641
+ train_dataset=dataset_dict["train"],
642
+ eval_dataset=dataset_dict["test"],
643
+ data_collator=data_collator,
644
+ callbacks=[ProgressCallback(), VRAMCallback()],
645
+ )
646
+
647
+ # 开始训练
648
+ logger.info("开始训练...")
649
+ train_result = trainer.train()
650
+
651
+ # 保存模型
652
+ logger.info(f"保存模型到: {config.output_dir}")
653
+ trainer.save_model(config.output_dir)
654
+ tokenizer.save_pretrained(config.output_dir)
655
+
656
+ # 保存训练结果
657
+ trainer.save_state()
658
+
659
+ # 打印训练结果
660
+ logger.info("=" * 60)
661
+ logger.info("训练完成")
662
+ logger.info(f"训练损失: {train_result.training_loss:.4f}")
663
+ logger.info(f"训练时间: {train_result.metrics.get('train_runtime', 0):.2f} 秒")
664
+ logger.info("=" * 60)
665
+
666
+
667
+ def backup_model(
668
+ model_path: str,
669
+ backup_dir: str = "./backups",
670
+ backup_name: Optional[str] = None
671
+ ) -> str:
672
+ """
673
+ 备份模型到指定目录
674
+
675
+ Args:
676
+ model_path: 模型路径
677
+ backup_dir: 备份目录
678
+ backup_name: 备份名称(默认使用时间戳)
679
+
680
+ Returns:
681
+ 备份路径
682
+ """
683
+ if not os.path.exists(model_path):
684
+ raise FileNotFoundError(f"模型路径不存在: {model_path}")
685
+
686
+ # 创建备份目录
687
+ os.makedirs(backup_dir, exist_ok=True)
688
+
689
+ # 生成备份名称
690
+ if backup_name is None:
691
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
692
+ model_name = os.path.basename(model_path)
693
+ backup_name = f"{model_name}_{timestamp}"
694
+
695
+ backup_path = os.path.join(backup_dir, backup_name)
696
+
697
+ # 如果备份已存在,跳过
698
+ if os.path.exists(backup_path):
699
+ logger.info(f"备份已存在: {backup_path}")
700
+ return backup_path
701
+
702
+ logger.info(f"开始备份模型: {model_path} -> {backup_path}")
703
+
704
+ # 复制模型文件
705
+ if os.path.isdir(model_path):
706
+ shutil.copytree(model_path, backup_path, symlinks=False, ignore_dangling_symlinks=True)
707
+ else:
708
+ shutil.copy2(model_path, backup_path)
709
+
710
+ logger.info(f"模型备份完成: {backup_path}")
711
+ return backup_path
712
+
713
+
714
+ def merge_model(
715
+ base_model_path: str,
716
+ adapter_path: str,
717
+ output_path: str,
718
+ trust_remote_code: bool = True
719
+ ):
720
+ """
721
+ 合并 LoRA 权重到基础模型
722
+
723
+ Args:
724
+ base_model_path: 基础模型路径
725
+ adapter_path: LoRA adapter 路径
726
+ output_path: 输出路径
727
+ trust_remote_code: 是否信任远程代码
728
+ """
729
+ logger.info("=" * 60)
730
+ logger.info("开始合并模型")
731
+ logger.info("=" * 60)
732
+
733
+ # 加载基础模型
734
+ logger.info(f"加载基础模型: {base_model_path}")
735
+ base_model = AutoModelForCausalLM.from_pretrained(
736
+ base_model_path,
737
+ trust_remote_code=trust_remote_code,
738
+ dtype=torch.float16,
739
+ device_map="auto",
740
+ )
741
+
742
+ # 加载 LoRA 模型
743
+ logger.info(f"加载 LoRA adapter: {adapter_path}")
744
+ model = PeftModel.from_pretrained(
745
+ base_model,
746
+ adapter_path,
747
+ device_map="auto",
748
+ )
749
+
750
+ # 合并权重
751
+ logger.info("合并 LoRA 权重...")
752
+ model = model.merge_and_unload()
753
+
754
+ # 保存合并后的模型
755
+ logger.info(f"保存合并后的模型到: {output_path}")
756
+ os.makedirs(output_path, exist_ok=True)
757
+ model.save_pretrained(output_path)
758
+
759
+ # 保存分词器
760
+ tokenizer = AutoTokenizer.from_pretrained(
761
+ adapter_path,
762
+ trust_remote_code=trust_remote_code,
763
+ )
764
+ tokenizer.save_pretrained(output_path)
765
+
766
+ logger.info("=" * 60)
767
+ logger.info("模型合并完成")
768
+ logger.info("=" * 60)
769
+
770
+
771
+ def main():
772
+ """主函数"""
773
+ parser = argparse.ArgumentParser(description="HOS 模型微调工具")
774
+
775
+ # 模型配置
776
+ parser.add_argument("--model", type=str, required=True, help="基础模型路径或名称")
777
+ parser.add_argument("--dataset", type=str, required=True, help="数据集路径(JSON 文件)")
778
+ parser.add_argument("--output", type=str, default="./output", help="输出目录")
779
+
780
+ # 训练方法
781
+ parser.add_argument(
782
+ "--method",
783
+ type=str,
784
+ choices=["qlora", "lora"],
785
+ default="qlora",
786
+ help="训练方法: qlora (4-bit) 或 lora (全精度)"
787
+ )
788
+
789
+ # 数据集配置
790
+ parser.add_argument(
791
+ "--format",
792
+ type=str,
793
+ choices=["alpaca", "sharegpt", "messages"],
794
+ default="alpaca",
795
+ help="数据格式"
796
+ )
797
+ parser.add_argument("--max-seq-length", type=int, default=2048, help="最大序列长度")
798
+
799
+ # LoRA 配置
800
+ parser.add_argument("--lora-rank", type=int, default=16, help="LoRA rank")
801
+ parser.add_argument("--lora-alpha", type=int, default=32, help="LoRA alpha")
802
+ parser.add_argument("--lora-dropout", type=float, default=0.05, help="LoRA dropout")
803
+
804
+ # 训练参数
805
+ parser.add_argument("--epochs", type=int, default=3, help="训练轮数")
806
+ parser.add_argument("--batch-size", type=int, default=2, help="批次大小")
807
+ parser.add_argument("--grad-accum", type=int, default=8, help="梯度累积步数")
808
+ parser.add_argument("--lr", type=float, default=2e-4, help="学习率")
809
+
810
+ # 其他选项
811
+ parser.add_argument("--no-unsloth", action="store_true", help="禁用 Unsloth 加速")
812
+ parser.add_argument("--merge", action="store_true", help="训练后自动合并模型")
813
+ parser.add_argument("--merge-only", action="store_true", help="仅执行模型合并")
814
+ parser.add_argument("--adapter-path", type=str, help="LoRA adapter 路径(用于合并)")
815
+
816
+ args = parser.parse_args()
817
+
818
+ # 创建训练配置
819
+ config = TrainingConfig(
820
+ model_name_or_path=args.model,
821
+ dataset_path=args.dataset,
822
+ dataset_format=args.format,
823
+ max_seq_length=args.max_seq_length,
824
+ finetuning_type=args.method,
825
+ use_4bit=(args.method == "qlora"),
826
+ lora_rank=args.lora_rank,
827
+ lora_alpha=args.lora_alpha,
828
+ lora_dropout=args.lora_dropout,
829
+ output_dir=args.output,
830
+ num_train_epochs=args.epochs,
831
+ per_device_train_batch_size=args.batch_size,
832
+ gradient_accumulation_steps=args.grad_accum,
833
+ learning_rate=args.lr,
834
+ use_unsloth=not args.no_unsloth,
835
+ )
836
+
837
+ # 执行操作
838
+ if args.merge_only:
839
+ if not args.adapter_path:
840
+ raise ValueError("合并模式需要指定 --adapter-path")
841
+ merge_model(
842
+ base_model_path=args.model,
843
+ adapter_path=args.adapter_path,
844
+ output_path=args.output,
845
+ )
846
+ else:
847
+ # 训练
848
+ train(config)
849
+
850
+ # 可选:自动合并
851
+ if args.merge:
852
+ merge_model(
853
+ base_model_path=args.model,
854
+ adapter_path=args.output,
855
+ output_path=f"{args.output}_merged",
856
+ )
857
+
858
+
859
+ if __name__ == "__main__":
860
+ main()