File size: 6,787 Bytes
8fc7fdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# /// 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()