API Reference¶
FlashANSR¶
Flash Amortized Neural Symbolic Regressor.
| PARAMETER | DESCRIPTION |
|---|---|
simplipy_engine
|
Engine responsible for manipulating and evaluating symbolic expressions.
TYPE:
|
flash_ansr_model
|
Trained transformer backbone that proposes expression programs.
TYPE:
|
tokenizer
|
Tokenizer mapping model outputs to expression tokens.
TYPE:
|
generation_config
|
Configuration that controls candidate generation. If
TYPE:
|
n_restarts
|
Number of optimizer restarts used by the refiner when fitting constants.
TYPE:
|
refiner_method
|
Optimization routine employed by the refiner.
TYPE:
|
refiner_p0_noise
|
Distribution applied to perturb initial constant guesses.
TYPE:
|
refiner_p0_noise_kwargs
|
Keyword arguments forwarded to the noise sampler.
TYPE:
|
numpy_errors
|
Desired NumPy error handling strategy applied during constant refinement.
TYPE:
|
length_penalty
|
Penalty coefficient that discourages overly long expressions.
TYPE:
|
constants_penalty
|
Penalty coefficient applied to the number of constants present in an expression.
TYPE:
|
likelihood_penalty
|
Penalty coefficient applied to the negative log likelihood of the generated beam.
TYPE:
|
refiner_workers
|
Number of worker processes to run during constant refinement.
TYPE:
|
prune_constant_budget
|
Apply constant-pruning refinement to the best beams after the initial
refinement (ranked by FVU). If
TYPE:
|
Source code in src/flash_ansr/flash_ansr.py
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 | |
load
classmethod
¶
load(directory: str, generation_config: GenerationConfig | None = None, n_restarts: int = 8, refiner_method: Literal['curve_fit_lm', 'minimize_bfgs', 'minimize_lbfgsb', 'minimize_neldermead', 'minimize_powell', 'least_squares_trf', 'least_squares_dogbox'] = 'curve_fit_lm', refiner_p0_noise: Literal['uniform', 'normal', 'cauchy', 'magspan'] | None = 'normal', refiner_p0_noise_kwargs: dict | None | Literal['default'] = 'default', numpy_errors: Literal['ignore', 'warn', 'raise', 'call', 'print', 'log'] | None = 'ignore', length_penalty: float = 0.05, constants_penalty: float = 0.0, likelihood_penalty: float = 0.0, device: str = 'cpu', refiner_workers: int | None = None, prune_constant_budget: float | int = 0, persistent_refine_pool: bool = False) -> FlashANSR
Instantiate a FlashANSR model from a configuration directory.
| PARAMETER | DESCRIPTION |
|---|---|
directory
|
Directory that contains
TYPE:
|
generation_config
|
Generation parameters to override defaults during candidate search.
TYPE:
|
n_restarts
|
Number of restarts passed to the refiner.
TYPE:
|
refiner_method
|
Optimization routine for constant fitting.
TYPE:
|
refiner_p0_noise
|
Distribution used to perturb initial constant guesses.
TYPE:
|
refiner_p0_noise_kwargs
|
Additional keyword arguments for the noise sampler.
TYPE:
|
numpy_errors
|
NumPy floating-point error policy applied during refinement.
TYPE:
|
length_penalty
|
Length penalty used when compiling results.
TYPE:
|
constants_penalty
|
Penalty applied per constant present in the expression during scoring.
TYPE:
|
likelihood_penalty
|
Penalty applied to the negative log likelihood of each beam.
TYPE:
|
device
|
Torch device where the model weights will be loaded.
TYPE:
|
refiner_workers
|
Desired worker-pool size for constant refinement.
TYPE:
|
prune_constant_budget
|
Number of top beams (by FVU) or fraction of beams (if 0<value<=1) to prune after initial refinement when pruning is enabled.
TYPE:
|
persistent_refine_pool
|
When
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
model
|
Fully initialized regressor ready for inference.
TYPE:
|
Source code in src/flash_ansr/flash_ansr.py
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | |
fit ¶
fit(X: ndarray | Tensor | DataFrame, y: ndarray | Tensor | DataFrame | Series, variable_names: list[str] | dict[str, str] | Literal['auto'] | None = 'auto', converge_error: Literal['raise', 'ignore', 'print'] = 'ignore', verbose: bool = False, *, complexity: int | float | None = None, allowed_terms: Iterable[Sequence[Any]] | None = None, include_terms: Iterable[Sequence[Any]] | None = None, exclude_terms: Iterable[Sequence[Any]] | None = None, refine_seed: int | None = None) -> None
Perform symbolic regression on (X, y) and refine candidate expressions.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Feature matrix where rows index observations and columns variables.
TYPE:
|
y
|
Target values. Multi-output targets are unsupported.
TYPE:
|
variable_names
|
Mapping from internal variable tokens to descriptive names.
TYPE:
|
converge_error
|
Handling strategy when the refiner fails to converge.
TYPE:
|
verbose
|
If
TYPE:
|
allowed_terms
|
Keyword-only list of term token sequences that may appear in the generated expression.
TYPE:
|
include_terms
|
Keyword-only subset of allowed terms that the expression should prioritise using.
TYPE:
|
exclude_terms
|
Keyword-only list of term token sequences that should be discouraged during generation.
TYPE:
|
refine_seed
|
Keyword-only seed for the constant-refinement
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/flash_ansr/flash_ansr.py
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 | |
infer ¶
infer(X: ndarray | Tensor | DataFrame, y: ndarray | Tensor | DataFrame | Series, variable_names: list[str] | dict[str, str] | Literal['auto'] | None = 'auto', *, X_val: ndarray | Tensor | DataFrame | None = None, complexity: int | float | None = None, converge_error: Literal['raise', 'ignore', 'print'] = 'ignore', refine_seed: int | None = None, predict_val: bool = True, top_k: int | None = None, verbose: bool = False) -> InferenceResult
Run symbolic regression on (X, y) and return ALL candidates directly.
Unlike :meth:fit (which commits to self._results for later predict /
get_expression read-back), infer returns an :class:~flash_ansr.inference.InferenceResult:
the score-sorted refined :class:~flash_ansr.inference.Candidates PLUS the full
:class:~flash_ansr.inference.CandidateLedger (the generation pool joined with the refined
survivors, classified FIT_OK / FIT_FAILED / INVALID). It writes NOTHING to instance state, so
it neither disturbs nor depends on self._results.
y_pred / y_pred_val are computed only for the top top_k candidates (top_k=None
-> the best only): evaluating every candidate is O(candidates x n_support) and would blow up
RAM at high candidate counts. predict_val toggles the validation-set prediction.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Support feature matrix and targets (the data to fit).
TYPE:
|
y
|
Support feature matrix and targets (the data to fit).
TYPE:
|
variable_names
|
Variable-name mapping (as in :meth:
TYPE:
|
X_val
|
Out-of-sample features for
TYPE:
|
complexity
|
As in :meth:
TYPE:
|
converge_error
|
As in :meth:
TYPE:
|
refine_seed
|
As in :meth:
TYPE:
|
verbose
|
As in :meth:
TYPE:
|
predict_val
|
Whether to compute validation predictions for the top candidates.
TYPE:
|
top_k
|
Compute
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
InferenceResult
|
Score-sorted candidates + the full candidate ledger + generation / refinement times.
If NO beam converges, |
Source code in src/flash_ansr/flash_ansr.py
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 | |
predict ¶
predict(X: ndarray | Tensor | DataFrame, nth_best_beam: int = 0, nth_best_constants: int = 0) -> np.ndarray
Evaluate a fitted expression on new data.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Feature matrix to evaluate.
TYPE:
|
nth_best_beam
|
Beam index to select from the ranked results.
TYPE:
|
nth_best_constants
|
Index of the constant fit to choose for the selected beam.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
y_pred
|
Predicted targets with the same leading dimension as
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the model has not been fitted before prediction. |
Source code in src/flash_ansr/flash_ansr.py
get_expression ¶
get_expression(nth_best_beam: int = 0, nth_best_constants: int = 0, return_prefix: bool = False, precision: int = 2, map_variables: bool = True, **kwargs: Any) -> list[str] | str
Retrieve a formatted expression from the compiled results.
| PARAMETER | DESCRIPTION |
|---|---|
nth_best_beam
|
Beam index to extract from
TYPE:
|
nth_best_constants
|
Constant fit index for the selected beam.
TYPE:
|
return_prefix
|
If
TYPE:
|
precision
|
Number of decimal places used when rendering constants.
TYPE:
|
map_variables
|
When
TYPE:
|
**kwargs
|
Extra keyword arguments forwarded to :meth:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
expression
|
Expression either as a token list or human-readable string.
TYPE:
|
Source code in src/flash_ansr/flash_ansr.py
save_results ¶
Persist fitted results (minus lambdas) for later reuse.
Source code in src/flash_ansr/flash_ansr.py
load_results ¶
Load previously saved results and rebuild refiners if requested.
Source code in src/flash_ansr/flash_ansr.py
compile_results ¶
compile_results(length_penalty: float | None = None, constants_penalty: float | None = None, likelihood_penalty: float | None = None) -> None
Aggregate refiner outputs into a tidy pandas.DataFrame.
| PARAMETER | DESCRIPTION |
|---|---|
length_penalty
|
Length penalty applied during score recomputation. Defaults to the
current
TYPE:
|
constants_penalty
|
Constant-count penalty applied during score recomputation. Defaults
to the current
TYPE:
|
likelihood_penalty
|
Negative log-likelihood penalty applied during score recomputation.
Defaults to the current
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ConvergenceError
|
If no beams converged during refinement. |
Source code in src/flash_ansr/flash_ansr.py
Inference results¶
The objects returned by FlashANSR.infer: the score-sorted refined candidates plus the full classified candidate ledger.
InferenceResult.to_dataframe() returns the refined survivors (the FIT_OK candidates in result.candidates) as a pandas DataFrame, one row per candidate; it does not include the full ledger.
InferenceResult¶
The result of one :meth:FlashANSR.infer: score-sorted refined candidates + the full ledger.
Candidate¶
One refined survivor (a generated expression that fitted). Rich, for interactive use.
CandidateLedger¶
The FULL generation pool U refined survivors, classified -- the lean columnar "all candidates" object (tokens + fvu + log_prob + valid + fit_status + best-constants). Holds NO model objects.
FlashANSRDataset¶
Dataset wrapper for amortized neural symbolic regression training.
Manages skeleton sampling, support point generation, optional prompt
preprocessing, and collation into model-ready batches. Can also compile
streaming output into an on-disk datasets.Dataset for deterministic
iteration.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
symbolic-data problem source streaming ready-to-use Problems (skeleton + support points) from its underlying generative catalog.
TYPE:
|
tokenizer
|
Tokenizer used for expression serialization and padding.
TYPE:
|
padding
|
Strategy for padding numeric support points.
TYPE:
|
preprocessor
|
Prompt-aware preprocessor; when provided, prompt metadata can be injected during sampling or in worker processes.
TYPE:
|
Notes
This object owns a multiprocessing worker pool. Call dataset.shutdown()
when done, or use it as a context manager
(with FlashANSRDataset(...) as dataset:) so the pool is shut down
automatically. If neither is done, a warning is emitted at garbage
collection.
Source code in src/flash_ansr/data/data.py
from_config
classmethod
¶
Instantiate from a YAML/dict config.
Paths are normalized via load_config and substitute_root_path. The
config carries a source: block: {catalog: <path-to-catalog-yaml OR
inline dict>, sampling: {...}}. The catalog (a generative
lample_charton catalog) is loaded into a dict and handed to a
ProblemSource.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Dataset config or path to a YAML file.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FlashANSRDataset
|
Dataset wrapper with tokenizer and optional preprocessor wired. |
Source code in src/flash_ansr/data/data.py
iterate ¶
iterate(size: int | None = None, steps: int | None = None, batch_size: int | None = None, n_support: int | None = None, max_seq_len: int = 512, max_n_support: int | None = None, n_per_equation: int = 1, preprocess: bool = False, preprocess_in_worker: bool | None = None, include_metrics: Sequence[str] | str | None = None, tokenizer_oov: Literal['unk', 'raise'] = 'raise', num_workers: int | None = None, prefetch_factor: int = 2, persistent: bool = False, unconditional_prob: float | None = None, tqdm_kwargs: dict[str, Any] | None = None, verbose: bool = False) -> Generator[dict[str, Any], None, None]
Stream batches of synthetic data.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
Total number of samples to generate (used if
TYPE:
|
steps
|
Number of generation steps; overrides
TYPE:
|
batch_size
|
Samples per step; defaults to 1.
TYPE:
|
n_support
|
Support points per equation; pool default when None.
TYPE:
|
max_seq_len
|
Maximum prefix length for generated expressions.
TYPE:
|
max_n_support
|
Upper bound for support points; used for padding.
TYPE:
|
n_per_equation
|
Number of datasets to draw per skeleton before moving on.
TYPE:
|
preprocess
|
Whether to run the preprocessor on generated batches.
TYPE:
|
preprocess_in_worker
|
Force preprocessing inside workers (True), main process (False), or auto-select (None).
TYPE:
|
include_metrics
|
Metrics to compute for each sampled expression. Supported values: "fisher", "hessian".
TYPE:
|
tokenizer_oov
|
How to handle tokens missing from the tokenizer.
TYPE:
|
num_workers
|
Worker count for multiprocessing; defaults to CPU count when None.
TYPE:
|
prefetch_factor
|
Jobs per worker to pre-schedule.
TYPE:
|
persistent
|
Clone tensors to detach from shared memory buffers.
TYPE:
|
tqdm_kwargs
|
Additional arguments forwarded to tqdm progress bars.
TYPE:
|
verbose
|
Enable progress reporting.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
dict
|
Model-ready batch with tensors and optional prompt metadata. |
Source code in src/flash_ansr/data/data.py
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 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 | |
compile ¶
compile(size: int | None = None, steps: int | None = None, batch_size: int | None = None, n_support: int | None = None, verbose: bool = False) -> None
Materialize a streaming iterator into an on-disk dataset.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
Total number of samples to generate (used if
TYPE:
|
steps
|
Number of iteration steps (overrides
TYPE:
|
batch_size
|
Per-step generation batch size; defaults to 1.
TYPE:
|
n_support
|
Number of support points per equation; falls back to pool defaults.
TYPE:
|
verbose
|
Enable progress reporting.
TYPE:
|
Source code in src/flash_ansr/data/data.py
save ¶
save(directory: str, *args: Any, config: dict[str, Any] | str | None = None, reference: str = 'relative', recursive: bool = True, **kwargs: Any) -> None
Persist the compiled dataset and its config.
| PARAMETER | DESCRIPTION |
|---|---|
directory
|
Target directory for
TYPE:
|
config
|
Config to save alongside the dataset. When omitted a warning is raised and only the data is stored.
TYPE:
|
reference
|
How to normalize paths when writing the config.
TYPE:
|
recursive
|
Whether to recursively resolve nested configs.
TYPE:
|
*args
|
Passed to
TYPE:
|
**kwargs
|
Passed to
TYPE:
|
Source code in src/flash_ansr/data/data.py
FlashANSRPreprocessor¶
Format batch inputs and optionally enrich them with prompt metadata.
Source code in src/flash_ansr/preprocessing/pipeline.py
from_config
classmethod
¶
from_config(config: dict[str, Any] | str | None, *, simplipy_engine: SimpliPyEngine, tokenizer: Tokenizer, catalog: LampleChartonCatalog | None = None, rng: Generator | None = None) -> 'FlashANSRPreprocessor'
Construct a preprocessor from a config plus the required runtime dependencies.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Config mapping or path to a config file. A top-level
TYPE:
|
simplipy_engine
|
Engine used to manipulate and evaluate symbolic expressions.
TYPE:
|
tokenizer
|
Tokenizer used to serialize prompts and expressions.
TYPE:
|
catalog
|
Catalog enabling prompt-feature extraction; prompts are only emitted when a catalog is supplied and the configured prompt probability is positive.
TYPE:
|
rng
|
Random generator driving stochastic prompt inclusion. Defaults to a fresh generator.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FlashANSRPreprocessor
|
The configured preprocessor. |
Source code in src/flash_ansr/preprocessing/pipeline.py
format ¶
Format a batch instance-by-instance, optionally enriching it with prompt metadata.
Each instance in batch is formatted (adding input_num / prompt_mask /
prompt_metadata and, when enabled, a sampled prompt prefix), then the results are
re-stacked back into per-key lists.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
A batch mapping keys to per-instance sequences; must contain
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
The batch with formatted fields. Returned unchanged if |
Source code in src/flash_ansr/preprocessing/pipeline.py
serialize_prompt_prefix ¶
serialize_prompt_prefix(*, complexity: float | int | None = None, allowed_terms: Iterable[Sequence[Any]] | None = None, include_terms: Iterable[Sequence[Any]] | None = None, exclude_terms: Iterable[Sequence[Any]] | None = None) -> dict[str, Any]
Serialize an explicit prompt prefix constraining generation.
Builds the token prefix (starting from <bos>) that encodes the requested constraints,
emitting the <prompt> block only when the tokenizer defines the needed special tokens.
| PARAMETER | DESCRIPTION |
|---|---|
complexity
|
Target expression complexity to encode in the prompt.
TYPE:
|
allowed_terms
|
Terms the generated expression is restricted to.
TYPE:
|
include_terms
|
Terms that must appear in the generated expression.
TYPE:
|
exclude_terms
|
Terms that must not appear in the generated expression.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
The serialized prefix with |
Source code in src/flash_ansr/preprocessing/pipeline.py
Generation configurations¶
BeamSearchConfig¶
Configuration for beam-search based generation.
Source code in src/flash_ansr/utils/generation.py
to_kwargs ¶
Return the beam-search keyword arguments (beam_width, max_len, ...).
Source code in src/flash_ansr/utils/generation.py
SoftmaxSamplingConfig¶
Configuration for softmax sampling generation.
Source code in src/flash_ansr/utils/generation.py
to_kwargs ¶
Return the softmax-sampling keyword arguments (choices, top_k, top_p, ...).
Source code in src/flash_ansr/utils/generation.py
MCTSGenerationConfig¶
Configuration for Monte Carlo tree search generation.
Source code in src/flash_ansr/utils/generation.py
to_kwargs ¶
Return the MCTS keyword arguments (simulations, uct_c, max_depth, ...).
Source code in src/flash_ansr/utils/generation.py
Utilities¶
Resolve a path relative to the project root (see :func:get_root).
Optionally creates the directories leading to the resolved path when create is set.
Source code in src/flash_ansr/utils/paths.py
Load a YAML config (optionally resolving nested relative paths).