File size: 7,569 Bytes
c9aee57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
从训练日志中提取loss数据,保存为JSONL格式。

2loss 实验说明:
- 去掉了 region loss
- context loss 权重调整为 0.25(和 DeCLIP 一致)
- 因此不需要进行归一化,直接对比
"""

import re
import json
import os
from pathlib import Path


# 配置
DECLIP_LOG = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/DeCLIP_EVA-B_DINOv2-B_560/out.log"
INTEGRATED_2LOSS_LOG = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/Integrated_EVA-B_DINOv2-B_560_2loss/out.log"
OUTPUT_DIR = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/decoupling_analysis/2loss/results/data"


def parse_training_line(line: str) -> dict | None:
    """
    解析训练日志行,提取loss数据。
    
    格式示例:
    2026-01-22,15:50:21 | INFO | Train Epoch: 0 [    16/118287 (0%)] ... Loss_context: 2.2152 (2.2152) Loss_content: 0.55079 (0.55079) Loss: 2.7660 (2.7660)
    """
    if "Train Epoch:" not in line:
        return None
    
    try:
        # 提取时间戳
        timestamp_match = re.match(r'(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2})', line)
        timestamp = timestamp_match.group(1) if timestamp_match else None
        
        # 提取epoch
        epoch_match = re.search(r'Train Epoch:\s*(\d+)', line)
        epoch = int(epoch_match.group(1)) if epoch_match else None
        
        # 提取当前step和总step
        step_match = re.search(r'\[\s*(\d+)/(\d+)', line)
        current_step = int(step_match.group(1)) if step_match else None
        total_steps = int(step_match.group(2)) if step_match else None
        
        # 提取LR
        lr_match = re.search(r'LR:\s*([\d.e+-]+)', line)
        lr = float(lr_match.group(1)) if lr_match else None
        
        # 提取Loss_context (当前值)
        context_match = re.search(r'Loss_context:\s*([\d.e+-]+)', line)
        loss_context = float(context_match.group(1)) if context_match else None
        
        # 提取Loss_content (当前值)
        content_match = re.search(r'Loss_content:\s*([\d.e+-]+)', line)
        loss_content = float(content_match.group(1)) if content_match else None
        
        # 提取总Loss (当前值) - 注意匹配 "Loss:" 但不匹配 "Loss_xxx:"
        total_match = re.search(r'Loss:\s*([\d.e+-]+)\s*\(', line)
        loss_total = float(total_match.group(1)) if total_match else None
        
        if all(v is not None for v in [epoch, loss_context, loss_content, loss_total]):
            return {
                "timestamp": timestamp,
                "epoch": epoch,
                "step": current_step,
                "total_steps": total_steps,
                "lr": lr,
                "loss_context": loss_context,
                "loss_content": loss_content,
                "loss_total": loss_total
            }
    except Exception as e:
        print(f"解析行失败: {line[:100]}... 错误: {e}")
    
    return None


def parse_validation_line(line: str) -> dict | None:
    """
    解析验证指标行。
    """
    if "rois.thing.macc1" not in line:
        return None
    
    try:
        # 提取时间戳
        timestamp_match = re.match(r'(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2})', line)
        timestamp = timestamp_match.group(1) if timestamp_match else None
        
        # 提取字典部分
        dict_match = re.search(r'\{[^}]+\}', line)
        if dict_match:
            dict_str = dict_match.group(0).replace("'", '"')
            metrics = json.loads(dict_str)
            
            return {
                "timestamp": timestamp,
                "metrics": metrics
            }
    except Exception as e:
        print(f"解析验证行失败: {line[:100]}... 错误: {e}")
    
    return None


def extract_from_log(log_path: str, model_name: str) -> tuple[list, list]:
    """
    从日志文件中提取训练loss和验证指标。
    """
    training_data = []
    validation_data = []
    
    print(f"正在解析日志: {log_path}")
    
    with open(log_path, 'r', encoding='utf-8') as f:
        for line in f:
            # 尝试解析训练行
            train_record = parse_training_line(line)
            if train_record:
                train_record["model"] = model_name
                training_data.append(train_record)
                continue
            
            # 尝试解析验证行
            val_record = parse_validation_line(line)
            if val_record:
                val_record["model"] = model_name
                validation_data.append(val_record)
    
    print(f"  - 提取到 {len(training_data)} 条训练记录")
    print(f"  - 提取到 {len(validation_data)} 条验证记录")
    
    return training_data, validation_data


def save_jsonl(data: list, filepath: str):
    """保存数据为JSONL格式。"""
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    with open(filepath, 'w', encoding='utf-8') as f:
        for record in data:
            f.write(json.dumps(record, ensure_ascii=False) + '\n')
    print(f"已保存: {filepath} ({len(data)} 条记录)")


def main():
    print("=" * 60)
    print("训练数据提取工具 (2loss 版本)")
    print("=" * 60)
    print("说明: 2loss 实验已将 context loss 权重调整为 0.25,无需归一化")
    print()
    
    # 提取DeCLIP数据
    declip_train, declip_val = extract_from_log(DECLIP_LOG, model_name="DeCLIP")
    
    # 提取Integrated_2loss数据
    integrated_train, integrated_val = extract_from_log(
        INTEGRATED_2LOSS_LOG,
        model_name="Integrated_2loss"
    )
    
    print()
    print("=" * 60)
    print("保存数据")
    print("=" * 60)
    
    # 保存训练数据
    save_jsonl(declip_train, os.path.join(OUTPUT_DIR, "declip_training.jsonl"))
    save_jsonl(integrated_train, os.path.join(OUTPUT_DIR, "integrated_2loss_training.jsonl"))
    
    # 保存验证数据
    all_validation = declip_val + integrated_val
    save_jsonl(all_validation, os.path.join(OUTPUT_DIR, "validation_metrics.jsonl"))
    
    # 打印统计信息
    print()
    print("=" * 60)
    print("数据统计")
    print("=" * 60)
    
    print("\n【DeCLIP训练数据】")
    if declip_train:
        epochs = set(r["epoch"] for r in declip_train)
        print(f"  Epoch范围: {min(epochs)} - {max(epochs)}")
        print(f"  总记录数: {len(declip_train)}")
        print(f"  最终Loss: context={declip_train[-1]['loss_context']:.4f}, "
              f"content={declip_train[-1]['loss_content']:.4f}, "
              f"total={declip_train[-1]['loss_total']:.4f}")
    
    print("\n【Integrated_2loss训练数据】")
    if integrated_train:
        epochs = set(r["epoch"] for r in integrated_train)
        print(f"  Epoch范围: {min(epochs)} - {max(epochs)}")
        print(f"  总记录数: {len(integrated_train)}")
        print(f"  最终Loss: context={integrated_train[-1]['loss_context']:.4f}, "
              f"content={integrated_train[-1]['loss_content']:.4f}, "
              f"total={integrated_train[-1]['loss_total']:.4f}")
    
    print("\n【验证指标】")
    for val in all_validation:
        print(f"  {val['model']} @ {val['timestamp']}:")
        m = val['metrics']
        print(f"    rois.thing.macc1: {m['rois.thing.macc1']:.4f}")
        print(f"    maskpool.thing.macc1: {m['maskpool.thing.macc1']:.4f}")
    
    print()
    print("=" * 60)
    print("提取完成!")
    print("=" * 60)


if __name__ == "__main__":
    main()