fineweb2-bagaco2 / classification /benchmark_encode_batch_size.py
booteek-ai's picture
Duplicate from duarteocarmo/fineweb2-bagaco2
8fc7fdd
# /// script
# dependencies = [
# "sentence-transformers",
# "torch",
# "numpy<2",
# "polars[pyarrow]",
# "pyarrow",
# "huggingface_hub",
# ]
# requires-python = ">=3.10"
# ///
"""
Benchmark sentence-transformer encode batch sizes on a representative sample.
Usage:
uv run classification/benchmark_encode_batch_size.py
Useful env vars:
REPO_ID=duarteocarmo/fineweb2-bagaco2
INPUT_PREFIX=fineweb2-ptpt-prototype/
MODEL_NAME=intfloat/multilingual-e5-small
SAMPLE_ROWS=12000
PARQUET_COUNT=2
MAX_CHARS=800
BATCH_SIZES=1024,1536,2048,2560,3072,3584,4096
"""
import os
import subprocess
import time
from pathlib import Path
from types import SimpleNamespace
import polars
from huggingface_hub import HfApi
config = SimpleNamespace(
repo_id=os.getenv("REPO_ID", "duarteocarmo/fineweb2-bagaco2"),
input_prefix=os.getenv("INPUT_PREFIX", "fineweb2-ptpt-prototype/"),
model_name=os.getenv("MODEL_NAME", "intfloat/multilingual-e5-small"),
download_dir=Path(os.getenv("DOWNLOAD_DIR", "./shard_cache")),
sample_rows=int(os.getenv("SAMPLE_ROWS", "12000")),
parquet_count=int(os.getenv("PARQUET_COUNT", "2")),
max_chars=int(os.getenv("MAX_CHARS", "800")),
batch_sizes=[
int(value)
for value in os.getenv(
"BATCH_SIZES", "1024,1536,2048,2560,3072,3584,4096"
).split(",")
if value.strip()
],
)
def get_device() -> str:
import torch
if torch.cuda.is_available():
return "cuda"
if torch.backends.mps.is_available():
return "mps"
return "cpu"
def run_hf_download(*args: str) -> None:
command = ["hf", "download", config.repo_id, "--repo-type", "dataset", *args]
subprocess.run(args=command, check=True)
def list_input_parquets() -> list[str]:
api = HfApi()
files = api.list_repo_files(repo_id=config.repo_id, repo_type="dataset")
parquet_files = sorted(
file_path
for file_path in files
if file_path.startswith(config.input_prefix) and file_path.endswith(".parquet")
)
return parquet_files
def download_input_parquets(parquet_files: list[str]) -> list[Path]:
config.download_dir.mkdir(parents=True, exist_ok=True)
local_paths: list[Path] = []
for parquet_file in parquet_files:
run_hf_download(
"--local-dir",
str(config.download_dir),
parquet_file,
)
local_paths.append(config.download_dir / parquet_file)
return local_paths
def load_texts() -> list[str]:
parquet_files = list_input_parquets()[: config.parquet_count]
if not parquet_files:
raise RuntimeError(
f"No parquet files found under {config.repo_id}/{config.input_prefix}"
)
local_paths = download_input_parquets(parquet_files=parquet_files)
texts: list[str] = []
for local_path in local_paths:
df = polars.read_parquet(local_path).select("text")
texts.extend(df["text"].to_list())
if len(texts) >= config.sample_rows:
break
truncated = [
text[: config.max_chars].strip() for text in texts[: config.sample_rows]
]
truncated = [text for text in truncated if text]
if not truncated:
raise RuntimeError("No texts loaded for benchmarking")
print(
f"Loaded {len(truncated)} texts from {len(local_paths)} parquet files for benchmarking"
)
return truncated
def load_model(device: str):
from sentence_transformers import SentenceTransformer
model_kwargs = {}
if device in ("cuda", "mps"):
model_kwargs["torch_dtype"] = "float16"
model = SentenceTransformer(
config.model_name,
device=device,
model_kwargs=model_kwargs,
)
print(f"Loaded {config.model_name} on {device}")
return model
def warm_up(model, texts: list[str]) -> None:
warmup_size = min(len(texts), 256)
if warmup_size == 0:
return
model.encode(
texts[:warmup_size],
batch_size=min(warmup_size, 256),
show_progress_bar=False,
)
def benchmark_batch_size(model, texts: list[str], batch_size: int, device: str) -> dict:
import torch
if device == "cuda":
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
started_at = time.perf_counter()
try:
embeddings = model.encode(
texts,
batch_size=batch_size,
show_progress_bar=False,
)
except torch.OutOfMemoryError:
if device == "cuda":
torch.cuda.empty_cache()
return {"batch_size": batch_size, "status": "oom"}
except RuntimeError as exc:
if "out of memory" not in str(exc).lower():
raise
if device == "cuda":
torch.cuda.empty_cache()
return {"batch_size": batch_size, "status": "oom"}
elapsed_seconds = time.perf_counter() - started_at
throughput = len(texts) / elapsed_seconds if elapsed_seconds > 0 else 0.0
result = {
"batch_size": batch_size,
"status": "ok",
"seconds": elapsed_seconds,
"texts": len(texts),
"throughput": throughput,
"embedding_shape": tuple(embeddings.shape),
}
if device == "cuda":
peak_memory = torch.cuda.max_memory_allocated() / 1024**3
result["peak_cuda_gb"] = peak_memory
return result
def print_result(result: dict) -> None:
if result["status"] == "oom":
print(f"batch_size={result['batch_size']}: OOM")
return
peak_memory = result.get("peak_cuda_gb")
if peak_memory is None:
print(
f"batch_size={result['batch_size']}: {result['throughput']:.0f} texts/s in {result['seconds']:.1f}s"
)
return
print(
f"batch_size={result['batch_size']}: {result['throughput']:.0f} texts/s in {result['seconds']:.1f}s, peak_cuda={peak_memory:.2f} GiB"
)
def main() -> None:
device = get_device()
print(f"Device: {device}")
print(f"Batch sizes: {config.batch_sizes}")
texts = load_texts()
model = load_model(device=device)
warm_up(model=model, texts=texts)
results = []
for batch_size in config.batch_sizes:
result = benchmark_batch_size(
model=model,
texts=texts,
batch_size=batch_size,
device=device,
)
results.append(result)
print_result(result=result)
successful = [result for result in results if result["status"] == "ok"]
if not successful:
print("No successful batch size found")
return
fastest = max(successful, key=lambda result: result["throughput"])
print("\nRecommended batch size:")
print_result(result=fastest)
if __name__ == "__main__":
main()