2. データサンプリング
Reading time: 9 minutes
データサンプリング
データサンプリングは、GPTのような大規模言語モデル(LLM)のトレーニングのためにデータを準備する際の重要なプロセスです。これは、モデルが前の単語に基づいて次の単語(またはトークン)を予測する方法を学ぶために使用する入力とターゲットのシーケンスにテキストデータを整理することを含みます。適切なデータサンプリングは、モデルが言語パターンと依存関係を効果的に捉えることを保証します。
tip
この第二段階の目標は非常にシンプルです:入力データをサンプリングし、通常は特定の長さの文にデータセットを分け、期待される応答も生成してトレーニングフェーズのために準備します。
データサンプリングが重要な理由
GPTのようなLLMは、前の単語によって提供されるコンテキストを理解することによってテキストを生成または予測するようにトレーニングされています。これを達成するためには、トレーニングデータは、モデルが単語のシーケンスとその後の単語との関係を学べるように構造化されている必要があります。この構造化されたアプローチにより、モデルは一般化し、一貫性があり文脈に関連したテキストを生成することができます。
データサンプリングの主要概念
- トークン化: テキストをトークン(例:単語、サブワード、または文字)と呼ばれる小さな単位に分解すること。
- シーケンスの長さ(max_length): 各入力シーケンス内のトークンの数。
- スライディングウィンドウ: トークン化されたテキストの上をウィンドウを移動させることによって重複する入力シーケンスを作成する方法。
- ストライド: スライディングウィンドウが次のシーケンスを作成するために前進するトークンの数。
ステップバイステップの例
データサンプリングを説明するために、例を見ていきましょう。
例文
"Lorem ipsum dolor sit amet, consectetur adipiscing elit."
トークン化
基本的なトークナイザーを使用して、テキストを単語と句読点に分割すると仮定します:
Tokens: ["Lorem", "ipsum", "dolor", "sit", "amet,", "consectetur", "adipiscing", "elit."]
パラメータ
- 最大シーケンス長 (max_length): 4 トークン
- スライディングウィンドウストライド: 1 トークン
入力とターゲットシーケンスの作成
- スライディングウィンドウアプローチ:
- 入力シーケンス: 各入力シーケンスは
max_length
トークンで構成されます。 - ターゲットシーケンス: 各ターゲットシーケンスは、対応する入力シーケンスの直後に続くトークンで構成されます。
- シーケンスの生成:
ウィンドウ位置 | 入力シーケンス | ターゲットシーケンス |
---|---|---|
1 | ["Lorem", "ipsum", "dolor", "sit"] | ["ipsum", "dolor", "sit", "amet,"] |
2 | ["ipsum", "dolor", "sit", "amet,"] | ["dolor", "sit", "amet,", "consectetur"] |
3 | ["dolor", "sit", "amet,", "consectetur"] | ["sit", "amet,", "consectetur", "adipiscing"] |
4 | ["sit", "amet,", "consectetur", "adipiscing"] | ["amet,", "consectetur", "adipiscing", "elit."] |
- 結果の入力とターゲット配列:
- 入力:
[
["Lorem", "ipsum", "dolor", "sit"],
["ipsum", "dolor", "sit", "amet,"],
["dolor", "sit", "amet,", "consectetur"],
["sit", "amet,", "consectetur", "adipiscing"],
]
- ターゲット:
[
["ipsum", "dolor", "sit", "amet,"],
["dolor", "sit", "amet,", "consectetur"],
["sit", "amet,", "consectetur", "adipiscing"],
["amet,", "consectetur", "adipiscing", "elit."],
]
視覚的表現
トークン位置 | トークン |
---|---|
1 | Lorem |
2 | ipsum |
3 | dolor |
4 | sit |
5 | amet, |
6 | consectetur |
7 | adipiscing |
8 | elit. |
ストライド1のスライディングウィンドウ:
- 最初のウィンドウ (位置 1-4): ["Lorem", "ipsum", "dolor", "sit"] → ターゲット: ["ipsum", "dolor", "sit", "amet,"]
- 2番目のウィンドウ (位置 2-5): ["ipsum", "dolor", "sit", "amet,"] → ターゲット: ["dolor", "sit", "amet,", "consectetur"]
- 3番目のウィンドウ (位置 3-6): ["dolor", "sit", "amet,", "consectetur"] → ターゲット: ["sit", "amet,", "consectetur", "adipiscing"]
- 4番目のウィンドウ (位置 4-7): ["sit", "amet,", "consectetur", "adipiscing"] → ターゲット: ["amet,", "consectetur", "adipiscing", "elit."]
ストライドの理解
- ストライド1: ウィンドウは毎回1トークン前進し、非常に重複したシーケンスを生成します。これにより、文脈関係の学習が向上する可能性がありますが、類似のデータポイントが繰り返されるため、過学習のリスクが高まる可能性があります。
- ストライド2: ウィンドウは毎回2トークン前進し、重複を減らします。これにより冗長性と計算負荷が減少しますが、文脈のニュアンスを見逃す可能性があります。
- ストライドがmax_lengthに等しい: ウィンドウは全ウィンドウサイズ分前進し、重複のないシーケンスを生成します。これによりデータの冗長性が最小限に抑えられますが、シーケンス間の依存関係を学習するモデルの能力が制限される可能性があります。
ストライド2の例:
同じトークン化されたテキストと max_length
が4の場合:
- 最初のウィンドウ (位置 1-4): ["Lorem", "ipsum", "dolor", "sit"] → ターゲット: ["ipsum", "dolor", "sit", "amet,"]
- 2番目のウィンドウ (位置 3-6): ["dolor", "sit", "amet,", "consectetur"] → ターゲット: ["sit", "amet,", "consectetur", "adipiscing"]
- 3番目のウィンドウ (位置 5-8): ["amet,", "consectetur", "adipiscing", "elit."] → ターゲット: ["consectetur", "adipiscing", "elit.", "sed"] (続きがあると仮定)
コード例
https://github.com/rasbt/LLMs-from-scratch/blob/main/ch02/01_main-chapter-code/ch02.ipynb からのコード例を通じて、これをよりよく理解しましょう。
# Download the text to pre-train the LLM
import urllib.request
url = ("https://raw.githubusercontent.com/rasbt/LLMs-from-scratch/main/ch02/01_main-chapter-code/the-verdict.txt")
file_path = "the-verdict.txt"
urllib.request.urlretrieve(url, file_path)
with open("the-verdict.txt", "r", encoding="utf-8") as f:
raw_text = f.read()
"""
Create a class that will receive some params lie tokenizer and text
and will prepare the input chunks and the target chunks to prepare
the LLM to learn which next token to generate
"""
import torch
from torch.utils.data import Dataset, DataLoader
class GPTDatasetV1(Dataset):
def __init__(self, txt, tokenizer, max_length, stride):
self.input_ids = []
self.target_ids = []
# Tokenize the entire text
token_ids = tokenizer.encode(txt, allowed_special={"<|endoftext|>"})
# Use a sliding window to chunk the book into overlapping sequences of max_length
for i in range(0, len(token_ids) - max_length, stride):
input_chunk = token_ids[i:i + max_length]
target_chunk = token_ids[i + 1: i + max_length + 1]
self.input_ids.append(torch.tensor(input_chunk))
self.target_ids.append(torch.tensor(target_chunk))
def __len__(self):
return len(self.input_ids)
def __getitem__(self, idx):
return self.input_ids[idx], self.target_ids[idx]
"""
Create a data loader which given the text and some params will
prepare the inputs and targets with the previous class and
then create a torch DataLoader with the info
"""
import tiktoken
def create_dataloader_v1(txt, batch_size=4, max_length=256,
stride=128, shuffle=True, drop_last=True,
num_workers=0):
# Initialize the tokenizer
tokenizer = tiktoken.get_encoding("gpt2")
# Create dataset
dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)
# Create dataloader
dataloader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
drop_last=drop_last,
num_workers=num_workers
)
return dataloader
"""
Finally, create the data loader with the params we want:
- The used text for training
- batch_size: The size of each batch
- max_length: The size of each entry on each batch
- stride: The sliding window (how many tokens should the next entry advance compared to the previous one). The smaller the more overfitting, usually this is equals to the max_length so the same tokens aren't repeated.
- shuffle: Re-order randomly
"""
dataloader = create_dataloader_v1(
raw_text, batch_size=8, max_length=4, stride=1, shuffle=False
)
data_iter = iter(dataloader)
first_batch = next(data_iter)
print(first_batch)
# Note the batch_size of 8, the max_length of 4 and the stride of 1
[
# Input
tensor([[ 40, 367, 2885, 1464],
[ 367, 2885, 1464, 1807],
[ 2885, 1464, 1807, 3619],
[ 1464, 1807, 3619, 402],
[ 1807, 3619, 402, 271],
[ 3619, 402, 271, 10899],
[ 402, 271, 10899, 2138],
[ 271, 10899, 2138, 257]]),
# Target
tensor([[ 367, 2885, 1464, 1807],
[ 2885, 1464, 1807, 3619],
[ 1464, 1807, 3619, 402],
[ 1807, 3619, 402, 271],
[ 3619, 402, 271, 10899],
[ 402, 271, 10899, 2138],
[ 271, 10899, 2138, 257],
[10899, 2138, 257, 7026]])
]
# With stride=4 this will be the result:
[
# Input
tensor([[ 40, 367, 2885, 1464],
[ 1807, 3619, 402, 271],
[10899, 2138, 257, 7026],
[15632, 438, 2016, 257],
[ 922, 5891, 1576, 438],
[ 568, 340, 373, 645],
[ 1049, 5975, 284, 502],
[ 284, 3285, 326, 11]]),
# Target
tensor([[ 367, 2885, 1464, 1807],
[ 3619, 402, 271, 10899],
[ 2138, 257, 7026, 15632],
[ 438, 2016, 257, 922],
[ 5891, 1576, 438, 568],
[ 340, 373, 645, 1049],
[ 5975, 284, 502, 284],
[ 3285, 326, 11, 287]])
]