Hugging Face + Dask 如何擴展 AI 資料處理
Scaling AI-based Data Processing with Hugging Face + Dask
Hugging Face Blog 示範以 Dask 和 Coiled 把 FineWeb-Edu 網頁分類流程,從 pandas 本機處理 100 行擴展至雲端多 GPU 處理 211 million 行。
FineWeb-Edu 分類案例呈現了由 pandas 本機小批次測試,擴展至 Dask 與 Coiled 雲端多 GPU 處理 211 million 行資料的完整流程,為大型資料集推理提供可參照的工程做法。
Hugging Face 平台提供大量資料集和預訓練模型,讓使用及訓練最先進機器學習模型變得愈來愈容易。然而,AI 資料集通常容量龐大(數百 GB 至數 TB),而使用 Hugging Face transformers 進行模型推論有時運算成本甚高,因此 AI 任務不易擴展。
Dask 是一款用於分散式運算的 Python 程式庫,可把資料集分成容易管理的小塊,進行外存運算(處理容量大於記憶體的資料)。因此可輕鬆完成以下工作:
- 透過容易使用、仿照 pandas 的 API,高效載入及預處理 TB 級資料集
- 平行執行模型推論(亦可選擇在多個節點上使用 GPU 推論)
本文會示範如何處理 FineWeb 資料集,使用 FineWeb-Edu 分類器識別教育價值較高的網頁。我們會展示:
- 如何在本機以 pandas 處理 100 行資料
- 如何使用 Dask,在雲端多個 GPU 上擴展至處理 2.11 億行資料
使用 pandas 處理 100 行資料
FineWeb 資料集包含 15 兆個英文網頁資料 token,資料來源是Common Crawl。這個非牟利組織託管每月更新的公開網頁爬取資料集。FineWeb 常用於多種任務,例如大型語言模型訓練、分類、內容篩選,以及各行各業的資訊檢索。
使用 pandas 在手提電腦上下載並讀取單一檔案,可能需要超過 1 分鐘。
import pandas as pd
df = pd.read_parquet(
"hf://datasets/HuggingFaceFW/fineweb/data/CC-MAIN-2024-10/000_00000.parquet"
)
接著,我們會使用 HF FineWeb-Edu 分類器,評估資料集中網頁的教育價值。網頁會按 0 至 5 分評級:0 代表沒有教育價值,5 代表教育價值很高。我們可用 pandas 處理較小的 100 行資料子集,在配備 GPU 的 M1 Mac 上約需 10 秒。
from transformers import pipeline
def compute_scores(texts):
import torch
# Select which hardware to use
if torch.cuda.is_available():
device = torch.device("cuda")
elif torch.backends.mps.is_available():
device = torch.device("mps")
else:
device = torch.device("cpu")
pipe = pipeline(
"text-classification",
model="HuggingFaceFW/fineweb-edu-classifier",
device=device
)
results = pipe(
texts.to_list(),
batch_size=25, # Choose batch size based on data size and hardware
padding="longest",
truncation=True,
function_to_apply="none"
)
return pd.Series([r["score"] for r in results])
df = df[:100]
min_edu_score = 3
df["edu-classifier-score"] = compute_scores(df.text)
df = df[df["edu-classifier-score"] >= min_edu_score]
請注意,我們亦在 compute_scores 函數中加入檢查可用硬件的步驟,因為下一步使用 Dask 擴展時,這個函數會以分散式方式執行。因此,從單一電腦本機測試(使用 CPU,或使用配備 Apple silicon GPU 的 MacBook),到分散至多部電腦(例如 NVIDIA GPU),都很容易。
使用 Dask 擴展至 2.11 億行資料
2024 年 2 月至 3 月的完整網頁爬取資料,磁碟上的容量為 432 GB,記憶體中約為 715 GB,分為 250 個 Parquet 檔案。即使電腦記憶體足以容納整個資料集,以序列方式處理仍會慢得難以接受。
要擴展處理規模,可使用 Dask DataFrame,透過平行化 pandas 來處理大型表格資料。它與 pandas API 十分相似,因此可輕易由單一資料集測試擴展至完整資料集。Dask 亦能配合 Hugging Face 資料集預設使用的 Parquet 格式,支援豐富資料類型、高效欄式篩選及壓縮。
import dask.dataframe as dd
df = dd.read_parquet(
# Load the full dataset lazily with Dask
"hf://datasets/HuggingFaceFW/fineweb/data/CC-MAIN-2024-10/*.parquet"
)
我們會在 Dask DataFrame 上使用 compute_scores 函數進行文字分類,並透過 map_partitions 對大型 Dask DataFrame 中的每個 pandas DataFrame 平行套用函數。meta 參數是 Dask 專用,用來指定輸出資料結構(欄位名稱及資料類型)。
from transformers import pipeline
def compute_scores(texts):
import torch
# Select which hardware to use
if torch.cuda.is_available():
device = torch.device("cuda")
elif torch.backends.mps.is_available():
device = torch.device("mps")
else:
device = torch.device("cpu")
pipe = pipeline(
"text-classification",
model="HuggingFaceFW/fineweb-edu-classifier",
device=device,
)
results = pipe(
texts.to_list(),
batch_size=768,
padding="longest",
truncation=True,
function_to_apply="none",
)
return pd.Series([r["score"] for r in results])
min_edu_score = 3
df["edu-classifier-score"] = df.text.map_partitions(compute_scores, meta=pd.Series([0]))
df = df[df["edu-classifier-score"] >= min_edu_score]
請注意,我們為此示例選擇了合適的 batch_size;你應按自己的工作流程所用硬件、資料及模型調整此設定(請參閲 HF 批次處理文件)。
找出需要的資料集資料列後,我們可儲存結果供其他下游分析使用。Dask DataFrame 原生支援以分散式方式寫入 Parquet。Hugging Face 使用 commit 追蹤資料集變更,並支援平行寫入 Dask DataFrame。
repo_id = "<your-hf-user>/<your-dataset-name>" # Update with your dataset location
df.to_parquet(f"hf://datasets/{repo_id}")
由於每個檔案都會建立一個 commit,建議在上載後合併提交記錄:
from huggingface_hub import HfApi
HfApi().super_squash_history(repo_id=repo_id, repo_type="dataset")
你亦可使用這個自訂函數,每個 commit 上載多個檔案。
多 GPU 平行模型推論
有多種方法可在不同硬件上部署 Dask。在此我們會使用 Coiled 在雲端部署 Dask,按需要啟動 VM,完成後再清理資源。
cluster = coiled.Cluster(
region="us-east-1", # Same region as data
n_workers=100,
spot_policy="spot_with_fallback", # Use spot instances, if available
worker_vm_types="g5.xlarge", # NVIDIA A10 Tensor Core GPU
worker_options={"nthreads": 1},
)
client = cluster.get_client()
Coiled 在幕後會處理:
- 佈建配備 GPU 硬件的雲端 VM。本例使用 AWS 的
g5.xlarge執行個體。 - 設定適當的 NVIDIA 驅動程式、CUDA 執行階段等。
- 透過 套件同步,自動在雲端 VM 安裝與本機相同的套件,包括工作目錄中的 Python 檔案。
整個工作流程約需 5 小時完成,而且 GPU 硬件利用率良好。
把以上步驟整合起來,完整工作流程如下:
import dask.dataframe as dd
from transformers import pipeline
from huggingface_hub import HfApi
import os
import coiled
cluster = coiled.Cluster(
region="us-east-1",
n_workers=100,
spot_policy="spot_with_fallback",
worker_vm_types="g5.xlarge",
worker_options={"nthreads": 1},
)
client = cluster.get_client()
cluster.send_private_envs(
{"HF_TOKEN": "<your-hf-token>"} # Send credentials over encrypted connection
)
df = dd.read_parquet(
"hf://datasets/HuggingFaceFW/fineweb/data/CC-MAIN-2024-10/*.parquet"
)
def compute_scores(texts):
import torch
# Select which hardware to use
if torch.cuda.is_available():
device = torch.device("cuda")
elif torch.backends.mps.is_available():
device = torch.device("mps")
else:
device = torch.device("cpu")
pipe = pipeline(
"text-classification",
model="HuggingFaceFW/fineweb-edu-classifier",
device=device
)
results = pipe(
texts.to_list(),
batch_size=768,
padding="longest",
truncation=True,
function_to_apply="none"
)
return pd.Series([r["score"] for r in results])
min_edu_score = 3
df["edu-classifier-score"] = df.text.map_partitions(compute_scores, meta=pd.Series([0]))
df = df[df["edu-classifier-score"] >= min_edu_score]
repo_id = "<your-hf-user>/<your-dataset-name>" # Replace with your dataset location
df.to_parquet(f"hf://datasets/{repo_id}")
HfApi().super_squash_history(repo_id=repo_id, repo_type="dataset") # optional: squash commit history
總結
Hugging Face + Dask 是強大組合。在這個示例中,我們使用 Dask + Coiled,讓工作流程在雲端多個 GPU 上平行執行,把分類任務由 100 行擴展至 2.11 億行。
同類工作流程亦可用於其他情境,例如:
- 篩選基因組資料,選出感興趣的基因
- 從非結構化文字抽取資訊,並轉化為結構化資料集
- 清理從互聯網或 Common Crawl 擷取的文字資料
- 執行多模態模型推論,分析大型音訊、圖像或影片資料集
來源:Hugging Face Blog · huggingface.co