File size: 13,694 Bytes
f115e56
 
 
4691031
f115e56
4691031
f115e56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4691031
 
 
 
 
 
 
 
 
 
 
f115e56
 
 
 
 
 
 
 
 
 
 
 
 
4691031
 
 
 
 
f115e56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4691031
 
 
 
f115e56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4691031
 
 
 
 
 
f115e56
 
 
 
 
 
 
 
 
 
4691031
 
 
 
 
 
 
 
 
f115e56
4691031
f115e56
 
 
 
 
 
 
 
 
 
 
 
 
4691031
 
 
 
 
f115e56
4691031
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f115e56
4691031
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f115e56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4691031
f115e56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4691031
 
 
 
f115e56
 
 
 
 
 
 
 
4691031
 
f115e56
 
 
 
 
4691031
 
 
 
 
 
f115e56
 
 
 
4691031
 
 
 
 
 
 
 
 
 
f115e56
 
 
 
 
 
4691031
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f115e56
 
 
 
 
 
 
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
"""Train both classifiers, enrich every dataset shard, and upload the result."""

import json
import multiprocessing
import subprocess
import time
from pathlib import Path

import fire
import numpy as numpy
import polars as polars
import torch
from sentence_transformers import SentenceTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import StandardScaler

HERE = Path(__file__).resolve().parent
MODEL = "intfloat/multilingual-e5-small"
REPO = "duarteocarmo/bagaco3"
TARGETS = ("educational_score", "category")
MAX_CHARS = 1_500
CHUNK_SIZE = 20_000


def classifier() -> LogisticRegression:
    return LogisticRegression(
        class_weight="balanced",
        max_iter=5_000,
        random_state=42,
    )


def features_for(
    *,
    texts: list[str],
    model: SentenceTransformer,
    scaler: StandardScaler,
    batch_size: int,
) -> numpy.ndarray:
    embeddings = model.encode(
        inputs=[text[:MAX_CHARS] for text in texts],
        batch_size=batch_size,
        normalize_embeddings=True,
        show_progress_bar=False,
    )
    lengths = numpy.log1p(numpy.array([len(text) for text in texts])).reshape(-1, 1)
    return numpy.column_stack(tup=(embeddings, scaler.transform(X=lengths) * 0.1))


def evaluation_for(
    *,
    labels: list,
    features: numpy.ndarray,
) -> dict:
    splitter = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
    train_indices, test_indices = next(splitter.split(X=features, y=labels))
    evaluator = classifier().fit(
        X=features[train_indices],
        y=[labels[index] for index in train_indices],
    )
    actual = [labels[index] for index in test_indices]
    predicted = evaluator.predict(X=features[test_indices])
    report_labels = sorted(set(labels))
    return {
        "labels": report_labels,
        "classification_report": classification_report(
            y_true=actual,
            y_pred=predicted,
            labels=report_labels,
            output_dict=True,
            zero_division=0,
        ),
        "confusion_matrix": confusion_matrix(
            y_true=actual,
            y_pred=predicted,
            labels=report_labels,
        ).tolist(),
    }


def load_model(*, device: str) -> SentenceTransformer:
    model_kwargs = {"torch_dtype": torch.float16} if device.startswith("cuda") else {}
    precision = "float16" if model_kwargs else "float32"
    print(f"Loading {MODEL} on {device} with {precision}", flush=True)
    return SentenceTransformer(
        model_name_or_path=MODEL,
        device=device,
        model_kwargs=model_kwargs,
    )


def train_classifiers(
    *,
    output_dir: Path,
    device: str,
    batch_size: int,
) -> tuple[SentenceTransformer, StandardScaler, dict[str, LogisticRegression]]:
    annotations = polars.read_parquet(
        source=HERE / "data/annotated.parquet",
        columns=["text", *TARGETS],
    ).drop_nulls()
    texts = annotations.get_column("text").to_list()
    lengths = numpy.log1p(numpy.array([len(text) for text in texts])).reshape(-1, 1)
    scaler = StandardScaler().fit(X=lengths)
    model = load_model(device=device)
    print(
        f"Encoding {annotations.height:,} annotated rows and training classifiers",
        flush=True,
    )
    features = features_for(
        texts=texts,
        model=model,
        scaler=scaler,
        batch_size=batch_size,
    )
    labels = {target: annotations.get_column(target).to_list() for target in TARGETS}
    metrics = {
        target: evaluation_for(labels=labels[target], features=features)
        for target in TARGETS
    }
    classifiers = {
        target: classifier().fit(X=features, y=labels[target]) for target in TARGETS
    }
    (output_dir / "classification_metrics.json").write_text(
        json.dumps(obj=metrics, indent=2) + "\n",
        encoding="utf-8",
    )
    print(
        f"Trained and evaluated both classifiers on {annotations.height:,} rows",
        flush=True,
    )
    return model, scaler, classifiers


