著者: Jerry Fan

AIの学習データにJSONLを使う

AI・機械学習向けの学習データをJSONLで準備するための総合ガイドです。OpenAIのファインチューニング、Anthropic Claude、HuggingFaceのデータセット、データの検証、大規模なデータパイプラインについて解説します。

JSONLがAIの学習データの標準になった理由

JSONL(JSON Lines)は、AI・機械学習の学習データにおける事実上の標準となっています。OpenAI、Anthropic、HuggingFaceをはじめ、主要なAIプロバイダーはいずれも、ファインチューニング用データセットの主な形式としてJSONLを採用しています。その理由は、1行に1つのサンプルを格納する構造にあります。この構造により、学習中のデータのストリーミング、サンプルのシャッフル、レコード数の集計、学習用・テスト用データへの分割が簡単に行えます。新しいサンプルを追加する際も、ファイル全体を書き換える必要はありません。

単一のJSON配列は使用前に全体をパースする必要がありますが、JSONLファイルは1行ずつ処理できます。サンプル数が数百万件、ファイルサイズがギガバイト単位に達する学習データセットでは、この違いが重要になります。このガイドでは、OpenAI、Anthropic Claude、HuggingFaceがそれぞれ求めるJSONL形式の詳細と、データの検証・クリーニング方法、本番の学習に向けた大規模データセットの準備方法を解説します。

学習データをオンラインで検証

OpenAI、Anthropic、HuggingFaceにアップロードする前に、無料のブラウザツールでJSONL学習データを検証・整形・変換できます。

OpenAIのファインチューニング用JSONL形式

OpenAIは、ファインチューニングとBatch APIの両方でJSONLを使用しています。GPT-4o-miniなどのチャットモデルをファインチューニングする場合、各行には標準的なChat Completionの構造に従ったmessages配列が必要です。system、user、assistantの3つのロールを使って、モデルに再現させたい会話を定義します。

各行が1つの学習サンプルに対応します。systemメッセージでモデルの振る舞いを指定し、userメッセージに入力を、assistantメッセージにモデルが学習すべき正解の出力を記述します。

Chat Completionの学習データ形式
{"messages": [{"role": "system", "content": "You are a helpful customer support agent for an e-commerce platform."}, {"role": "user", "content": "Where is my order #12345?"}, {"role": "assistant", "content": "I can see that order #12345 was shipped on February 10th via FedEx. The tracking number is FX987654321. Based on the latest update, it should arrive by February 14th."}]}
{"messages": [{"role": "system", "content": "You are a helpful customer support agent for an e-commerce platform."}, {"role": "user", "content": "I want to return my purchase."}, {"role": "assistant", "content": "I would be happy to help with your return. Could you please provide the order number and the reason for the return? Our return policy allows returns within 30 days of delivery for most items."}]}

複数ターンの会話を学習させる場合は、会話履歴をすべて含めます。モデルはmessages配列内のすべてのassistantの応答から学習します。これにより、追加の質問にも対応できるようになります。

複数ターンの会話を学習させる
{"messages": [{"role": "system", "content": "You are a Python programming tutor."}, {"role": "user", "content": "What is a list comprehension?"}, {"role": "assistant", "content": "A list comprehension is a concise way to create lists in Python. Instead of writing a for loop to build a list, you can write it in one line: [expression for item in iterable if condition]."}, {"role": "user", "content": "Can you show me an example?"}, {"role": "assistant", "content": "Sure! Here is an example that creates a list of squares for even numbers:\n\nsquares = [x**2 for x in range(10) if x % 2 == 0]\n# Result: [0, 4, 16, 36, 64]\n\nThis is equivalent to:\nsquares = []\nfor x in range(10):\n    if x % 2 == 0:\n        squares.append(x**2)"}]}

OpenAIでは学習サンプルが最低10件必要ですが、はっきりとした改善を得るには50〜100件が推奨されています。すべてのメッセージにroleとcontentフィールドが必要です。systemメッセージは省略できますが、モデルの振る舞いを一貫させるために含めることが推奨されています。アップロード前に、OpenAI CLIでファイルを検証してください:openai tools fine_tunes.prepare_data -f training.jsonl

