SageMath backend¶
When using backend="sagemath", the following classes are used for generation and sampling. You can also use them directly without DatasetPipeline.
See Dataset Generator (Overview) for the pipeline and data.yaml configuration.
DatasetGenerator ¶
DatasetGenerator(
backend: str = "multiprocessing",
n_jobs: int = -1,
verbose: bool = True,
root_seed: int = 42,
)
Base class for instance generators
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str
|
Backend for parallel processing |
'multiprocessing'
|
n_jobs
|
int
|
Number of parallel jobs (-1 for all cores) |
-1
|
verbose
|
bool
|
Whether to display progress information |
True
|
root_seed
|
int
|
Root seed for reproducibility |
42
|
Source code in src/calt/dataset/sagemath/dataset_generator.py
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 | |
run ¶
run(
dataset_sizes: dict[str, int],
instance_generator: Callable,
statistics_calculator: Callable | None = None,
dataset_writer: DatasetWriter | None = None,
batch_size: int = 100000,
save_dir: str | None = None,
save_text: bool = True,
save_json: bool = True,
)
Generate multiple datasets using parallel processing with batch writing.
This is the main entry point for dataset generation. It supports generating multiple datasets (train/test) simultaneously or separately, with efficient memory management through batch processing and parallel execution.
Key features:
- Parallel processing using joblib for high performance
- Batch-based memory management to handle large datasets
- Incremental statistics calculation to avoid memory issues
- Reproducible generation with unique seeds for each sample
- Support for nested data structures (up to 2 levels)
- Multiple output formats (text, JSON Lines) via DatasetWriter
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_sizes
|
dict[str, int]
|
Dictionary mapping dataset names to number of samples. Any string can be used as dataset name (e.g., "train", "test", "validation"). Duplicate names are not allowed. Example: {"train": 100000, "test": 1000} or {"train": 100000, "validation": 5000} |
required |
instance_generator
|
Callable
|
Function that generates (problem, answer) pair given a seed. Must accept a single integer seed parameter. |
required |
statistics_calculator
|
Callable | None
|
Optional function to calculate sample-specific statistics. Must accept (problem, answer) and return dict or None. |
None
|
dataset_writer
|
DatasetWriter | None
|
DatasetWriter object for saving datasets to files. If None, a new DatasetWriter will be created using save_dir, save_text, and save_json parameters. |
None
|
batch_size
|
int
|
Number of samples to process in each batch. Larger batches use more memory but may be more efficient for I/O operations. |
100000
|
save_dir
|
str | None
|
Base directory for saving datasets. Used only if dataset_writer is None. If None, uses current working directory. |
None
|
save_text
|
bool
|
Whether to save raw text files. Used only if dataset_writer is None. Text files use "#" as separator between problem and answer. |
True
|
save_json
|
bool
|
Whether to save JSON Lines files. Used only if dataset_writer is None. JSON Lines files preserve the original nested structure format. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If dataset_sizes is invalid or instance_generator is None |
Exception
|
If parallel processing fails |
Note
- Each sample gets a unique seed for reproducibility
- Progress is logged if verbose=True (set in init)
- Memory usage scales with batch_size, not total dataset size
- Statistics are calculated incrementally to handle large datasets
- If dataset_writer is provided, save_dir, save_text, and save_json parameters are ignored
Examples:
>>> # Define instance generator function
>>> def instance_generator(seed):
... import random
... random.seed(seed)
... # Generate random polynomial problem
... problem = [random.randint(1, 1000) for _ in range(random.randint(1, 10))]
... answer = sum(problem)
... return problem, answer
>>>
>>> # Initialize dataset generator
>>> generator = DatasetGenerator(n_jobs=-1, verbose=True)
>>>
>>> # Method 1: Automatic DatasetWriter creation
>>> generator.run(
... dataset_sizes={"train": 10000, "test": 1000, "validation": 500},
... instance_generator=instance_generator,
... save_dir="./datasets",
... save_text=True,
... save_json=True,
... batch_size=100
... )
>>>
>>> # Method 2: Manual DatasetWriter creation (for advanced use cases)
>>> from calt.dataset.sagemath import DatasetWriter
>>> writer = DatasetWriter(save_dir="./datasets", save_text=True, save_json=True)
>>> generator.run(
... dataset_sizes={"train": 10000, "test": 1000},
... instance_generator=instance_generator,
... dataset_writer=writer,
... batch_size=100
... )
>>>
>>> # Method 3: Generate datasets separately (if needed)
>>> generator.run(
... dataset_sizes={"train": 10000},
... instance_generator=instance_generator,
... save_dir="./datasets",
... batch_size=100
... )
>>> generator.run(
... dataset_sizes={"test": 1000, "validation": 500},
... instance_generator=instance_generator,
... save_dir="./datasets",
... batch_size=100
... )
Source code in src/calt/dataset/sagemath/dataset_generator.py
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 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | |
PolynomialSampler ¶
PolynomialSampler(
symbols: str | None = None,
field_str: str | None = None,
order: str | TermOrder | None = "degrevlex",
ring: Any = None,
max_num_terms: int | None = 10,
max_degree: int = 5,
min_degree: int = 0,
degree_sampling: str = "uniform",
term_sampling: str = "uniform",
max_coeff: int | None = None,
num_bound: int | None = None,
strictly_conditioned: bool = True,
nonzero_instance: bool = True,
nonzero_coeff: bool = True,
max_attempts: int = 1000,
)
Generator for random polynomials with specific constraints.
The sampler builds polynomials by first choosing a target degree and number of terms (within min/max bounds), then selecting that many distinct monomials and assigning random coefficients from the base ring. Ring and constraints can be given either as (symbols, field_str, order) or as a pre-built PolynomialRing.
Behavior summary¶
degree_sampling controls how monomial degrees are chosen:
'uniform': For each term, a degree in [min_degree, max_degree] is chosen uniformly at random, then a monomial of that degree is chosen. The resulting polynomial's degree distribution is more uniform over the range.'fixed': Monomials are chosen uniformly from all monomials of degree at most max_degree. Because there are more such monomials at higher degrees, the polynomial tends to have total degree equal to max_degree.
Degree and number of terms: Every returned polynomial has total
degree >= min_degree. The guarantees on total degree and number of
terms depend on strictly_conditioned and nonzero_coeff; see
the constructor parameters for details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
str | None
|
Variable names for the polynomial ring (required if ring is None). |
None
|
field_str
|
str | None
|
Base ring specifier: "QQ", "RR", "ZZ", or "GF(p)" for a prime finite field (required if ring is None). |
None
|
order
|
str | TermOrder | None
|
Term order of the ring, e.g. "degrevlex" (required if ring is None). |
'degrevlex'
|
ring
|
Any
|
Pre-built PolynomialRing (alternative to symbols/field_str/order). |
None
|
max_num_terms
|
int | None
|
Upper bound on number of terms. If None, all monomials of the chosen degree are allowed. |
10
|
max_degree
|
int
|
Maximum total degree of the polynomial. |
5
|
min_degree
|
int
|
Minimum total degree; every returned polynomial has total degree >= min_degree. |
0
|
max_coeff
|
int | None
|
Bound on coefficient absolute value for RR and ZZ. |
None
|
num_bound
|
int | None
|
Bound on numerator/denominator absolute value for QQ. |
None
|
degree_sampling
|
str
|
|
'uniform'
|
term_sampling
|
str
|
|
'uniform'
|
strictly_conditioned
|
bool
|
Controls when a generated polynomial is accepted.
|
True
|
nonzero_instance
|
bool
|
If True, the zero polynomial is never returned. |
True
|
nonzero_coeff
|
bool
|
If True, no coefficient is zero (default); gives a predictable number of terms and fewer retries when strictly_conditioned is True. |
True
|
max_attempts
|
int
|
Maximum trials per polynomial when strictly_conditioned is True; RuntimeError is raised if no success. |
1000
|
Source code in src/calt/dataset/sagemath/utils/polynomial_sampler.py
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 | |
get_field ¶
get_field()
Convert field_str to the SageMath base ring (QQ, RR, ZZ, or GF(p)).
Source code in src/calt/dataset/sagemath/utils/polynomial_sampler.py
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 | |
get_ring ¶
get_ring() -> PolynomialRing
Return the polynomial ring (the configured ring if set, otherwise one built from symbols/field_str/order).
Returns:
| Name | Type | Description |
|---|---|---|
PolynomialRing |
PolynomialRing
|
The polynomial ring. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If polynomial ring creation fails with informative error message. |
Source code in src/calt/dataset/sagemath/utils/polynomial_sampler.py
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 | |
sample ¶
sample(
num_samples: int = 1,
size: tuple[int, int] | None = None,
density: float = 1.0,
matrix_type: str | None = None,
) -> list[MPolynomial_libsingular] | list[matrix]
Generate random polynomial samples
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_samples
|
int
|
Number of samples to generate |
1
|
size
|
tuple[int, int] | None
|
If provided, generate matrix of polynomials with given size |
None
|
density
|
float
|
Probability of non-zero entries in matrix |
1.0
|
matrix_type
|
str | None
|
Special matrix type (e.g., 'unimodular_upper_triangular') |
None
|
Returns:
| Type | Description |
|---|---|
list[MPolynomial_libsingular] | list[matrix]
|
List of polynomials or polynomial matrices |
Source code in src/calt/dataset/sagemath/utils/polynomial_sampler.py
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 | |