def classify_shard(
    *,
    source_file: Path,
    output_file: Path,
    model: SentenceTransformer,
    scaler: StandardScaler,
    classifiers: dict[str, LogisticRegression],
    batch_size: int,
) -> polars.DataFrame:
    if output_file.exists():
        return polars.read_parquet(
            source=output_file,
            columns=[*TARGETS, "char_len"],
        )
    with source_file.open(mode="rb") as file:
        if file.read(4) != b"PAR1":
            raise RuntimeError(f"{source_file} is a Git LFS pointer; run git lfs pull")
    data = polars.read_parquet(source=source_file, low_memory=True)
    predictions = {target: [] for target in TARGETS}
    for chunk in data.iter_slices(n_rows=CHUNK_SIZE):
        features = features_for(
            texts=chunk.get_column("text").to_list(),
            model=model,
            scaler=scaler,
            batch_size=batch_size,
        )
        for target in TARGETS:
            predictions[target].extend(
                classifiers[target].predict(X=features).tolist()
            )
    columns = {
        target: polars.Series(values=values)
        for target, values in predictions.items()
    }
    columns["char_len"] = polars.col("text").str.len_chars()
    classified = data.with_columns(**columns)
    temporary_file = output_file.with_suffix(".parquet.tmp")
    classified.write_parquet(file=temporary_file, compression="zstd")
    temporary_file.replace(output_file)
    return classified.select([*TARGETS, "char_len"])


def summary_for(*, data: polars.DataFrame, target: str) -> polars.DataFrame:
    return data.group_by(target).agg(
        polars.len().cast(polars.UInt64).alias("rows"),
        polars.col("char_len").cast(polars.UInt64).sum().alias("total_chars"),
    )


def format_duration(*, seconds: float) -> str:
    minutes, seconds = divmod(int(seconds), 60)
    hours, minutes = divmod(minutes, 60)
    return f"{hours:d}h {minutes:02d}m {seconds:02d}s"


def classify_dataset(
    *,
    source_files: list[Path],
    output_dir: Path,
    model: SentenceTransformer,
    scaler: StandardScaler,
    classifiers: dict[str, LogisticRegression],
    batch_size: int,
) -> dict[str, list[polars.DataFrame]]:
    summaries = {target: [] for target in TARGETS}
    classification_seconds = 0.0
    classified_count = 0
    total_to_classify = sum(
        not (output_dir / source_file.name).exists() for source_file in source_files
    )
    print(
        f"Classifying {len(source_files):,} shards on {model.device}",
        flush=True,
    )
    for index, source_file in enumerate(source_files, start=1):
        started_at = time.monotonic()
        output_file = output_dir / source_file.name
        existed = output_file.exists()
        classified = classify_shard(
            source_file=source_file,
            output_file=output_file,
            model=model,
            scaler=scaler,
            classifiers=classifiers,
            batch_size=batch_size,
        )
        for target in TARGETS:
            summaries[target].append(summary_for(data=classified, target=target))
        action = "Kept" if existed else "Classified"
        if not existed:
            classification_seconds += time.monotonic() - started_at
            classified_count += 1
        remaining = total_to_classify - classified_count
        eta = classification_seconds / classified_count * remaining if classified_count else 0
        print(
            f"{action} shard {index:,}/{len(source_files):,} "
            f"({source_file.name}): {classified.height:,} rows; "
            f"ETA {format_duration(seconds=eta)}",
            flush=True,
        )
    return summaries


def classify_worker(
    *,
    worker_index: int,
    source_files: list[Path],
    output_dir: Path,
    scaler: StandardScaler,
    classifiers: dict[str, LogisticRegression],
    batch_size: int,
) -> None:
    device = f"cuda:{worker_index}"
    model = load_model(device=device)
    classify_dataset(
        source_files=source_files,
        output_dir=output_dir,
        model=model,
        scaler=scaler,
        classifiers=classifiers,
        batch_size=batch_size,
    )