Anthropic Claudeの学習データ形式

Anthropicは、ClaudeモデルのファインチューニングにJSONLを使用しています。humanとassistantのやり取りを、構造化された会話として記述する形式です。具体的な形式はファインチューニングの方法やAPIのバージョンによって異なりますが、基本的にはMessages APIの構造に従います。

各行には、システムプロンプトと、user・assistantのメッセージが交互に並ぶ会話を記述します。モデルは会話の文脈に応じたassistantの応答を生成するように学習します。

ClaudeのMessages形式
{"system": "You are a medical information assistant. Provide accurate, general health information while always recommending consulting a healthcare professional.", "messages": [{"role": "user", "content": "What are the symptoms of vitamin D deficiency?"}, {"role": "assistant", "content": "Common symptoms of vitamin D deficiency include fatigue and tiredness, bone pain and muscle weakness, mood changes including depression, slow wound healing, and frequent infections. However, many people with mild deficiency may not notice symptoms. A blood test is the only way to confirm your vitamin D levels. I recommend speaking with your doctor who can order the appropriate test and recommend supplementation if needed."}]}
{"system": "You are a medical information assistant. Provide accurate, general health information while always recommending consulting a healthcare professional.", "messages": [{"role": "user", "content": "Is it safe to take ibuprofen daily?"}, {"role": "assistant", "content": "Taking ibuprofen daily for extended periods can carry risks including stomach ulcers and gastrointestinal bleeding, increased risk of heart attack and stroke, kidney problems with long-term use, and potential interactions with other medications. For occasional pain relief, short-term use at recommended doses is generally considered safe for most adults. However, if you find yourself needing daily pain relief, please consult your doctor. They can evaluate the underlying cause and recommend a safer long-term treatment plan."}]}

複数ターンの学習データでは、userとassistantのメッセージを交互に並べ、会話全体を含めます。モデルは会話の流れと、やり取りを重ねても文脈を維持する方法を学習します。

Claudeでの複数ターンの会話
{"system": "You are a cooking assistant specializing in Italian cuisine.", "messages": [{"role": "user", "content": "How do I make carbonara?"}, {"role": "assistant", "content": "Authentic carbonara uses just five ingredients: spaghetti, guanciale (cured pork cheek), eggs, Pecorino Romano cheese, and black pepper. The key technique is tempering the egg mixture with the hot pasta water so it creates a creamy sauce without scrambling."}, {"role": "user", "content": "Can I use bacon instead of guanciale?"}, {"role": "assistant", "content": "While guanciale gives the most authentic flavor, pancetta is a closer substitute. Bacon works in a pinch but its smoky flavor changes the dish significantly. If using bacon, choose an unsmoked variety. Whichever you use, cut it into small pieces and render the fat slowly over medium-low heat until crispy."}]}

HuggingFaceのデータセットでJSONLを使う

HuggingFaceのdatasetsライブラリは、JSONL形式の入力に標準で対応しています。ローカルのJSONLファイルの読み込み、リモートデータセットのストリーミング、形式の相互変換を簡単に行えます。HuggingFace Hubでデータセットを共有する際にも、JSONLが推奨されています。

datasetsライブラリを使って、JSONLファイルをDatasetオブジェクトに読み込みます。メモリマップによる効率的なアクセスや、組み込みの学習用・テスト用データ分割機能を利用でき、Trainer APIともスムーズに連携できます。

JSONLデータセットの読み込み
from datasets import load_dataset


# Load a local JSONL file
dataset = load_dataset('json', data_files='training.jsonl')
print(dataset)
# DatasetDict({
#     train: Dataset({
#         features: ['messages', 'system'],
#         num_rows: 5000
#     })
# })


# Load with train/test split
dataset = load_dataset('json', data_files={
    'train': 'train.jsonl',
    'test': 'test.jsonl'
})


# Stream a large remote dataset
dataset = load_dataset(
    'json',
    data_files='https://example.com/large_dataset.jsonl',
    streaming=True
)
for example in dataset['train']:
    print(example)
    break

