llm-annotator 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ from .annotator import Annotator
@@ -0,0 +1,692 @@
1
+ import gc
2
+ import json
3
+ import shutil
4
+ import string
5
+ from dataclasses import dataclass, field
6
+ from math import ceil
7
+ from os import PathLike
8
+ from pathlib import Path
9
+ from typing import Any, Iterable
10
+
11
+ import torch
12
+ from datasets import Dataset, IterableDataset, concatenate_datasets, get_dataset_split_names, load_dataset
13
+ from huggingface_hub import create_branch, create_repo, upload_large_folder
14
+ from tqdm import tqdm
15
+ from transformers import AutoTokenizer, PreTrainedTokenizer
16
+ from vllm import LLM, RequestOutput, SamplingParams
17
+ from vllm.distributed import destroy_distributed_environment, destroy_model_parallel
18
+ from vllm.sampling_params import GuidedDecodingParams
19
+
20
+ from llm_annotator.utils import remove_empty_jsonl_files, retry
21
+
22
+
23
+ @dataclass
24
+ class Annotator:
25
+ """Sensible base class for LLM-based dataset annotation.
26
+
27
+ This class provides a framework for annotating datasets using large language models
28
+ through the vLLM library. It handles dataset loading, processing, and output generation
29
+ with support for streaming, batching, and uploading to Hugging Face Hub.
30
+
31
+ Args:
32
+ model_id: The Hugging Face model identifier or local path.
33
+ prompt_template_file: Path to the prompt template file. Can/should contain fields in `{}`
34
+ that match dataset column names, e.g. "Analyze the following text: {text}".
35
+ prompt_template: Prompt template string (alternative to prompt_template_file). Can/should
36
+ contain fields in `{}` that match dataset column names, e.g. "Analyze the
37
+ following text: {text}".
38
+ prompt_field_swapper: Optional mapping to replace template fields. Useful if you want to use
39
+ the same template with different datasets that use different field names.
40
+ output_schema_file: Path to a JSON schema file for guided decoding (optional).
41
+ output_schema: JSON schema as a dictionary or string (alternative to output_schema_file).
42
+ whitespace_pattern: Regex pattern for whitespace handling in guided decoding.
43
+ idx_column: Column name to use as unique identifier.
44
+ num_proc: Number of processes for dataset operations.
45
+ tensor_parallel_size: Number of GPUs for tensor parallelism. Especially useful if running on
46
+ multiple GPUs; set to the number of GPUs available.
47
+ max_num_seqs: Maximum number of sequences to process in parallel (~batch size).
48
+ gpu_memory_utilization: Max. GPU memory utilization goal.
49
+ enforce_eager: Whether to enforce eager execution mode. Eager mode is safer but may be slower.
50
+ quantization: Quantization method to use (optional).
51
+ verbose: Whether to enable verbose logging.
52
+ keep_columns: Columns to keep in output. True for all, None/false-y for none. Available default columns are
53
+ {self.idx_column}, {self.prefix}prompted (filled-in prompt), {self.prefix}response (raw model output).
54
+ If a JSON schema is given, also {self.prefix}valid_fields (boolean if all required fields were valid
55
+ according to output_schema) and output columns according to the JSON schema if given.
56
+ upload_every_n_samples: Upload to hub every N samples (0 to disable).
57
+ max_samples_per_output_file: Maximum samples per output file (0 for unlimited).
58
+ max_model_len: Maximum model sequence length.
59
+ enable_thinking: Whether to enable thinking mode for chat templates.
60
+ prefix: String prefix to use for internal column names and file operations.
61
+ """
62
+
63
+ model_id: str
64
+ prompt_template_file: str | PathLike | None = None
65
+ prompt_template: str | None = None
66
+ prompt_field_swapper: dict[str, str] | None = None
67
+ output_schema_file: str | PathLike | None = None
68
+ output_schema: str | dict[str, Any] | None = None
69
+ whitespace_pattern: str | None = None
70
+ idx_column: str = "idx"
71
+ num_proc: int | None = None
72
+ tensor_parallel_size: int = 1
73
+ max_num_seqs: int = 256
74
+ gpu_memory_utilization: float = 0.95
75
+ enforce_eager: bool = False
76
+ quantization: str | None = None
77
+ verbose: bool = False
78
+ keep_columns: str | Iterable[str] | bool | None = None
79
+ upload_every_n_samples: int = 0
80
+ max_samples_per_output_file: int = 0
81
+ max_model_len: int | None = None
82
+ enable_thinking: bool = False
83
+ prefix: str = ""
84
+
85
+ pipe: LLM | None = field(default=None, init=False)
86
+ dataset: Dataset | None = field(default=None, init=False)
87
+ dataset_config: str = field(default=None, init=False)
88
+ dataset_split: str = field(default=None, init=False)
89
+ tokenizer: PreTrainedTokenizer | None = field(default=None, init=False)
90
+ prompt_fields: tuple[str, ...] = field(default=None, init=False)
91
+
92
+ def __post_init__(self) -> None:
93
+ self.max_samples_per_output_file = (
94
+ 0 if self.max_samples_per_output_file is None else max(0, self.max_samples_per_output_file)
95
+ )
96
+ if not self.prompt_template_file and not self.prompt_template:
97
+ raise ValueError("Either prompt_template_file or prompt_template must be provided")
98
+
99
+ if self.prompt_template_file and self.prompt_template:
100
+ raise ValueError("Only one of prompt_template_file or prompt_template should be provided")
101
+
102
+ if self.prompt_template_file:
103
+ self.prompt_template = Path(self.prompt_template_file).read_text(encoding="utf-8")
104
+
105
+ self.prompt_field_swapper = self.prompt_field_swapper or {}
106
+
107
+ for fld, value in self.prompt_field_swapper.items():
108
+ self.prompt_template = self.prompt_template.replace(f"{{{fld}}}", value)
109
+
110
+ str_formatter = string.Formatter()
111
+ self.prompt_fields = tuple(
112
+ [fld[1] for fld in str_formatter.parse(self.prompt_template) if fld[1] is not None and not fld[2]]
113
+ )
114
+ if not self.keep_columns:
115
+ self.keep_columns = set()
116
+ elif isinstance(self.keep_columns, str):
117
+ self.keep_columns = {self.keep_columns}
118
+ elif self.keep_columns is True:
119
+ # Redundant but makes it clearer that the value can be True
120
+ self.keep_columns = True
121
+ else:
122
+ try:
123
+ self.keep_columns = set(self.keep_columns)
124
+ except TypeError as exc:
125
+ raise TypeError("keep_columns must be None, True, a string, or a collection of strings") from exc
126
+
127
+ # Always keep idx_column
128
+ if isinstance(self.keep_columns, set):
129
+ self.keep_columns.add(self.idx_column)
130
+
131
+ if self.output_schema_file and self.output_schema:
132
+ raise ValueError("Only one of output_schema_file or output_schema should be provided")
133
+
134
+ if self.output_schema_file:
135
+ self.output_schema = json.loads(Path(self.output_schema_file).read_text(encoding="utf-8"))
136
+
137
+ def cached_input_dataset_path(self, pdout: PathLike) -> Path:
138
+ """Get the path to the cached input dataset.
139
+
140
+ Args:
141
+ pdout: Output directory path.
142
+
143
+ Returns:
144
+ Path to the cached input dataset directory.
145
+ """
146
+ pdout = Path(pdout)
147
+ return pdout / f"{self.prefix}cached_input_dataset"
148
+
149
+ def _get_skip_idxs(self, pdout: Path) -> set[int]:
150
+ """Get indices of samples that have already been processed.
151
+
152
+ Scans existing output files to determine which samples can be skipped
153
+ in resumed processing.
154
+
155
+ Args:
156
+ pdout: Output directory path to scan for existing files.
157
+
158
+ Returns:
159
+ Set of indices that have already been processed.
160
+ """
161
+ ids_done = set()
162
+ if pdout.exists() and pdout.stat().st_size > 0:
163
+ for pfin in pdout.glob("*.jsonl"):
164
+ if pfin.stat().st_size == 0:
165
+ continue
166
+ ds = Dataset.from_json(str(pfin))
167
+
168
+ if self.dataset_split and "dataset_split" in ds.column_names:
169
+ ds = ds.filter(lambda s: s["dataset_split"] == self.dataset_split)
170
+
171
+ if self.dataset_config and "dataset_config" in ds.column_names:
172
+ ds = ds.filter(lambda s: s["dataset_config"] == self.dataset_config)
173
+
174
+ ids_done.update(ds.unique(self.idx_column))
175
+
176
+ return ids_done
177
+
178
+ def _load_dataset(
179
+ self,
180
+ dataset_name: str,
181
+ pdout: Path,
182
+ dataset_config: str = None,
183
+ data_dir: str | None = None,
184
+ dataset_split: str | None = None,
185
+ streaming: bool = False,
186
+ max_num_samples: int | None = None,
187
+ shuffle_seed: int | None = None,
188
+ cache_input_dataset: bool = True,
189
+ use_cached_input_dataset: bool = True,
190
+ ) -> int:
191
+ """Load and preprocess the dataset for annotation.
192
+
193
+ Handles dataset loading from various sources, applies prompt templates,
194
+ and manages caching for efficient resumption of interrupted jobs.
195
+
196
+ Args:
197
+ dataset_name: Name or path of the dataset to load.
198
+ pdout: Output directory for caching and results.
199
+ dataset_config: Dataset configuration name (optional).
200
+ data_dir: Data directory for local datasets (optional).
201
+ dataset_split: Specific split to load (optional).
202
+ streaming: Whether to use streaming mode for large datasets.
203
+ max_num_samples: Maximum number of samples to process.
204
+ shuffle_seed: Seed for dataset shuffling (optional).
205
+ cache_input_dataset: Whether to cache the input dataset.
206
+ Especially useful if using streaming + max_num_samples.
207
+ use_cached_input_dataset: Whether to use a cached input dataset if available.
208
+
209
+ Raises:
210
+ ValueError: If streaming mode is used without max_num_samples.
211
+ """
212
+ if max_num_samples is not None and max_num_samples <= 0:
213
+ raise ValueError("'max_num_samples' must be a positive integer or None")
214
+
215
+ self.dataset_config = dataset_config
216
+ self.dataset_split = dataset_split
217
+ self.streaming = streaming
218
+ self.dataset = None
219
+
220
+ # Split verification and defaulting
221
+ split_names = get_dataset_split_names(dataset_name)
222
+ if not dataset_split:
223
+ if len(split_names) == 1:
224
+ dataset_split = split_names[0]
225
+ else:
226
+ raise ValueError(
227
+ f"Dataset '{dataset_name}' has multiple splits {split_names}. "
228
+ "Please specify a split using the 'dataset_split' argument."
229
+ )
230
+ elif dataset_split not in split_names:
231
+ raise ValueError(f"Dataset '{dataset_name}' does not have a split named '{dataset_split}'")
232
+
233
+ cached_input_ds = self.cached_input_dataset_path(pdout)
234
+
235
+ dataset = None
236
+
237
+ # If exists and not empty, try to load from cache. If loading the
238
+ # cached dataset fails (corrupted cache), fall back to loading from
239
+ # the original source.
240
+ if use_cached_input_dataset and cached_input_ds.exists() and cached_input_ds.stat().st_size > 0:
241
+ try:
242
+ dataset = Dataset.load_from_disk(cached_input_ds)
243
+ except Exception:
244
+ dataset = None
245
+
246
+ if dataset is None:
247
+ if streaming and not max_num_samples:
248
+ raise ValueError(
249
+ "Streaming mode requires max_num_samples to be set."
250
+ " The dataset itself will be streamed and stored up to"
251
+ " the requested number of samples."
252
+ )
253
+
254
+ if streaming:
255
+ ds_iter: IterableDataset = load_dataset(
256
+ dataset_name, name=dataset_config, data_dir=data_dir, split=dataset_split, streaming=True
257
+ )
258
+
259
+ if shuffle_seed is not None:
260
+ # IterableDataset.shuffle does not accept buffer_size in some
261
+ # versions; call with only seed to be compatible.
262
+ try:
263
+ ds_iter = ds_iter.shuffle(seed=shuffle_seed, buffer_size=10_000)
264
+ except TypeError:
265
+ ds_iter = ds_iter.shuffle(seed=shuffle_seed)
266
+
267
+ def yield_fn():
268
+ num_samples = 0
269
+ for sample in ds_iter:
270
+ yield sample
271
+ num_samples += 1
272
+ if max_num_samples and num_samples >= max_num_samples:
273
+ break
274
+
275
+ # Convert to Dataset
276
+ dataset = Dataset.from_generator(yield_fn, split=dataset_split)
277
+ else:
278
+ dataset = load_dataset(dataset_name, name=dataset_config, data_dir=data_dir, split=dataset_split)
279
+ if shuffle_seed is not None:
280
+ dataset = dataset.shuffle(seed=shuffle_seed)
281
+
282
+ if max_num_samples:
283
+ dataset = dataset.select(range(min(max_num_samples, len(dataset))))
284
+
285
+ # Validate that the dataset contains all fields required by the
286
+ # prompt template. Tests expect a ValueError when a required
287
+ # field is missing.
288
+ if dataset is not None and self.prompt_fields:
289
+ missing = [fld for fld in self.prompt_fields if fld not in dataset.column_names]
290
+ if missing:
291
+ raise ValueError(f"Template contains field '{missing[0]}' not present in dataset")
292
+
293
+ dataset = self._preprocess_dataset(dataset)
294
+
295
+ dataset = dataset.map(
296
+ lambda sample, idx: {
297
+ f"{self.prefix}prompted": self.tokenizer.apply_chat_template(
298
+ [
299
+ {
300
+ "role": "user",
301
+ "content": self.prompt_template.format(
302
+ **{fld: sample[fld] for fld in self.prompt_fields}
303
+ ),
304
+ }
305
+ ],
306
+ tokenize=False,
307
+ add_generation_template=True,
308
+ enable_thinking=self.enable_thinking,
309
+ ),
310
+ self.idx_column: idx,
311
+ },
312
+ with_indices=True,
313
+ num_proc=self.num_proc,
314
+ desc="Applying prompt template",
315
+ )
316
+ if cache_input_dataset:
317
+ dataset.save_to_disk(cached_input_ds)
318
+
319
+ skip_idxs = self._get_skip_idxs(pdout)
320
+ processed_n_samples = 0
321
+ if skip_idxs:
322
+ dataset = dataset.filter(
323
+ lambda s: s[self.idx_column] not in skip_idxs,
324
+ num_proc=self.num_proc,
325
+ desc="Filtering done idxs",
326
+ )
327
+ processed_n_samples = len(skip_idxs)
328
+ if self.verbose:
329
+ print(f"Skipping {len(skip_idxs)} already-processed samples")
330
+
331
+ dataset = self._postprocess_dataset(dataset)
332
+ self.dataset = dataset
333
+ return processed_n_samples
334
+
335
+ def _preprocess_dataset(self, dataset: Dataset) -> Dataset:
336
+ """Preprocess the dataset before applying prompt templates.
337
+
338
+ Override this method to add custom preprocessing logic such as
339
+ filtering, transforming columns, or adding metadata.
340
+
341
+ Args:
342
+ dataset: The loaded dataset to preprocess.
343
+
344
+ Returns:
345
+ The preprocessed dataset.
346
+ """
347
+ return dataset
348
+
349
+ def _postprocess_dataset(self, dataset: Dataset) -> Dataset:
350
+ """Postprocess the dataset after applying prompt templates.
351
+
352
+ Override this method to add final processing steps before annotation
353
+ such as additional filtering or column transformations.
354
+
355
+ Args:
356
+ dataset: The dataset with applied prompt templates.
357
+
358
+ Returns:
359
+ The postprocessed dataset ready for annotation.
360
+ """
361
+ return dataset
362
+
363
+ def _load_tokenizer(self) -> None:
364
+ """Load and configure the tokenizer for the model.
365
+
366
+ Sets up the tokenizer with appropriate padding settings and ensures
367
+ a pad token is available.
368
+ """
369
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
370
+
371
+ self.tokenizer.padding_side = "left"
372
+
373
+ if not self.tokenizer.pad_token_id:
374
+ self.tokenizer.pad_token = self.tokenizer.eos_token
375
+ self.tokenizer.pad_token_id = self.tokenizer.convert_tokens_to_ids(self.tokenizer.pad_token)
376
+
377
+ def _load_pipeline(self) -> None:
378
+ """Load and initialize the vLLM pipeline for inference.
379
+
380
+ Configures the LLM with the specified parameters including tensor
381
+ parallelism, quantization, and memory settings.
382
+ """
383
+ self.pipe = LLM(
384
+ model=self.model_id,
385
+ tensor_parallel_size=self.tensor_parallel_size,
386
+ quantization=self.quantization,
387
+ max_model_len=self.max_model_len,
388
+ enforce_eager=self.enforce_eager,
389
+ max_num_seqs=self.max_num_seqs,
390
+ gpu_memory_utilization=self.gpu_memory_utilization,
391
+ )
392
+
393
+ def _process_output(self, output: RequestOutput) -> dict[str, Any]:
394
+ """Process a single model output into the desired annotation format.
395
+
396
+ Override this method to implement custom output parsing and validation.
397
+
398
+ Args:
399
+ output: The raw output from the model for a single input.
400
+ Returns:
401
+ - A key '{prefix}_response' containing the raw model output text.
402
+ - A key '{prefix}_finish_reason' indicating why generation stopped.
403
+ - A key '{prefix}_num_tokens' indicating the number of tokens in the output.
404
+
405
+ And if an output_schema is provided, also:
406
+ - Keys from the output_schema with their parsed values (or None if parsing failed).
407
+ - A key '{prefix}_valid_fields' indicating if all required fields were valid.
408
+ """
409
+ raw_response = output.outputs[0].text
410
+
411
+ data = {
412
+ f"{self.prefix}response": raw_response,
413
+ f"{self.prefix}finish_reason": output.outputs[0].finish_reason if output.outputs else "unknown",
414
+ f"{self.prefix}num_tokens": len(output.outputs[0].token_ids) if output.outputs else 0,
415
+ }
416
+ if not self.output_schema:
417
+ return data
418
+
419
+ required_keys = self.output_schema["properties"].keys()
420
+ result = dict.fromkeys(required_keys)
421
+
422
+ valid_fields = True
423
+ try:
424
+ parsed_response = json.loads(raw_response)
425
+ except json.JSONDecodeError:
426
+ valid_fields = False
427
+ else:
428
+ result.update(parsed_response)
429
+
430
+ valid_fields = valid_fields and all(result[key] is not None for key in required_keys)
431
+
432
+ return {
433
+ **data,
434
+ f"{self.prefix}valid_fields": valid_fields,
435
+ **result,
436
+ }
437
+
438
+ def reset_model_and_dataset(self) -> None:
439
+ """Clean up model and dataset resources to free memory.
440
+
441
+ Destroys the distributed environment, clears GPU cache, and resets
442
+ internal state. Useful for processing multiple datasets sequentially.
443
+ """
444
+ try:
445
+ destroy_model_parallel()
446
+ except Exception:
447
+ pass
448
+ try:
449
+ destroy_distributed_environment()
450
+ except Exception:
451
+ pass
452
+
453
+ try:
454
+ # Remove nested attributes if present
455
+ if hasattr(self.pipe, "llm_engine") and hasattr(self.pipe.llm_engine, "model_executor"):
456
+ del self.pipe.llm_engine.model_executor
457
+ except Exception:
458
+ pass
459
+
460
+ try:
461
+ del self.pipe
462
+ except Exception:
463
+ pass
464
+
465
+ gc.collect()
466
+ try:
467
+ torch.cuda.empty_cache()
468
+ except Exception:
469
+ pass
470
+
471
+ self.pipe = None
472
+ self.dataset = None
473
+
474
+ def _process_batch(
475
+ self,
476
+ batch: dict[str, list[Any]],
477
+ sampling_params: SamplingParams,
478
+ ) -> list[dict[str, Any]]:
479
+ """Process a batch of samples through the model.
480
+
481
+ Takes a batch of prompted samples, runs inference, and processes
482
+ the outputs using the `_process_output` method.
483
+
484
+ Args:
485
+ batch: Dictionary containing batch data with prompted samples.
486
+ sampling_params: Sampling parameters for model generation.
487
+
488
+ Returns:
489
+ List of processed output dictionaries for each sample in the batch.
490
+ """
491
+ outputs = self.pipe.generate(batch[f"{self.prefix}prompted"], sampling_params, use_tqdm=False)
492
+ results = [self._process_output(outp) for outp in outputs]
493
+
494
+ return results
495
+
496
+ def annotate_dataset(
497
+ self,
498
+ dataset_name: str,
499
+ output_dir: str | Path,
500
+ *,
501
+ new_hub_id: str | None = None,
502
+ overwrite: bool = False,
503
+ dataset_config: str | None = None,
504
+ data_dir: str | None = None,
505
+ dataset_split: str | None = None,
506
+ shuffle_seed: int | None = None,
507
+ streaming: bool = False,
508
+ sampling_params: dict[str, Any] | None = None,
509
+ max_num_samples: int | None = None,
510
+ cache_input_dataset: bool = True,
511
+ use_cached_input_dataset: bool = True,
512
+ ) -> None:
513
+ """Annotate an entire dataset using the configured model and prompt.
514
+
515
+ Main entry point for dataset annotation. Handles the complete pipeline
516
+ from dataset loading through model inference to output generation.
517
+
518
+ Args:
519
+ dataset_name: Name or path of the dataset to annotate.
520
+ output_dir: Directory to save annotation results.
521
+ new_hub_id: Optional Hugging Face dataset ID for uploads (overrides instance setting).
522
+ overwrite: Whether to overwrite existing output directory.
523
+ dataset_config: Dataset configuration name (optional).
524
+ data_dir: Data directory for local datasets (optional).
525
+ dataset_split: Specific split to annotate (optional).
526
+ shuffle_seed: Seed for dataset shuffling (optional).
527
+ streaming: Whether to use streaming mode for large datasets.
528
+ sampling_params: Parameters for model generation (optional).
529
+ max_num_samples: Maximum number of samples to annotate.
530
+ cache_input_dataset: Whether to cache the input dataset. Especially useful if
531
+ using streaming + max_num_samples.
532
+ use_cached_input_dataset: Whether to use a cached input dataset if available.
533
+ """
534
+ if self.upload_every_n_samples < 0 or not isinstance(self.upload_every_n_samples, int):
535
+ raise ValueError("upload_every_n_samples must be a positive integer or 0")
536
+ elif self.upload_every_n_samples > 0 and not new_hub_id:
537
+ raise ValueError("If upload_every_n_samples is set, new_hub_id must be provided")
538
+
539
+ pdout = Path(output_dir)
540
+ if pdout.is_dir() and overwrite:
541
+ shutil.rmtree(pdout)
542
+
543
+ pdout.mkdir(exist_ok=True, parents=True)
544
+
545
+ self._load_tokenizer()
546
+ processed_n_samples = self._load_dataset(
547
+ dataset_name,
548
+ pdout,
549
+ dataset_config=dataset_config,
550
+ data_dir=data_dir,
551
+ dataset_split=dataset_split,
552
+ streaming=streaming,
553
+ max_num_samples=max_num_samples,
554
+ shuffle_seed=shuffle_seed,
555
+ cache_input_dataset=cache_input_dataset,
556
+ use_cached_input_dataset=use_cached_input_dataset,
557
+ )
558
+ if len(self.dataset) > 0:
559
+ pfout = self.get_fhout_name(pdout, processed_n_samples=processed_n_samples)
560
+ fhout = pfout.open("a", encoding="utf-8")
561
+
562
+ self._load_pipeline()
563
+
564
+ sampling_params = sampling_params or {}
565
+ if self.output_schema:
566
+ ws_pattern = self.whitespace_pattern or None
567
+ sampling_params["guided_decoding"] = GuidedDecodingParams(
568
+ json=self.output_schema,
569
+ whitespace_pattern=ws_pattern,
570
+ )
571
+ sampling_params = SamplingParams(**sampling_params)
572
+
573
+ total_num_batches = ceil(len(self.dataset) / self.max_num_seqs)
574
+ for batch in tqdm(
575
+ self.dataset.iter(self.max_num_seqs),
576
+ total=total_num_batches,
577
+ desc=f"Annotating (max_bs={self.max_num_seqs})",
578
+ unit="batch",
579
+ ):
580
+ results = self._process_batch(batch, sampling_params)
581
+
582
+ batch_size = len(batch[self.idx_column])
583
+ if self.keep_columns is True:
584
+ # Keep all columns
585
+ inputs = [{k: v[i] for k, v in batch.items()} for i in range(batch_size)]
586
+ else:
587
+ inputs = [{k: v[i] for k, v in batch.items() if k in self.keep_columns} for i in range(batch_size)]
588
+
589
+ # Iterate over results and write them out in order
590
+ for result_idx, res in enumerate(results):
591
+ inp = inputs[result_idx]
592
+ data_sample = {**inp, **res}
593
+ fhout.write(json.dumps(data_sample) + "\n")
594
+ fhout.flush()
595
+ processed_n_samples += 1
596
+ print(processed_n_samples)
597
+
598
+ # Handle hub upload checkpointing and output file rotation
599
+ if self.upload_every_n_samples > 0 and processed_n_samples % self.upload_every_n_samples == 0:
600
+ fhout.close()
601
+ remove_empty_jsonl_files(pdout)
602
+ if new_hub_id:
603
+ self.push_dir_to_hub(pdout, new_hub_id=new_hub_id)
604
+ pfout = self.get_fhout_name(pdout)
605
+ fhout = pfout.open("a", encoding="utf-8")
606
+
607
+ fhout.close()
608
+ remove_empty_jsonl_files(pdout)
609
+ if new_hub_id and self.upload_every_n_samples > 0:
610
+ self.push_dir_to_hub(pdout, new_hub_id=new_hub_id)
611
+
612
+ return self._post_annotate(pdout, new_hub_id)
613
+
614
+ def _post_annotate(self, pdout: Path, new_hub_id: str | None = None) -> Dataset:
615
+ """Clean up after annotation is complete.
616
+
617
+ Removes empty output files and performs any final cleanup operations.
618
+
619
+ Args:
620
+ pdout: Output directory path to clean up.
621
+ new_hub_id: Optional Hugging Face dataset ID for uploads (overrides instance setting).
622
+
623
+ Returns:
624
+ The concatenated dataset of all annotation results (JSON-invalid samples are NOT removed)
625
+ """
626
+ ds_parts = []
627
+ for pfin in pdout.glob("*.jsonl"):
628
+ if pfin.stat().st_size > 0:
629
+ ds_parts.append(Dataset.from_json(str(pfin)))
630
+
631
+ ds = concatenate_datasets(ds_parts).remove_columns(self.idx_column)
632
+
633
+ if new_hub_id:
634
+ ds.push_to_hub(new_hub_id, private=True)
635
+
636
+ ds.cleanup_cache_files()
637
+
638
+ cached_input_ds = pdout / "cached_input_dataset"
639
+ if cached_input_ds.exists():
640
+ shutil.rmtree(cached_input_ds)
641
+
642
+ return ds
643
+
644
+ def get_fhout_name(self, output_dir: Path | str, *, processed_n_samples: int | None = None) -> Path:
645
+ """Generate the output file name based on configuration.
646
+
647
+ Creates appropriate file names for output files, handling both
648
+ single-file and multi-file output modes.
649
+
650
+ Args:
651
+ output_dir: The output directory path.
652
+ processed_n_samples: The number of samples processed so far.
653
+
654
+ Returns:
655
+ Path object for the output file name.
656
+ """
657
+ stem = Path(output_dir).stem
658
+ if not self.max_samples_per_output_file:
659
+ return Path(output_dir).joinpath(f"{stem}.jsonl")
660
+ else:
661
+ count_idx = processed_n_samples // self.max_samples_per_output_file
662
+ return Path(output_dir).joinpath(f"{stem}_{count_idx}.jsonl")
663
+
664
+ @retry()
665
+ def push_dir_to_hub(self, dir_path: Path | str, new_hub_id: str | None = None) -> None:
666
+ """Upload the output directory to Hugging Face Hub.
667
+
668
+ Creates a dataset repository and uploads all annotation files,
669
+ excluding cached input data. Uses a separate branch for uploads.
670
+
671
+ Args:
672
+ dir_path: Path to the directory containing annotation files.
673
+ new_hub_id: Optional Hugging Face dataset ID to override the instance's new_hub_id.
674
+
675
+ Raises:
676
+ Exception: If upload fails after retries (handled by @retry decorator).
677
+ """
678
+ if not new_hub_id:
679
+ raise ValueError("'new_hub_id' must be set to push data to the HuggingFace Hub")
680
+
681
+ create_repo(new_hub_id, repo_type="dataset", exist_ok=True, private=True)
682
+ create_branch(new_hub_id, repo_type="dataset", branch=f"{self.prefix}jsonl_upload", exist_ok=True)
683
+
684
+ upload_large_folder(
685
+ repo_id=new_hub_id,
686
+ repo_type="dataset",
687
+ folder_path=str(dir_path),
688
+ allow_patterns=["*.jsonl", "*.json"], # Include data files (jsonl) and config files (json)
689
+ ignore_patterns=[f"{self.prefix}cached_input_dataset/*", ".cache/*"], # Ignore cached input dataset
690
+ private=True,
691
+ revision=f"{self.prefix}jsonl_upload",
692
+ )
llm_annotator/utils.py ADDED
@@ -0,0 +1,149 @@
1
+ import functools
2
+ import hashlib
3
+ import json
4
+ import sys
5
+ import time
6
+ from os import PathLike
7
+ from pathlib import Path
8
+
9
+ from tqdm import tqdm
10
+
11
+
12
+ def get_hash(text: str) -> str:
13
+ """Compute a SHA256 hash for a given text string."""
14
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
15
+
16
+
17
+ def convert_int_to_str(num: int) -> str:
18
+ """Convert an integer to a concise string approximating the `num`.
19
+ E.g. 1_000_000 -> '1M', 1_234_567 -> '1.23M', 1_234 -> '1.23K'
20
+ """
21
+ if num >= 1_000_000_000:
22
+ numstr = f"{num / 1_000_000_000:.1f}".rstrip("0").rstrip(".") # remove trailing '.0' if exactly 1 billion
23
+ return f"{numstr}B"
24
+ elif num >= 1_000_000:
25
+ numstr = f"{num / 1_000_000:.1f}".rstrip("0").rstrip(".")
26
+ return f"{numstr}M"
27
+ elif num >= 1_000:
28
+ numstr = f"{num / 1_000:.1f}".rstrip("0").rstrip(".")
29
+ return f"{numstr}K"
30
+ else:
31
+ return str(num)
32
+
33
+
34
+ def retry(num_retries: int = 3, sleep_time_s: int = 10) -> callable:
35
+ """
36
+ A decorator to automatically retry a function if it fails. Useful when we are uploading data.
37
+
38
+ Args:
39
+ num_retries (int): The maximum number of times to retry the function.
40
+ sleep_time_s (int): The initial time in seconds to wait before retrying.
41
+ This time will double after each failed attempt.
42
+ """
43
+
44
+ def decorator(func):
45
+ @functools.wraps(func)
46
+ def wrapper(*args, **kwargs):
47
+ retries_left = num_retries
48
+ current_sleep_time = sleep_time_s
49
+ while True:
50
+ try:
51
+ return func(*args, **kwargs)
52
+ except Exception as exc:
53
+ if retries_left <= 0:
54
+ print(f"Function {func.__name__} failed after {num_retries} retries.", file=sys.stderr)
55
+ raise exc
56
+
57
+ print(
58
+ f"Function {func.__name__} failed with {exc}. Retrying in {current_sleep_time}s... ({retries_left} retries left)",
59
+ file=sys.stderr,
60
+ )
61
+ time.sleep(current_sleep_time)
62
+ retries_left -= 1
63
+ current_sleep_time *= 2
64
+
65
+ return wrapper
66
+
67
+ return decorator
68
+
69
+
70
+ def yield_jsonl_robust(
71
+ pfiles: list[Path | str],
72
+ keep_columns: list[str] | None = None,
73
+ disable_tqdm: bool = False,
74
+ deduplicate_on: str | None = None,
75
+ ):
76
+ """
77
+ Given a set of .jsonl.gz files, this function reads them in a robust way, skipping incomplete lines,
78
+ and yielding one sample at a time (parse-able JSON line).
79
+
80
+ :param pfiles: A list of .jsonl.gz files
81
+ :param keep_columns: A list of columns to keep in the output. If not given, all columns are kept.
82
+ :param disable_tqdm: Whether to disable the progress bar
83
+ :param deduplicate_on: Column name to use for deduplication (will be hashed)
84
+ :return: A generator yielding the contents of the files
85
+ """
86
+ pfiles = [Path(pfile) for pfile in pfiles]
87
+ seen = set()
88
+ num_duplicates_removed = 0
89
+ with tqdm(total=len(pfiles), desc="Reading", unit="file", disable=disable_tqdm) as pbar:
90
+ for pfin in pfiles:
91
+ if pfin.stat().st_size == 0:
92
+ continue
93
+
94
+ with pfin.open(encoding="utf-8") as fhin:
95
+ num_failures = 0
96
+ while True:
97
+ try:
98
+ line = fhin.readline()
99
+ if not line:
100
+ break
101
+ data = json.loads(line)
102
+ if deduplicate_on:
103
+ hashed_col = get_hash(data[deduplicate_on])
104
+ if hashed_col in seen:
105
+ num_duplicates_removed += 1
106
+ continue
107
+ seen.add(hashed_col)
108
+
109
+ if keep_columns:
110
+ data = {k: v for k, v in data.items() if k in keep_columns}
111
+
112
+ yield data
113
+ except json.JSONDecodeError:
114
+ # Handle partial or malformed JSON (incomplete writes)
115
+ num_failures += 1
116
+ except EOFError:
117
+ # Handle unexpected EOF in gzip
118
+ num_failures += 1
119
+ break
120
+ if num_failures:
121
+ print(f"Skipped {num_failures:,} corrupt line(s) in {pfin}")
122
+ pbar.update(1)
123
+
124
+ if deduplicate_on:
125
+ print(f"Removed {num_duplicates_removed:,} duplicates")
126
+
127
+
128
+ def count_lines(fname: str | PathLike) -> int:
129
+ """Count the number of lines in a file."""
130
+ with open(fname, "r", encoding="utf-8") as fhin:
131
+ return sum([1 for _ in fhin])
132
+
133
+
134
+ def remove_empty_jsonl_files(pdout: Path) -> list[Path]:
135
+ """Remove any empty .jsonl files in the given directory.
136
+
137
+ Args:
138
+ pdout: Output directory path to clean up.
139
+
140
+ Returns:
141
+ A list of removed files.
142
+ """
143
+ files_removed = []
144
+ for pfin in pdout.glob("*.jsonl"):
145
+ if pfin.stat().st_size == 0:
146
+ files_removed.append(pfin)
147
+ pfin.unlink()
148
+
149
+ return files_removed
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: llm-annotator
3
+ Version: 0.1.1
4
+ Summary: An easy-to-extend LLM annotator for robust, resumable data annotation.
5
+ Author-email: Bram Vanroy <2779410+BramVanroy@users.noreply.github.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: datasets<5,>=4.1.1
10
+ Requires-Dist: hf-transfer<2,>=0.1.9
11
+ Requires-Dist: hf-xet<2,>=1.1.10
12
+ Requires-Dist: outlines<2,>=1.2.5
13
+ Requires-Dist: vllm<0.11,>=0.10.2
14
+ Description-Content-Type: text/markdown
15
+
16
+ # A simple, extensible LLM Annotator
17
+
18
+ This repository provides a small, resumable framework for annotating datasets with
19
+ LLMs (via `vllm`). Below is a minimal usage example showing how to instantiate the
20
+ `Annotator` class and run a short annotation job.
21
+
22
+ ## Installation
23
+
24
+ Recommended:
25
+
26
+ ```sh
27
+ uv add llm-annotator
28
+ ```
29
+
30
+ or
31
+
32
+ ```sh
33
+ pip install llm-annotator
34
+ ```
35
+
36
+ ## Usage
37
+
38
+ See [examples/](examples/) for usage examples.
39
+
40
+
41
+ ## Testing
42
+
43
+ ```sh
44
+ pytest -q
45
+ ```
@@ -0,0 +1,7 @@
1
+ llm_annotator/__init__.py,sha256=GH3m1gLdhVBV0yg1eKEiSXqpo6T6zfQiSZKj0nvRVFI,33
2
+ llm_annotator/annotator.py,sha256=j8-jjBRSvJXYH8ihcUy_SprXGTuubuxkWZmfXgkkAxU,29243
3
+ llm_annotator/utils.py,sha256=sYURUqGRhn1smtq9_pY74wZS9QqMJdJqeFsbDB6_BX4,5197
4
+ llm_annotator-0.1.1.dist-info/METADATA,sha256=BqpbHMc67TRG8xA0KmTvaLrsFQwtoAJ9gTeFtiF45Ew,948
5
+ llm_annotator-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ llm_annotator-0.1.1.dist-info/licenses/LICENSE,sha256=3jTgeOCjVI90nu4oiM8j32QF4xsdpsRZubf7Yc82BfQ,11341
7
+ llm_annotator-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Bram Vanroy
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.