def classify_in_parallel(
    *,
    source_files: list[Path],
    output_dir: Path,
    scaler: StandardScaler,
    classifiers: dict[str, LogisticRegression],
    batch_size: int,
    workers: int,
) -> None:
    context = multiprocessing.get_context(method="spawn")
    processes = [
        context.Process(
            target=classify_worker,
            kwargs={
                "worker_index": worker_index,
                "source_files": source_files[worker_index::workers],
                "output_dir": output_dir,
                "scaler": scaler,
                "classifiers": classifiers,
                "batch_size": batch_size,
            },
        )
        for worker_index in range(workers)
    ]
    started_at = time.monotonic()
    for process in processes:
        process.start()
    for process in processes:
        process.join()
    failed = [process.exitcode for process in processes if process.exitcode != 0]
    if failed:
        raise RuntimeError(f"Classifier workers failed with exit codes {failed}")
    elapsed = time.monotonic() - started_at
    print(
        f"Completed {len(source_files):,} shards with {workers} workers in "
        f"{format_duration(seconds=elapsed)}",
        flush=True,
    )


def summaries_for_outputs(
    *,
    source_files: list[Path],
    output_dir: Path,
) -> dict[str, list[polars.DataFrame]]:
    summaries = {target: [] for target in TARGETS}
    for source_file in source_files:
        classified = polars.read_parquet(
            source=output_dir / source_file.name,
            columns=[*TARGETS, "char_len"],
        )
        for target in TARGETS:
            summaries[target].append(summary_for(data=classified, target=target))
    return summaries


def save_class_counts(
    *,
    summaries: dict[str, list[polars.DataFrame]],
    output_dir: Path,
) -> None:
    counts = {
        target: (
            polars.concat(items=summaries[target])
            .group_by(target)
            .agg(polars.col("rows").sum(), polars.col("total_chars").sum())
            .sort(target)
            .to_dicts()
        )
        for target in TARGETS
    }
    (output_dir / "class_counts.json").write_text(
        json.dumps(obj=counts, indent=2) + "\n",
        encoding="utf-8",
    )
    print(f"Saved metrics and class counts to {output_dir}", flush=True)


def upload_outputs(*, output_dir: Path, repo: str) -> None:
    subprocess.run(
        args=[
            "uvx",
            "--from",
            "huggingface-hub",
            "hf",
            "upload-large-folder",
            repo,
            str(output_dir),
            "--repo-type=dataset",
            "--include=*.parquet",
            "--include=*.json",
        ],
        check=True,
    )
    print(
        f"Uploaded dataset to https://huggingface.co/datasets/{repo}",
        flush=True,
    )


def main(
    input_dir: str = str(HERE.parent),
    output_dir: str = str(HERE.parent / "classified"),
    repo: str = REPO,
    device: str = "cuda",
    batch_size: int = 256,
    workers: int = 1,
    dry_run: bool = False,
    upload: bool = True,
) -> None:
    """Classify the cloned dataset and optionally upload the enriched shards."""
    if device.startswith("cuda") and not torch.cuda.is_available():
        raise RuntimeError("CUDA is unavailable")
    if workers < 1:
        raise RuntimeError("workers must be at least 1")
    if workers > 1 and device != "cuda":
        raise RuntimeError("Multiple workers require device=cuda")
    if workers > torch.cuda.device_count() and device == "cuda":
        raise RuntimeError(f"Requested {workers} workers but found {torch.cuda.device_count()} GPUs")
    source_files = sorted(Path(input_dir).glob("*.parquet"))
    if not source_files:
        raise RuntimeError(f"No Parquet files found in {input_dir}")
    output_path = Path(output_dir)
    if dry_run:
        source_files = source_files[:workers]
        output_path = output_path.with_name(f"{output_path.name}-dry-run")
        if output_path.exists():
            raise RuntimeError(f"Dry-run output already exists: {output_path}")
        upload = False
        print(
            f"Dry run: processing {len(source_files)} shards with {workers} workers",
            flush=True,
        )
    output_path.mkdir(parents=True, exist_ok=True)
    model, scaler, classifiers = train_classifiers(
        output_dir=output_path,
        device=device,
        batch_size=batch_size,
    )
    if workers == 1:
        summaries = classify_dataset(
            source_files=source_files,
            output_dir=output_path,
            model=model,
            scaler=scaler,
            classifiers=classifiers,
            batch_size=batch_size,
        )
    else:
        del model
        torch.cuda.empty_cache()
        classify_in_parallel(
            source_files=source_files,
            output_dir=output_path,
            scaler=scaler,
            classifiers=classifiers,
            batch_size=batch_size,
            workers=workers,
        )
        summaries = summaries_for_outputs(
            source_files=source_files,
            output_dir=output_path,
        )
    save_class_counts(summaries=summaries, output_dir=output_path)
    if upload:
        upload_outputs(output_dir=output_path, repo=repo)


if __name__ == "__main__":
    fire.Fire(component=main)