lxcxjxhx commited on
Commit
ffa24ce
·
verified ·
1 Parent(s): 6099266

Upload tests/test_train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tests/test_train.py +589 -0
tests/test_train.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 训练模块单元测试
3
+
4
+ 测试训练模块的所有功能,包括:
5
+ - QLoRA 配置
6
+ - LoRA 配置
7
+ - 数据集加载和处理
8
+ - 模型合并
9
+ - 训练流程
10
+
11
+ 使用 mock 避免实际训练和模型加载。
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ import pytest
17
+ from pathlib import Path
18
+ from unittest.mock import MagicMock, patch, Mock
19
+ import json
20
+
21
+ # 添加项目路径
22
+ sys.path.insert(0, str(Path(__file__).parent.parent))
23
+
24
+ from hos_optimizer.train import (
25
+ TrainingConfig,
26
+ DatasetProcessor,
27
+ load_and_process_dataset,
28
+ get_quantization_config,
29
+ load_model_and_tokenizer,
30
+ get_lora_config,
31
+ prepare_model_for_training,
32
+ get_training_arguments,
33
+ VRAMCallback,
34
+ train,
35
+ merge_model,
36
+ )
37
+
38
+
39
+ class TestTrainingConfig:
40
+ """训练配置测试"""
41
+
42
+ def test_default_config(self):
43
+ """测试默认配置"""
44
+ config = TrainingConfig()
45
+
46
+ assert config.model_name_or_path == "Qwen/Qwen2.5-0.5B"
47
+ assert config.finetuning_type == "qlora"
48
+ assert config.use_4bit is True
49
+ assert config.lora_rank == 16
50
+ assert config.lora_alpha == 32
51
+ assert config.num_train_epochs == 3
52
+ assert config.learning_rate == 2e-4
53
+
54
+ def test_custom_config(self):
55
+ """测试自定义配置"""
56
+ config = TrainingConfig(
57
+ model_name_or_path="custom/model",
58
+ finetuning_type="lora",
59
+ use_4bit=False,
60
+ lora_rank=32,
61
+ lora_alpha=64,
62
+ num_train_epochs=5,
63
+ learning_rate=1e-4
64
+ )
65
+
66
+ assert config.model_name_or_path == "custom/model"
67
+ assert config.finetuning_type == "lora"
68
+ assert config.use_4bit is False
69
+ assert config.lora_rank == 32
70
+ assert config.lora_alpha == 64
71
+ assert config.num_train_epochs == 5
72
+ assert config.learning_rate == 1e-4
73
+
74
+
75
+ class TestDatasetProcessor:
76
+ """数据集处理器测试"""
77
+
78
+ def test_format_alpaca_with_input(self):
79
+ """测试 Alpaca 格式带输入的处理"""
80
+ mock_tokenizer = MagicMock()
81
+ processor = DatasetProcessor(mock_tokenizer, max_seq_length=512)
82
+
83
+ example = {
84
+ "instruction": "什么是网络安全?",
85
+ "input": "请举例说明",
86
+ "output": "网络安全是指保护计算机网络免受未经授权的访问。"
87
+ }
88
+
89
+ result = processor.format_alpaca(example)
90
+
91
+ assert "### 指令:" in result["text"]
92
+ assert "什么是网络安全?" in result["text"]
93
+ assert "### 输入:" in result["text"]
94
+ assert "请举例说明" in result["text"]
95
+ assert "### 回答:" in result["text"]
96
+ assert "保护计算机网络" in result["text"]
97
+
98
+ def test_format_alpaca_without_input(self):
99
+ """测试 Alpaca 格式不带输入的处理"""
100
+ mock_tokenizer = MagicMock()
101
+ processor = DatasetProcessor(mock_tokenizer, max_seq_length=512)
102
+
103
+ example = {
104
+ "instruction": "什么是网络安全?",
105
+ "input": "",
106
+ "output": "网络安全是指保护计算机网络。"
107
+ }
108
+
109
+ result = processor.format_alpaca(example)
110
+
111
+ assert "### 指令:" in result["text"]
112
+ assert "什么是网络安全?" in result["text"]
113
+ assert "### 输入:" not in result["text"]
114
+ assert "### 回答:" in result["text"]
115
+
116
+ def test_format_sharegpt(self):
117
+ """测试 ShareGPT 格式的处理"""
118
+ mock_tokenizer = MagicMock()
119
+ processor = DatasetProcessor(mock_tokenizer, max_seq_length=512)
120
+
121
+ example = {
122
+ "conversations": [
123
+ {"from": "human", "value": "你好"},
124
+ {"from": "gpt", "value": "你好!有什么可以帮助你的吗?"},
125
+ ]
126
+ }
127
+
128
+ result = processor.format_sharegpt(example)
129
+
130
+ assert "### 用户:" in result["text"]
131
+ assert "你好" in result["text"]
132
+ assert "### 助手:" in result["text"]
133
+ assert "帮助你的吗" in result["text"]
134
+
135
+ def test_tokenize_function(self):
136
+ """测试分词函数"""
137
+ mock_tokenizer = MagicMock()
138
+ mock_tokenizer.return_value = {
139
+ "input_ids": [1, 2, 3, 4, 5],
140
+ "attention_mask": [1, 1, 1, 1, 1]
141
+ }
142
+
143
+ processor = DatasetProcessor(mock_tokenizer, max_seq_length=512)
144
+
145
+ example = {"text": "测试文本"}
146
+ result = processor.tokenize_function(example)
147
+
148
+ assert "input_ids" in result
149
+ assert "attention_mask" in result
150
+ assert "labels" in result
151
+ assert result["labels"] == result["input_ids"]
152
+
153
+ def test_process_dataset_alpaca(self):
154
+ """测试处理 Alpaca 格式数据集"""
155
+ mock_tokenizer = MagicMock()
156
+ mock_tokenizer.return_value = {
157
+ "input_ids": [1, 2, 3],
158
+ "attention_mask": [1, 1, 1]
159
+ }
160
+ mock_tokenizer.num_proc = 4
161
+
162
+ processor = DatasetProcessor(mock_tokenizer, max_seq_length=512)
163
+
164
+ mock_dataset = MagicMock()
165
+ mock_dataset.__len__.return_value = 10
166
+ mock_dataset.column_names = ["instruction", "input", "output"]
167
+
168
+ # Mock map 方法
169
+ def mock_map(func, **kwargs):
170
+ return mock_dataset
171
+
172
+ mock_dataset.map = mock_map
173
+
174
+ result = processor.process_dataset(mock_dataset, dataset_format="alpaca")
175
+
176
+ assert result is not None
177
+
178
+ def test_process_dataset_invalid_format(self):
179
+ """测试处理无效格式数据集"""
180
+ mock_tokenizer = MagicMock()
181
+ processor = DatasetProcessor(mock_tokenizer, max_seq_length=512)
182
+
183
+ mock_dataset = MagicMock()
184
+
185
+ with pytest.raises(ValueError) as exc_info:
186
+ processor.process_dataset(mock_dataset, dataset_format="invalid_format")
187
+
188
+ assert "不支持的数据格式" in str(exc_info.value)
189
+
190
+
191
+ class TestLoadAndProcessDataset:
192
+ """数据集加载和处理测试"""
193
+
194
+ def test_load_dataset_file_not_found(self):
195
+ """测试加载不存在的数据集文件"""
196
+ mock_tokenizer = MagicMock()
197
+
198
+ with pytest.raises(FileNotFoundError) as exc_info:
199
+ load_and_process_dataset(
200
+ dataset_path="/nonexistent/dataset.json",
201
+ tokenizer=mock_tokenizer
202
+ )
203
+
204
+ assert "数据集文件不存在" in str(exc_info.value)
205
+
206
+ def test_load_dataset_success(self, tmp_dir):
207
+ """测试成功加载数据集"""
208
+ # 创建测试数据集
209
+ dataset_path = os.path.join(tmp_dir, "dataset.json")
210
+ data = [
211
+ {
212
+ "instruction": "测试指令",
213
+ "input": "",
214
+ "output": "测试输出"
215
+ }
216
+ ]
217
+ with open(dataset_path, "w", encoding="utf-8") as f:
218
+ json.dump(data, f, ensure_ascii=False)
219
+
220
+ mock_tokenizer = MagicMock()
221
+ mock_tokenizer.return_value = {
222
+ "input_ids": [1, 2, 3],
223
+ "attention_mask": [1, 1, 1]
224
+ }
225
+ mock_tokenizer.num_proc = 4
226
+
227
+ with patch("hos_optimizer.train.load_dataset") as mock_load:
228
+ mock_dataset = MagicMock()
229
+ mock_dataset.__len__.return_value = 10
230
+ mock_dataset.column_names = ["instruction", "input", "output"]
231
+ mock_dataset.map.return_value = mock_dataset
232
+ mock_dataset.train_test_split.return_value = {
233
+ "train": MagicMock(__len__=MagicMock(return_value=9)),
234
+ "test": MagicMock(__len__=MagicMock(return_value=1))
235
+ }
236
+ mock_load.return_value = mock_dataset
237
+
238
+ result = load_and_process_dataset(
239
+ dataset_path=dataset_path,
240
+ tokenizer=mock_tokenizer,
241
+ dataset_format="alpaca",
242
+ max_seq_length=512,
243
+ test_size=0.1
244
+ )
245
+
246
+ assert "train" in result
247
+ assert "test" in result
248
+
249
+
250
+ class TestQuantizationConfig:
251
+ """量化配置测试"""
252
+
253
+ def test_get_quantization_config_disabled(self):
254
+ """测试禁用量化配置"""
255
+ config = TrainingConfig(use_4bit=False)
256
+
257
+ result = get_quantization_config(config)
258
+
259
+ assert result is None
260
+
261
+ def test_get_quantization_config_enabled(self):
262
+ """测试启用量化配置"""
263
+ config = TrainingConfig(
264
+ use_4bit=True,
265
+ bnb_4bit_quant_type="nf4",
266
+ bnb_4bit_use_double_quant=True,
267
+ bnb_4bit_compute_dtype="bfloat16"
268
+ )
269
+
270
+ with patch("hos_optimizer.train.BitsAndBytesConfig") as mock_bnb:
271
+ mock_config = MagicMock()
272
+ mock_bnb.return_value = mock_config
273
+
274
+ result = get_quantization_config(config)
275
+
276
+ assert result is not None
277
+ mock_bnb.assert_called_once()
278
+
279
+
280
+ class TestLoadModelAndTokenizer:
281
+ """模型和分词器加载测试"""
282
+
283
+ def test_load_model_standard(self):
284
+ """测试标准模型加载"""
285
+ config = TrainingConfig(
286
+ model_name_or_path="test/model",
287
+ use_unsloth=False,
288
+ use_4bit=False
289
+ )
290
+
291
+ with patch("hos_optimizer.train.AutoTokenizer") as mock_tokenizer_cls, \
292
+ patch("hos_optimizer.train.AutoModelForCausalLM") as mock_model_cls:
293
+
294
+ mock_tokenizer = MagicMock()
295
+ mock_tokenizer.pad_token = None
296
+ mock_tokenizer.eos_token = "<eos>"
297
+ mock_tokenizer_cls.from_pretrained.return_value = mock_tokenizer
298
+
299
+ mock_model = MagicMock()
300
+ mock_model.num_parameters.return_value = 1e9
301
+ mock_model_cls.from_pretrained.return_value = mock_model
302
+
303
+ model, tokenizer = load_model_and_tokenizer(config)
304
+
305
+ assert model is not None
306
+ assert tokenizer is not None
307
+ assert tokenizer.pad_token == "<eos>"
308
+
309
+ def test_load_model_with_unsloth(self):
310
+ """测试使用 Unsloth 加载模型"""
311
+ config = TrainingConfig(
312
+ model_name_or_path="test/model",
313
+ use_unsloth=True,
314
+ finetuning_type="qlora"
315
+ )
316
+
317
+ with patch("hos_optimizer.train.UNSLOTH_AVAILABLE", True), \
318
+ patch("hos_optimizer.train.FastLanguageModel") as mock_fast:
319
+
320
+ mock_model = MagicMock()
321
+ mock_tokenizer = MagicMock()
322
+ mock_fast.from_pretrained.return_value = (mock_model, mock_tokenizer)
323
+
324
+ model, tokenizer = load_model_and_tokenizer(config)
325
+
326
+ assert model is not None
327
+ assert tokenizer is not None
328
+ mock_fast.from_pretrained.assert_called_once()
329
+
330
+ def test_load_model_with_quantization(self):
331
+ """测试带量化的模型加载"""
332
+ config = TrainingConfig(
333
+ model_name_or_path="test/model",
334
+ use_unsloth=False,
335
+ use_4bit=True
336
+ )
337
+
338
+ with patch("hos_optimizer.train.get_quantization_config") as mock_get_quant, \
339
+ patch("hos_optimizer.train.AutoTokenizer") as mock_tokenizer_cls, \
340
+ patch("hos_optimizer.train.AutoModelForCausalLM") as mock_model_cls:
341
+
342
+ mock_quant_config = MagicMock()
343
+ mock_get_quant.return_value = mock_quant_config
344
+
345
+ mock_tokenizer = MagicMock()
346
+ mock_tokenizer.pad_token = "<pad>"
347
+ mock_tokenizer_cls.from_pretrained.return_value = mock_tokenizer
348
+
349
+ mock_model = MagicMock()
350
+ mock_model.num_parameters.return_value = 1e9
351
+ mock_model_cls.from_pretrained.return_value = mock_model
352
+
353
+ model, tokenizer = load_model_and_tokenizer(config)
354
+
355
+ assert model is not None
356
+ # 验证量化配置被传递
357
+ call_kwargs = mock_model_cls.from_pretrained.call_args[1]
358
+ assert "quantization_config" in call_kwargs
359
+
360
+
361
+ class TestLoraConfig:
362
+ """LoRA 配置测试"""
363
+
364
+ def test_get_lora_config_all_modules(self):
365
+ """测试所有模块的 LoRA 配置"""
366
+ config = TrainingConfig(
367
+ lora_rank=16,
368
+ lora_alpha=32,
369
+ lora_dropout=0.05,
370
+ lora_target_modules=["all"]
371
+ )
372
+
373
+ with patch("hos_optimizer.train.LoraConfig") as mock_lora:
374
+ mock_config = MagicMock()
375
+ mock_lora.return_value = mock_config
376
+
377
+ result = get_lora_config(config)
378
+
379
+ assert result is not None
380
+ mock_lora.assert_called_once()
381
+ # 验证 target_modules 为 None(表示所有模块)
382
+ call_kwargs = mock_lora.call_args[1]
383
+ assert call_kwargs["target_modules"] is None
384
+
385
+ def test_get_lora_config_specific_modules(self):
386
+ """测试特定模块的 LoRA 配置"""
387
+ config = TrainingConfig(
388
+ lora_rank=16,
389
+ lora_alpha=32,
390
+ lora_dropout=0.05,
391
+ lora_target_modules=["q_proj", "v_proj"]
392
+ )
393
+
394
+ with patch("hos_optimizer.train.LoraConfig") as mock_lora:
395
+ mock_config = MagicMock()
396
+ mock_lora.return_value = mock_config
397
+
398
+ result = get_lora_config(config)
399
+
400
+ assert result is not None
401
+ call_kwargs = mock_lora.call_args[1]
402
+ assert call_kwargs["target_modules"] == ["q_proj", "v_proj"]
403
+
404
+
405
+ class TestPrepareModelForTraining:
406
+ """模型训练准备测试"""
407
+
408
+ def test_prepare_model_qlora(self):
409
+ """测试 QLoRA 模式的模型准备"""
410
+ config = TrainingConfig(
411
+ use_4bit=True,
412
+ finetuning_type="qlora"
413
+ )
414
+
415
+ mock_model = MagicMock()
416
+
417
+ with patch("hos_optimizer.train.prepare_model_for_kbit_training") as mock_prepare, \
418
+ patch("hos_optimizer.train.get_lora_config") as mock_get_lora, \
419
+ patch("hos_optimizer.train.get_peft_model") as mock_get_peft:
420
+
421
+ mock_prepare.return_value = mock_model
422
+ mock_lora_config = MagicMock()
423
+ mock_get_lora.return_value = mock_lora_config
424
+ mock_get_peft.return_value = mock_model
425
+
426
+ result = prepare_model_for_training(mock_model, config)
427
+
428
+ assert result is not None
429
+ mock_prepare.assert_called_once()
430
+ mock_get_peft.assert_called_once()
431
+
432
+ def test_prepare_model_lora(self):
433
+ """测试 LoRA 模式的模型准备"""
434
+ config = TrainingConfig(
435
+ use_4bit=False,
436
+ finetuning_type="lora"
437
+ )
438
+
439
+ mock_model = MagicMock()
440
+
441
+ with patch("hos_optimizer.train.get_lora_config") as mock_get_lora, \
442
+ patch("hos_optimizer.train.get_peft_model") as mock_get_peft:
443
+
444
+ mock_lora_config = MagicMock()
445
+ mock_get_lora.return_value = mock_lora_config
446
+ mock_get_peft.return_value = mock_model
447
+
448
+ result = prepare_model_for_training(mock_model, config)
449
+
450
+ assert result is not None
451
+ mock_get_peft.assert_called_once()
452
+
453
+
454
+ class TestTrainingArguments:
455
+ """训练参数测试"""
456
+
457
+ def test_get_training_arguments(self):
458
+ """测试获取训练参数"""
459
+ config = TrainingConfig(
460
+ output_dir="./test_output",
461
+ num_train_epochs=5,
462
+ per_device_train_batch_size=4,
463
+ learning_rate=1e-4
464
+ )
465
+
466
+ with patch("hos_optimizer.train.TrainingArguments") as mock_args:
467
+ mock_training_args = MagicMock()
468
+ mock_args.return_value = mock_training_args
469
+
470
+ result = get_training_arguments(config)
471
+
472
+ assert result is not None
473
+ mock_args.assert_called_once()
474
+
475
+
476
+ class TestVRAMCallback:
477
+ """VRAM 回调测试"""
478
+
479
+ def test_vram_callback_on_log(self):
480
+ """测试 VRAM 回调的日志记录"""
481
+ callback = VRAMCallback()
482
+
483
+ mock_args = MagicMock()
484
+ mock_state = MagicMock()
485
+ mock_state.global_step = 100
486
+ mock_state.is_world_process_zero = True
487
+ mock_control = MagicMock()
488
+ logs = {}
489
+
490
+ with patch("torch.cuda.is_available", return_value=True), \
491
+ patch("torch.cuda.max_memory_allocated", return_value=4 * 1024 ** 3), \
492
+ patch("torch.cuda.memory_reserved", return_value=6 * 1024 ** 3):
493
+
494
+ callback.on_log(mock_args, mock_state, mock_control, logs=logs)
495
+
496
+ assert "gpu_memory_gb" in logs
497
+ assert "gpu_memory_reserved_gb" in logs
498
+
499
+
500
+ class TestTrain:
501
+ """训练流程测试"""
502
+
503
+ def test_train_success(self, tmp_dir):
504
+ """测试成功训练流程"""
505
+ # 创建测试数据集
506
+ dataset_path = os.path.join(tmp_dir, "dataset.json")
507
+ data = [{"instruction": "测试", "input": "", "output": "输出"}]
508
+ with open(dataset_path, "w", encoding="utf-8") as f:
509
+ json.dump(data, f, ensure_ascii=False)
510
+
511
+ config = TrainingConfig(
512
+ model_name_or_path="test/model",
513
+ dataset_path=dataset_path,
514
+ output_dir=os.path.join(tmp_dir, "output")
515
+ )
516
+
517
+ with patch("hos_optimizer.train.load_model_and_tokenizer") as mock_load, \
518
+ patch("hos_optimizer.train.load_and_process_dataset") as mock_load_dataset, \
519
+ patch("hos_optimizer.train.prepare_model_for_training") as mock_prepare, \
520
+ patch("hos_optimizer.train.get_training_arguments") as mock_get_args, \
521
+ patch("hos_optimizer.train.Trainer") as mock_trainer_cls, \
522
+ patch("hos_optimizer.train.DataCollatorForSeq2Seq"):
523
+
524
+ mock_model = MagicMock()
525
+ mock_tokenizer = MagicMock()
526
+ mock_load.return_value = (mock_model, mock_tokenizer)
527
+
528
+ mock_dataset_dict = {
529
+ "train": MagicMock(),
530
+ "test": MagicMock()
531
+ }
532
+ mock_load_dataset.return_value = mock_dataset_dict
533
+
534
+ mock_prepare.return_value = mock_model
535
+
536
+ mock_training_args = MagicMock()
537
+ mock_get_args.return_value = mock_training_args
538
+
539
+ mock_trainer = MagicMock()
540
+ mock_train_result = MagicMock()
541
+ mock_train_result.training_loss = 0.5
542
+ mock_train_result.metrics = {"train_runtime": 100.0}
543
+ mock_trainer.train.return_value = mock_train_result
544
+ mock_trainer_cls.return_value = mock_trainer
545
+
546
+ train(config)
547
+
548
+ mock_trainer.train.assert_called_once()
549
+ mock_trainer.save_model.assert_called_once()
550
+
551
+
552
+ class TestMergeModel:
553
+ """模型合并测试"""
554
+
555
+ def test_merge_model_success(self, tmp_dir):
556
+ """测试成功合并模型"""
557
+ base_model_path = "/path/to/base"
558
+ adapter_path = "/path/to/adapter"
559
+ output_path = os.path.join(tmp_dir, "merged")
560
+
561
+ with patch("hos_optimizer.train.AutoModelForCausalLM") as mock_model_cls, \
562
+ patch("hos_optimizer.train.PeftModel") as mock_peft, \
563
+ patch("hos_optimizer.train.AutoTokenizer") as mock_tokenizer_cls, \
564
+ patch("os.makedirs"):
565
+
566
+ mock_base_model = MagicMock()
567
+ mock_model_cls.from_pretrained.return_value = mock_base_model
568
+
569
+ mock_peft_model = MagicMock()
570
+ mock_merged_model = MagicMock()
571
+ mock_peft.from_pretrained.return_value = mock_peft_model
572
+ mock_peft_model.merge_and_unload.return_value = mock_merged_model
573
+
574
+ mock_tokenizer = MagicMock()
575
+ mock_tokenizer_cls.from_pretrained.return_value = mock_tokenizer
576
+
577
+ merge_model(
578
+ base_model_path=base_model_path,
579
+ adapter_path=adapter_path,
580
+ output_path=output_path
581
+ )
582
+
583
+ mock_peft_model.merge_and_unload.assert_called_once()
584
+ mock_merged_model.save_pretrained.assert_called_once_with(output_path)
585
+ mock_tokenizer.save_pretrained.assert_called_once_with(output_path)
586
+
587
+
588
+ if __name__ == "__main__":
589
+ pytest.main([__file__, "-v"])