将用于 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)