HuggingFaceの任意のデータセットをJSONL形式に変換すれば、ほかの学習パイプラインでも利用できます。to_jsonメソッドは、各サンプルを個別の行にJSONとして書き出します。

JSONLへのエクスポート
from datasets import load_dataset


# Load a dataset from the Hub
dataset = load_dataset('squad', split='train')


# Export to JSONL
dataset.to_json('squad_train.jsonl')
print(f'Exported {len(dataset)} examples')


# Export with specific columns
dataset.select_columns(['question', 'context', 'answers']).to_json(
    'squad_filtered.jsonl'
)


# Process and export
def format_for_finetuning(example):
    return {
        'messages': [
            {'role': 'user', 'content': example['question']},
            {'role': 'assistant', 'content': example['answers']['text'][0]}
        ]
    }


formatted = dataset.map(format_for_finetuning, remove_columns=dataset.column_names)
formatted.to_json('squad_chat_format.jsonl')

データの検証とクリーニング

学習データの品質は、モデルの性能に直接影響します。不正なJSON、フィールドの欠落、長すぎるサンプル、データの重複は、いずれもファインチューニングの結果を悪化させる原因になります。学習を始める前に、必ずJSONLファイルを検証し、クリーニングしてください。

このスクリプトはJSONLファイルを行ごとに検証し、不正なJSON、必須フィールドの欠落、空のコンテンツ、トークン数といった、よくある問題を確認します。アップロード前に実行して、問題を早い段階で見つけてください。

JSONL学習データの検証スクリプト
import json
import sys
from collections import Counter


def validate_training_data(path: str) -> dict:
    """Validate a JSONL file for AI fine-tuning."""
    stats = Counter()
    errors = []


    with open(path, 'r', encoding='utf-8') as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            stats['total'] += 1


            # Check valid JSON
            try:
                data = json.loads(line)
            except json.JSONDecodeError as e:
                errors.append(f'Line {line_num}: Invalid JSON - {e}')
                stats['invalid_json'] += 1
                continue


            # Check messages field exists
            if 'messages' not in data:
                errors.append(f'Line {line_num}: Missing "messages" field')
                stats['missing_messages'] += 1
                continue


            messages = data['messages']


            # Check message structure
            for i, msg in enumerate(messages):
                if 'role' not in msg:
                    errors.append(f'Line {line_num}, msg {i}: Missing "role"')
                    stats['missing_role'] += 1
                if 'content' not in msg:
                    errors.append(f'Line {line_num}, msg {i}: Missing "content"')
                    stats['missing_content'] += 1
                elif not msg['content'].strip():
                    errors.append(f'Line {line_num}, msg {i}: Empty content')
                    stats['empty_content'] += 1


            # Check has at least one assistant message
            roles = [m.get('role') for m in messages]
            if 'assistant' not in roles:
                errors.append(f'Line {line_num}: No assistant message')
                stats['no_assistant'] += 1


            stats['valid'] += 1


    return {'stats': dict(stats), 'errors': errors[:50]}


result = validate_training_data('training.jsonl')
print(f"Total: {result['stats'].get('total', 0)}")
print(f"Valid: {result['stats'].get('valid', 0)}")
if result['errors']:
    print(f"\nFirst {len(result['errors'])} errors:")
    for err in result['errors']:
        print(f'  {err}')

学習サンプルの重複は計算リソースの無駄になるだけでなく、データ中に多く現れるパターンへモデルを偏らせるおそれがあります。このスクリプトは、各行の内容のハッシュ値を使って、内容が完全に一致する重複サンプルを除去します。

重複を除去するスクリプト
import json
import hashlib


