congrads 0.2.0__py3-none-any.whl → 0.3.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,515 @@
1
+ """This module holds utility functions and classes for the congrads package."""
2
+
3
+ import inspect
4
+ import os
5
+ import random
6
+ from collections.abc import Callable
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import torch
11
+ import torch.nn as nn
12
+ from torch import Generator, Tensor, argsort, cat, int32, unique
13
+ from torch.nn.modules.loss import _Loss
14
+ from torch.utils.data import DataLoader, Dataset, random_split
15
+
16
+ __all__ = [
17
+ "CSVLogger",
18
+ "split_data_loaders",
19
+ "ZeroLoss",
20
+ "LossWrapper",
21
+ "process_data_monotonicity_constraint",
22
+ "DictDatasetWrapper",
23
+ "Seeder",
24
+ ]
25
+
26
+
27
+ class CSVLogger:
28
+ """A utility class for logging key-value pairs to a CSV file, organized by epochs.
29
+
30
+ Supports merging with existing logs or overwriting them.
31
+
32
+ Args:
33
+ file_path (str): The path to the CSV file for logging.
34
+ overwrite (bool): If True, overwrites any existing file at the file_path.
35
+ merge (bool): If True, merges new values with existing data in the file.
36
+
37
+ Raises:
38
+ ValueError: If both overwrite and merge are True.
39
+ FileExistsError: If the file already exists and neither overwrite nor merge is True.
40
+ """
41
+
42
+ def __init__(self, file_path: str, overwrite: bool = False, merge: bool = True):
43
+ """Initializes the CSVLogger.
44
+
45
+ Supports merging with existing logs or overwriting them.
46
+
47
+ Args:
48
+ file_path (str): The path to the CSV file for logging.
49
+ overwrite (optional, bool): If True, overwrites any existing file at the file_path. Defaults to False.
50
+ merge (optional, bool): If True, merges new values with existing data in the file. Defaults to True.
51
+
52
+ Raises:
53
+ ValueError: If both overwrite and merge are True.
54
+ FileExistsError: If the file already exists and neither overwrite nor merge is True.
55
+ """
56
+ self.file_path = file_path
57
+ self.values: dict[tuple[int, str], float] = {}
58
+
59
+ if merge and overwrite:
60
+ raise ValueError(
61
+ "The attributes overwrite and merge cannot be True at the "
62
+ "same time. Either specify overwrite=True or merge=True."
63
+ )
64
+
65
+ if not os.path.exists(file_path):
66
+ pass
67
+ elif merge:
68
+ self.load()
69
+ elif overwrite:
70
+ pass
71
+ else:
72
+ raise FileExistsError(
73
+ f"A CSV file already exists at {file_path}. Specify "
74
+ "CSVLogger(..., overwrite=True) to overwrite the file."
75
+ )
76
+
77
+ def add_value(self, name: str, value: float, epoch: int):
78
+ """Adds a value to the logger for a specific epoch and name.
79
+
80
+ Args:
81
+ name (str): The name of the metric or value to log.
82
+ value (float): The value to log.
83
+ epoch (int): The epoch associated with the value.
84
+ """
85
+ self.values[epoch, name] = value
86
+
87
+ def save(self):
88
+ """Saves the logged values to the specified CSV file.
89
+
90
+ If the file exists and merge is enabled, merges the current data
91
+ with the existing file.
92
+ """
93
+ data = self.to_dataframe(self.values)
94
+ data.to_csv(self.file_path, index=False)
95
+
96
+ def load(self):
97
+ """Loads data from the CSV file into the logger.
98
+
99
+ Converts the CSV data into the internal dictionary format for
100
+ further updates or operations.
101
+ """
102
+ df = pd.read_csv(self.file_path)
103
+ self.values = self.to_dict(df)
104
+
105
+ @staticmethod
106
+ def to_dataframe(values: dict[tuple[int, str], float]) -> pd.DataFrame:
107
+ """Converts a dictionary of values into a DataFrame.
108
+
109
+ Args:
110
+ values (dict[tuple[int, str], float]): A dictionary of values keyed by (epoch, name).
111
+
112
+ Returns:
113
+ pd.DataFrame: A DataFrame where epochs are rows, names are columns, and values are the cell data.
114
+ """
115
+ # Convert to a DataFrame
116
+ df = pd.DataFrame.from_dict(values, orient="index", columns=["value"])
117
+
118
+ # Reset the index to separate epoch and name into columns
119
+ df.index = pd.MultiIndex.from_tuples(df.index, names=["epoch", "name"])
120
+ df = df.reset_index()
121
+
122
+ # Pivot the DataFrame so epochs are rows and names are columns
123
+ result = df.pivot(index="epoch", columns="name", values="value")
124
+
125
+ # Optional: Reset the column names for a cleaner look
126
+ result = result.reset_index().rename_axis(columns=None)
127
+
128
+ return result
129
+
130
+ @staticmethod
131
+ def to_dict(df: pd.DataFrame) -> dict[tuple[int, str], float]:
132
+ """Converts a CSVLogger DataFrame to a dictionary the format {(epoch, name): value}."""
133
+ # Set the epoch column as the index (if not already)
134
+ df = df.set_index("epoch")
135
+
136
+ # Stack the DataFrame to create a multi-index series
137
+ stacked = df.stack()
138
+
139
+ # Convert the multi-index series to a dictionary
140
+ result = stacked.to_dict()
141
+
142
+ return result
143
+
144
+
145
+ def split_data_loaders(
146
+ data: Dataset,
147
+ loader_args: dict = None,
148
+ train_loader_args: dict = None,
149
+ valid_loader_args: dict = None,
150
+ test_loader_args: dict = None,
151
+ train_size: float = 0.8,
152
+ valid_size: float = 0.1,
153
+ test_size: float = 0.1,
154
+ split_generator: Generator = None,
155
+ ) -> tuple[DataLoader, DataLoader, DataLoader]:
156
+ """Splits a dataset into training, validation, and test sets, and returns corresponding DataLoader objects.
157
+
158
+ Args:
159
+ data (Dataset): The dataset to be split.
160
+ loader_args (dict, optional): Default DataLoader arguments, merges
161
+ with loader-specific arguments, overlapping keys from
162
+ loader-specific arguments are superseded.
163
+ train_loader_args (dict, optional): Training DataLoader arguments,
164
+ merges with `loader_args`, overriding overlapping keys.
165
+ valid_loader_args (dict, optional): Validation DataLoader arguments,
166
+ merges with `loader_args`, overriding overlapping keys.
167
+ test_loader_args (dict, optional): Test DataLoader arguments,
168
+ merges with `loader_args`, overriding overlapping keys.
169
+ train_size (float, optional): Proportion of data to be used for
170
+ training. Defaults to 0.8.
171
+ valid_size (float, optional): Proportion of data to be used for
172
+ validation. Defaults to 0.1.
173
+ test_size (float, optional): Proportion of data to be used for
174
+ testing. Defaults to 0.1.
175
+ split_generator (Generator, optional): Optional random seed generator
176
+ to control the splitting of the dataset.
177
+
178
+ Returns:
179
+ tuple: A tuple containing three DataLoader objects: one for the
180
+ training, validation and test set.
181
+
182
+ Raises:
183
+ ValueError: If the train_size, valid_size, and test_size are not
184
+ between 0 and 1, or if their sum does not equal 1.
185
+ """
186
+ # Validate split sizes
187
+ if not (0 < train_size < 1 and 0 < valid_size < 1 and 0 < test_size < 1):
188
+ raise ValueError("train_size, valid_size, and test_size must be between 0 and 1.")
189
+ if not abs(train_size + valid_size + test_size - 1.0) < 1e-6:
190
+ raise ValueError("train_size, valid_size, and test_size must sum to 1.")
191
+
192
+ # Perform the splits
193
+ train_val_data, test_data = random_split(
194
+ data, [1 - test_size, test_size], generator=split_generator
195
+ )
196
+ train_data, valid_data = random_split(
197
+ train_val_data,
198
+ [
199
+ train_size / (1 - test_size),
200
+ valid_size / (1 - test_size),
201
+ ],
202
+ generator=split_generator,
203
+ )
204
+
205
+ # Set default arguments for each loader
206
+ train_loader_args = dict(loader_args or {}, **(train_loader_args or {}))
207
+ valid_loader_args = dict(loader_args or {}, **(valid_loader_args or {}))
208
+ test_loader_args = dict(loader_args or {}, **(test_loader_args or {}))
209
+
210
+ # Create the DataLoaders
211
+ train_generator = DataLoader(train_data, **train_loader_args)
212
+ valid_generator = DataLoader(valid_data, **valid_loader_args)
213
+ test_generator = DataLoader(test_data, **test_loader_args)
214
+
215
+ return train_generator, valid_generator, test_generator
216
+
217
+
218
+ class ZeroLoss(_Loss):
219
+ """A loss function that always returns zero.
220
+
221
+ This custom loss function ignores the input and target tensors
222
+ and returns a constant zero loss, which can be useful for debugging
223
+ or when no meaningful loss computation is required.
224
+
225
+ Args:
226
+ reduction (str, optional): Specifies the reduction to apply to
227
+ the output. Defaults to "mean". Although specified, it has
228
+ no effect as the loss is always zero.
229
+ """
230
+
231
+ def __init__(self, reduction: str = "mean"):
232
+ """Initialize ZeroLoss with a specified reduction method.
233
+
234
+ Args:
235
+ reduction (str): Specifies the reduction to apply to the output. Defaults to "mean".
236
+ """
237
+ super().__init__(reduction=reduction)
238
+
239
+ def forward(self, predictions: Tensor, target: Tensor, **kwargs) -> torch.Tensor:
240
+ """Return a dummy loss of zero regardless of input and target."""
241
+ return (predictions * 0).sum()
242
+
243
+
244
+ class LossWrapper:
245
+ """Wraps a loss function to optionally accept batch-level data.
246
+
247
+ This adapter allows both standard PyTorch loss functions (e.g.
248
+ ``nn.MSELoss``) and custom loss functions that accept an additional
249
+ ``data`` keyword argument to be used interchangeably.
250
+
251
+ The wrapped loss can always be called with the same signature:
252
+
253
+ loss(output, target, data=batch)
254
+
255
+ If the underlying loss function does not accept ``data``, the
256
+ argument is silently ignored.
257
+ """
258
+
259
+ def __init__(self, loss_fn: Callable):
260
+ """Initializes the LossWrapper.
261
+
262
+ Args:
263
+ loss_fn (Callable): The underlying loss function or callable
264
+ (e.g. a ``torch.nn.Module`` or a custom function).
265
+ """
266
+ self.loss_fn = loss_fn
267
+ self.accepts_data = self._accepts_data()
268
+
269
+ def _accepts_data(self) -> bool:
270
+ """Checks whether the wrapped loss function accepts a ``data`` argument.
271
+
272
+ The check returns ``True`` if either:
273
+ - The function explicitly defines a ``data`` parameter, or
274
+ - The function accepts arbitrary keyword arguments (``**kwargs``).
275
+
276
+ Returns:
277
+ bool: ``True`` if the loss function can accept ``data``,
278
+ ``False`` otherwise.
279
+ """
280
+ # For nn.Module, inspect forward(), not __call__()
281
+ if isinstance(self.loss_fn, nn.Module):
282
+ fn = self.loss_fn.forward
283
+ else:
284
+ fn = self.loss_fn
285
+
286
+ sig = inspect.signature(fn)
287
+
288
+ return "data" in sig.parameters or any(
289
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
290
+ )
291
+
292
+ def __call__(self, output: Tensor, target: Tensor, *, data: dict | None = None) -> Tensor:
293
+ """Computes the loss.
294
+
295
+ Args:
296
+ output (torch.Tensor): Model predictions.
297
+ target (torch.Tensor): Ground-truth targets.
298
+ data (dict, optional): Full batch data passed to custom loss
299
+ functions that require additional context.
300
+
301
+ Returns:
302
+ torch.Tensor: Computed loss value.
303
+ """
304
+ if self.accepts_data:
305
+ return self.loss_fn(output, target, data=data)
306
+ return self.loss_fn(output, target)
307
+
308
+
309
+ def process_data_monotonicity_constraint(data: Tensor, ordering: Tensor, identifiers: Tensor):
310
+ """Reorders input samples to support monotonicity checking.
311
+
312
+ Reorders input samples such that:
313
+ 1. Samples from the same run are grouped together.
314
+ 2. Within each run, samples are sorted chronologically.
315
+
316
+ Args:
317
+ data (Tensor): The input data.
318
+ ordering (Tensor): On what to order the data.
319
+ identifiers (Tensor): Identifiers specifying different runs.
320
+
321
+ Returns:
322
+ Tuple[Tensor, Tensor, Tensor]: Sorted data, ordering, and
323
+ identifiers.
324
+ """
325
+ # Step 1: Sort by run identifiers
326
+ sorted_indices = argsort(identifiers, stable=True, dim=0).reshape(-1)
327
+ data_sorted, ordering_sorted, identifiers_sorted = (
328
+ data[sorted_indices],
329
+ ordering[sorted_indices],
330
+ identifiers[sorted_indices],
331
+ )
332
+
333
+ # Step 2: Get unique runs and their counts
334
+ _, counts = unique(identifiers, sorted=False, return_counts=True)
335
+ counts = counts.to(int32) # Avoid repeated conversions
336
+
337
+ sorted_data, sorted_ordering, sorted_identifiers = [], [], []
338
+ index = 0 # Tracks the current batch element index
339
+
340
+ # Step 3: Process each run independently
341
+ for count in counts:
342
+ end = index + count
343
+ run_data, run_ordering, run_identifiers = (
344
+ data_sorted[index:end],
345
+ ordering_sorted[index:end],
346
+ identifiers_sorted[index:end],
347
+ )
348
+
349
+ # Step 4: Sort within each run by time
350
+ time_sorted_indices = argsort(run_ordering, stable=True, dim=0).reshape(-1)
351
+ sorted_data.append(run_data[time_sorted_indices])
352
+ sorted_ordering.append(run_ordering[time_sorted_indices])
353
+ sorted_identifiers.append(run_identifiers[time_sorted_indices])
354
+
355
+ index = end # Move to next run
356
+
357
+ # Step 5: Concatenate results and return
358
+ return (
359
+ cat(sorted_data, dim=0),
360
+ cat(sorted_ordering, dim=0),
361
+ cat(sorted_identifiers, dim=0),
362
+ )
363
+
364
+
365
+ class DictDatasetWrapper(Dataset):
366
+ """A wrapper for PyTorch datasets that converts each sample into a dictionary.
367
+
368
+ This class takes any PyTorch dataset and returns its samples as dictionaries,
369
+ where each element of the original sample is mapped to a key. This is useful
370
+ for integration with the Congrads toolbox or other frameworks that expect
371
+ dictionary-formatted data.
372
+
373
+ Attributes:
374
+ base_dataset (Dataset): The underlying PyTorch dataset being wrapped.
375
+ field_names (list[str] | None): Names assigned to each field of a sample.
376
+ If None, default names like 'field0', 'field1', ... are generated.
377
+
378
+ Args:
379
+ base_dataset (Dataset): The PyTorch dataset to wrap.
380
+ field_names (list[str] | None, optional): Custom names for each field.
381
+ If provided, the list is truncated or extended to match the number
382
+ of elements in a sample. Defaults to None.
383
+
384
+ Example:
385
+ Wrapping a TensorDataset with custom field names:
386
+
387
+ >>> from torch.utils.data import TensorDataset
388
+ >>> import torch
389
+ >>> dataset = TensorDataset(torch.randn(5, 3), torch.randint(0, 2, (5,)))
390
+ >>> wrapped = DictDatasetWrapper(dataset, field_names=["features", "label"])
391
+ >>> wrapped[0]
392
+ {'features': tensor([...]), 'label': tensor(1)}
393
+
394
+ Wrapping a built-in dataset like CIFAR10:
395
+
396
+ >>> from torchvision.datasets import CIFAR10
397
+ >>> from torchvision import transforms
398
+ >>> cifar = CIFAR10(
399
+ ... root="./data", train=True, download=True, transform=transforms.ToTensor()
400
+ ... )
401
+ >>> wrapped_cifar = DictDatasetWrapper(cifar, field_names=["input", "output"])
402
+ >>> wrapped_cifar[0]
403
+ {'input': tensor([...]), 'output': tensor(6)}
404
+ """
405
+
406
+ def __init__(self, base_dataset: Dataset, field_names: list[str] | None = None):
407
+ """Initialize the DictDatasetWrapper.
408
+
409
+ Args:
410
+ base_dataset (Dataset): The PyTorch dataset to wrap.
411
+ field_names (list[str] | None, optional): Optional list of field names
412
+ for the dictionary output. Defaults to None, in which case
413
+ automatic names 'field0', 'field1', ... are generated.
414
+ """
415
+ self.base_dataset = base_dataset
416
+ self.field_names = field_names
417
+
418
+ def __getitem__(self, idx: int):
419
+ """Retrieve a sample from the dataset as a dictionary.
420
+
421
+ Each element in the original sample is mapped to a key in the dictionary.
422
+ If the sample is not a tuple or list, it is converted into a single-element
423
+ tuple. Numerical values (int or float) are automatically converted to tensors.
424
+
425
+ Args:
426
+ idx (int): Index of the sample to retrieve.
427
+
428
+ Returns:
429
+ dict: A dictionary mapping field names to sample values.
430
+ """
431
+ sample = self.base_dataset[idx]
432
+
433
+ # Ensure sample is always a tuple
434
+ if not isinstance(sample, (tuple, list)):
435
+ sample = (sample,)
436
+
437
+ n_fields = len(sample)
438
+
439
+ # Generate default field names if none are provided
440
+ if self.field_names is None:
441
+ names = [f"field{i}" for i in range(n_fields)]
442
+ else:
443
+ names = list(self.field_names)
444
+ if len(names) < n_fields:
445
+ names.extend([f"field{i}" for i in range(len(names), n_fields)])
446
+ names = names[:n_fields] # truncate if too long
447
+
448
+ # Build dictionary
449
+ out = {}
450
+ for name, value in zip(names, sample, strict=False):
451
+ if isinstance(value, (int, float)):
452
+ value = torch.tensor(value)
453
+ out[name] = value
454
+
455
+ return out
456
+
457
+ def __len__(self):
458
+ """Return the number of samples in the dataset.
459
+
460
+ Returns:
461
+ int: Length of the underlying dataset.
462
+ """
463
+ return len(self.base_dataset)
464
+
465
+
466
+ class Seeder:
467
+ """A deterministic seed manager for reproducible experiments.
468
+
469
+ This class provides a way to consistently generate pseudo-random
470
+ seeds derived from a fixed base seed. It ensures that different
471
+ libraries (Python's `random`, NumPy, and PyTorch) are initialized
472
+ with reproducible seeds, making experiments deterministic across runs.
473
+ """
474
+
475
+ def __init__(self, base_seed: int):
476
+ """Initialize the Seeder with a base seed.
477
+
478
+ Args:
479
+ base_seed (int): The initial seed from which all subsequent seudo-random seeds are deterministically derived.
480
+ """
481
+ self._rng = random.Random(base_seed)
482
+
483
+ def roll_seed(self) -> int:
484
+ """Generate a new deterministic pseudo-random seed.
485
+
486
+ Each call returns an integer seed derived from the internal
487
+ pseudo-random generator, which itself is initialized by the
488
+ base seed.
489
+
490
+ Returns:
491
+ int: A pseudo-random integer seed in the range [0, 2**31 - 1].
492
+ """
493
+ return self._rng.randint(0, 2**31 - 1)
494
+
495
+ def set_reproducible(self) -> None:
496
+ """Configure global random states for reproducibility.
497
+
498
+ Seeds the following libraries with deterministically generated seeds based on the base seed:
499
+ - Python's built-in `random`
500
+ - NumPy's random number generator
501
+ - PyTorch (CPU and GPU)
502
+
503
+ Also enforces deterministic behavior in PyTorch by:
504
+ - Seeding all CUDA devices
505
+ - Disabling CuDNN benchmarking
506
+ - Enabling CuDNN deterministic mode
507
+
508
+ """
509
+ random.seed(self.roll_seed())
510
+ np.random.seed(self.roll_seed())
511
+ torch.manual_seed(self.roll_seed())
512
+ torch.cuda.manual_seed_all(self.roll_seed())
513
+
514
+ torch.backends.cudnn.deterministic = True
515
+ torch.backends.cudnn.benchmark = False
@@ -0,0 +1,191 @@
1
+ """Validation utilities for type checking and argument validation.
2
+
3
+ This module provides utility functions for validating function arguments,
4
+ including type validation, callable validation, and PyTorch-specific
5
+ validation functions.
6
+ """
7
+
8
+ from torch.utils.data import DataLoader
9
+
10
+ __all__ = [
11
+ "validate_type",
12
+ "validate_iterable",
13
+ "validate_comparator",
14
+ "validate_callable",
15
+ "validate_callable_iterable",
16
+ "validate_loaders",
17
+ ]
18
+
19
+
20
+ def validate_type(name, value, expected_types, allow_none=False):
21
+ """Validate that a value is of the specified type(s).
22
+
23
+ Args:
24
+ name (str): Name of the argument for error messages.
25
+ value: Value to validate.
26
+ expected_types (type or tuple of types): Expected type(s) for the value.
27
+ allow_none (bool): Whether to allow the value to be None.
28
+ Defaults to False.
29
+
30
+ Raises:
31
+ TypeError: If the value is not of the expected type(s).
32
+ """
33
+ if value is None:
34
+ if not allow_none:
35
+ raise TypeError(f"Argument {name} cannot be None.")
36
+ return
37
+
38
+ if not isinstance(value, expected_types):
39
+ raise TypeError(
40
+ f"Argument {name} '{str(value)}' is not supported. "
41
+ f"Only values of type {str(expected_types)} are allowed."
42
+ )
43
+
44
+
45
+ def validate_iterable(
46
+ name,
47
+ value,
48
+ expected_element_types,
49
+ allowed_iterables=(list, set, tuple),
50
+ allow_empty=False,
51
+ allow_none=False,
52
+ ):
53
+ """Validate that a value is an iterable (e.g., list, set) with elements of the specified type(s).
54
+
55
+ Args:
56
+ name (str): Name of the argument for error messages.
57
+ value: Value to validate.
58
+ expected_element_types (type or tuple of types): Expected type(s)
59
+ for the elements.
60
+ allowed_iterables (tuple of types): Iterable types that are
61
+ allowed (default: list and set).
62
+ allow_empty (bool): Whether to allow empty iterables. Defaults to False.
63
+ allow_none (bool): Whether to allow the value to be None.
64
+ Defaults to False.
65
+
66
+ Raises:
67
+ TypeError: If the value is not an allowed iterable type or if
68
+ any element is not of the expected type(s).
69
+ """
70
+ if value is None:
71
+ if not allow_none:
72
+ raise TypeError(f"Argument {name} cannot be None.")
73
+ return
74
+
75
+ if len(value) == 0:
76
+ if not allow_empty:
77
+ raise TypeError(f"Argument {name} cannot be an empty iterable.")
78
+ return
79
+
80
+ if not isinstance(value, allowed_iterables):
81
+ raise TypeError(
82
+ f"Argument {name} '{str(value)}' is not supported. "
83
+ f"Only values of type {str(allowed_iterables)} are allowed."
84
+ )
85
+ if not all(isinstance(element, expected_element_types) for element in value):
86
+ raise TypeError(
87
+ f"Invalid elements in {name} '{str(value)}'. "
88
+ f"Only elements of type {str(expected_element_types)} are allowed."
89
+ )
90
+
91
+
92
+ def validate_comparator(name, value, comparator_map: dict):
93
+ """Validate that a value is a callable PyTorch comparator function.
94
+
95
+ Args:
96
+ name (str): Name of the argument for error messages.
97
+ value: Value to validate.
98
+ comparator_map: The comparator function map.
99
+
100
+ Raises:
101
+ TypeError: If the value is not a valid comparator.
102
+ """
103
+ if value not in comparator_map:
104
+ raise TypeError(
105
+ f"Unsupported comparator: {value}. Supported comparators are: {list(comparator_map.keys())}."
106
+ )
107
+
108
+
109
+ def validate_callable(name, value, allow_none=False):
110
+ """Validate that a value is callable function.
111
+
112
+ Args:
113
+ name (str): Name of the argument for error messages.
114
+ value: Value to validate.
115
+ allow_none (bool): Whether to allow the value to be None.
116
+ Defaults to False.
117
+
118
+ Raises:
119
+ TypeError: If the value is not callable.
120
+ """
121
+ if value is None:
122
+ if not allow_none:
123
+ raise TypeError(f"Argument {name} cannot be None.")
124
+ return
125
+
126
+ if not callable(value):
127
+ raise TypeError(
128
+ f"Argument {name} '{str(value)}' is not supported. Only callable functions are allowed."
129
+ )
130
+
131
+
132
+ def validate_callable_iterable(
133
+ name,
134
+ value,
135
+ allowed_iterables=(list, set, tuple),
136
+ allow_none=False,
137
+ ):
138
+ """Validate that a value is an iterable containing only callable elements.
139
+
140
+ This function ensures that the given value is an iterable
141
+ (e.g., list or set and that all its elements are callable functions.
142
+
143
+ Args:
144
+ name (str): Name of the argument for error messages.
145
+ value: The value to validate.
146
+ allowed_iterables (tuple of types, optional): Iterable types that are
147
+ allowed. Defaults to (list, set).
148
+ allow_none (bool, optional): Whether to allow the value to be None.
149
+ Defaults to False.
150
+
151
+ Raises:
152
+ TypeError: If the value is not an allowed iterable type or if any
153
+ element is not callable.
154
+ """
155
+ if value is None:
156
+ if not allow_none:
157
+ raise TypeError(f"Argument {name} cannot be None.")
158
+ return
159
+
160
+ if not isinstance(value, allowed_iterables):
161
+ raise TypeError(
162
+ f"Argument {name} '{str(value)}' is not supported. "
163
+ f"Only values of type {str(allowed_iterables)} are allowed."
164
+ )
165
+
166
+ if not all(callable(element) for element in value):
167
+ raise TypeError(
168
+ f"Invalid elements in {name} '{str(value)}'. Only callable functions are allowed."
169
+ )
170
+
171
+
172
+ def validate_loaders(name: str, loaders: tuple[DataLoader, DataLoader, DataLoader]):
173
+ """Validates that `loaders` is a tuple of three DataLoader instances.
174
+
175
+ Args:
176
+ name (str): The name of the parameter being validated.
177
+ loaders (tuple[DataLoader, DataLoader, DataLoader]): A tuple of
178
+ three DataLoader instances.
179
+
180
+ Raises:
181
+ TypeError: If `loaders` is not a tuple of three DataLoader
182
+ instances or contains invalid types.
183
+ """
184
+ if not isinstance(loaders, tuple) or len(loaders) != 3:
185
+ raise TypeError(f"{name} must be a tuple of three DataLoader instances.")
186
+
187
+ for i, loader in enumerate(loaders):
188
+ if not isinstance(loader, DataLoader):
189
+ raise TypeError(
190
+ f"{name}[{i}] must be an instance of DataLoader, got {type(loader).__name__}."
191
+ )