将用于 Swift 微调模型的 JSON Lines(JSONL)格式数据集,转换为适用于 Qwen VL 模型微调的 JSON 格式

将用于 Swift 微调模型的 JSON Lines(JSONL)格式数据集,转换为适用于 Qwen VL 模型微调的 JSON 格式

flyfish

Qwen VL 微调代码

https://github.com/QwenLM/Qwen3-VL

SWIFT微调代码

https://github.com/modelscope/ms-swift

SWIFT微调使用的格式

(Scalable lightWeight Infrastructure for Fine-Tuning)

json 复制代码
{"query": "<image>描述图像", "response": "图中有狗", "images": ["images/1.jpg"]}
{"query": "<image>描述图像", "response": "图中有猫", "images": ["images/2.jpg"]}

微调 Qwen3-VL 使用的格式

json 复制代码
[
  {
    "image": "images/1.jpg",
    "conversations": [
      {
        "from": "human",
        "value": "<image>描述图像"
      },
      {
        "from": "gpt",
        "value": "图中有狗"
      }
    ]
  },
  {
    "image": "images/2.jpg",
    "conversations": [
      {
        "from": "human",
        "value": "<image>描述图像"
      },
      {
        "from": "gpt",
        "value": "图中有猫"
      }
    ]
  }
]

转换代码

python 复制代码
import json
import os

def convert_swift_to_qwen(jsonl_path, output_json_path):
    """
    将Swift微调的JSONL数据集转换为QwenVL格式的JSON文件
    :param jsonl_path: 输入train.jsonl的路径
    :param output_json_path: 输出train_qwen3.json的路径
    """
    # 1. 检查输入文件是否存在
    if not os.path.exists(jsonl_path):
        print(f"错误:输入文件 {jsonl_path} 不存在,请检查路径!")
        return

    # 2. 初始化目标格式的数据集列表
    qwen_dataset = []

    # 3. 逐行读取JSONL并转换格式
    with open(jsonl_path, "r", encoding="utf-8") as jsonl_file:
        line_num = 0  # 记录行号,方便定位错误
        for line in jsonl_file:
            line_num += 1
            # 跳过空行
            if not line.strip():
                continue
            
            try:
                # 解析当前行的JSON数据(原Swift格式)
                swift_data = json.loads(line.strip())
                
                # 检查原数据是否包含必要字段
                required_fields = ["query", "response", "images"]
                if not all(field in swift_data for field in required_fields):
                    print(f"警告:第{line_num}行缺少必要字段(query/response/images),已跳过该行")
                    continue
                if not swift_data["images"]:  # 检查images数组是否为空
                    print(f"警告:第{line_num}行images数组为空,已跳过该行")
                    continue

                # 4. 格式映射(核心步骤)
                qwen_sample = {
                    "image": swift_data["images"][0],  # 取第一张图(原数据为数组)
                    "conversations": [
                        {
                            "from": "human",
                            "value": swift_data["query"].strip()  # 人类提问(含<image>标签)
                        },
                        {
                            "from": "gpt",
                            "value": swift_data["response"].strip().strip('"')  # 模型回答,去除多余引号
                        }
                    ]
                }
                qwen_dataset.append(qwen_sample)

            except json.JSONDecodeError:
                print(f"警告:第{line_num}行JSON格式错误,已跳过该行")
            except Exception as e:
                print(f"警告:第{line_num}行处理失败,错误信息:{str(e)},已跳过该行")

    # 5. 检查是否有有效数据
    if not qwen_dataset:
        print("错误:没有解析到有效数据,无法生成输出文件!")
        return

    # 6. 将转换后的数据写入目标JSON文件(带缩进,方便查看)
    with open(output_json_path, "w", encoding="utf-8") as output_file:
        json.dump(qwen_dataset, output_file, ensure_ascii=False, indent=2)

    print(f"转换完成!共处理 {len(qwen_dataset)} 条有效数据,已保存到 {output_json_path}")


# ------------------- 执行转换 -------------------
# 请根据文件实际路径修改这两个参数!
INPUT_JSONL_PATH = "train.jsonl"       # 输入文件路径
OUTPUT_JSON_PATH = "train_qwen3.json"  # 输出文件路径

convert_swift_to_qwen(INPUT_JSONL_PATH, OUTPUT_JSON_PATH)
相关推荐
JoannaJuanCV6 小时前
vscode debug Transformer源码说明
ide·vscode·transformer·qwen3
songgeb8 小时前
🧩 iOS DiffableDataSource 死锁问题记录
ios·swift
大熊猫侯佩12 小时前
【大话码游之 Observation 传说】上集:月光宝盒里的计数玄机
swiftui·swift·weak·observable·self·引用循环·observations
HarderCoder15 小时前
Swift 方法全解:实例方法、mutating 方法与类型方法一本通
swift
HarderCoder17 小时前
Swift 类型转换实用指北:从 is / as 到 Any/AnyObject 的完整路线
swift
HarderCoder17 小时前
Swift 嵌套类型:在复杂类型内部优雅地组织枚举、结构体与协议
swift
HarderCoder2 天前
Swift 枚举完全指南——从基础语法到递归枚举的渐进式学习笔记
swift
非专业程序员Ping2 天前
从0到1自定义文字排版引擎:原理篇
ios·swift·assembly·font
HarderCoder3 天前
【Swift 筑基记】把“结构体”与“类”掰开揉碎——从值类型与引用类型说起
swift