def deduplicate_jsonl(input_path: str, output_path: str) -> dict:
    """Remove duplicate training examples from a JSONL file."""
    seen_hashes = set()
    total = 0
    unique = 0


    with open(input_path, 'r') as fin, open(output_path, 'w') as fout:
        for line in fin:
            line = line.strip()
            if not line:
                continue
            total += 1


            # Hash the normalized JSON to catch formatting differences
            data = json.loads(line)
            canonical = json.dumps(data, sort_keys=True)
            content_hash = hashlib.sha256(canonical.encode()).hexdigest()


            if content_hash not in seen_hashes:
                seen_hashes.add(content_hash)
                fout.write(json.dumps(data) + '\n')
                unique += 1


    duplicates = total - unique
    print(f'Total: {total}, Unique: {unique}, Removed: {duplicates}')
    return {'total': total, 'unique': unique, 'duplicates': duplicates}


deduplicate_jsonl('training.jsonl', 'training_deduped.jsonl')

大規模な学習データの準備

本番の学習に使うデータセットには、数十万件から数百万件のサンプルが含まれることも珍しくありません。この規模では、JSONLデータのシャッフル、学習用・テスト用への分割、シャーディングを自動化するパイプラインが必要です。適切に準備することで、破滅的忘却などの学習時の問題を防ぎ、実験の再現性を確保できます。

このスクリプトは、データをランダムにシャッフルしてから、学習用とテスト用に分割します。JSONLファイルは一定の順序で生成されることが多く、そのまま学習に使うと汎化性能が低下するおそれがあるため、シャッフルが欠かせません。

学習用・テスト用への分割とシャッフルのパイプライン
import json
import random
from pathlib import Path


def prepare_training_data(
    input_path: str,
    output_dir: str,
    test_ratio: float = 0.1,
    seed: int = 42
) -> dict:
    """Shuffle and split JSONL into train/test sets."""
    random.seed(seed)
    output = Path(output_dir)
    output.mkdir(parents=True, exist_ok=True)


    # Load all examples
    examples = []
    with open(input_path, 'r') as f:
        for line in f:
            line = line.strip()
            if line:
                examples.append(json.loads(line))


    # Shuffle
    random.shuffle(examples)


    # Split
    split_idx = int(len(examples) * (1 - test_ratio))
    train_data = examples[:split_idx]
    test_data = examples[split_idx:]


    # Write output files
    train_path = output / 'train.jsonl'
    test_path = output / 'test.jsonl'


    for data, path in [(train_data, train_path), (test_data, test_path)]:
        with open(path, 'w') as f:
            for example in data:
                f.write(json.dumps(example) + '\n')


    print(f'Train: {len(train_data)} examples -> {train_path}')
    print(f'Test:  {len(test_data)} examples -> {test_path}')
    return {'train': len(train_data), 'test': len(test_data)}


prepare_training_data(
    'all_examples.jsonl',
    './prepared_data/',
    test_ratio=0.1,
    seed=42
)

データセットが大きすぎて単一のファイルでは扱いにくい場合や、複数のGPUで分散学習を行う場合は、JSONLファイルを小さなファイルに分割します。分割した各ファイル(シャード)は、個別に処理できます。

分散学習に向けたファイルのシャーディング
import json
from pathlib import Path


def shard_jsonl(
    input_path: str,
    output_dir: str,
    shard_size: int = 50000
) -> int:
    """Split a large JSONL file into smaller shards."""
    output = Path(output_dir)
    output.mkdir(parents=True, exist_ok=True)


    shard_num = 0
    line_count = 0
    current_file = None


    with open(input_path, 'r') as fin:
        for line in fin:
            line = line.strip()
            if not line:
                continue


            if line_count % shard_size == 0:
                if current_file:
                    current_file.close()
                shard_path = output / f'shard_{shard_num:04d}.jsonl'
                current_file = open(shard_path, 'w')
                shard_num += 1


            current_file.write(line + '\n')
            line_count += 1


    if current_file:
        current_file.close()


    print(f'Created {shard_num} shards from {line_count} examples')
    return shard_num


shard_jsonl('large_dataset.jsonl', './shards/', shard_size=50000)

学習データの準備を始めましょう

ブラウザ上でJSONL学習データファイルを検証・整形し、内容を確認できます。アップロードもユーザー登録も不要で、プライバシーは100%守られます。

よくある質問

参考資料