↓ Skip to main content

IntegralIndx: semantic search for integrals

IntegralIndx is a search engine I built for finding integrals by what they mean rather than by how they happen to be typed. You hand it an integrand, and it hands back mathematically similar ones out of a database scraped from Math StackExchange. Try the live demo, or browse the code.

IntegralIndx web app showing a query and its most similar integrals
The live demo.

This post is how it works: e-graphs and contrastive learning for the embeddings, and a rather long fight with real-world LaTeX for the data.

Why I Built This
#

In my mathematics research1 I spend a lot of time searching for integrals online, mainly on Google and on Math StackExchange. It is often very frustrating because this kind of textual search works well only on very simple integrals, and even then I might miss useful results due to syntactic differences between my query and the results I was after. This happens because mathematical expressions can be written in many different ways, due to: basic mathematical rules (commutativity, power rules, etc.), naming conventions (e^x vs. exp(x), arcsin vs. sin^{-1}), or even personal taste in TeX formatting (arbitrary choice of the variable of integration, parameter names, and TeX commands).

For years, I had this idea in the back of my mind: build a proper, searchable integral database. I wanted a search engine that actually ‘understands’ mathematical expressions, providing an easy way to find other semantically similar integrals, something which simple bag-of-words approaches just can’t do.

Only now, when I finally found some free time, and after delving deeper into machine learning theory at university, I realized how ridiculously complex this problem actually is. The key thing needed for such a search engine is good embeddings of mathematical expressions, ones that capture the actual semantic meaning of the symbols involved. So I started reading some literature. I found MathBERT (Peng et al., 2021), which showed impressive results on mathematical reasoning tasks. The thing is, it’s fundamentally a language model. It’s trained on mathematical text with surrounding natural language, learning to predict masked tokens based on textual context. Even though it works reasonably well, I wanted something that understands pure mathematical equivalence without any surrounding text.

Then I found SemEmb (Gangwar & Kani, 2023), which creates embeddings over symbolic expressions directly. This seemed like exactly what I was looking for! It had decent results and was heading in the right direction. But then I stumbled upon the recent E-Gen (Zheng et al., 2025) paper, and I was genuinely thrilled. E-Gen took everything SemEmb was doing and pushed it much further. The greatest obstacle thus far was the very limited amount of meaningful training data available. The authors of E-Gen proposed a beautiful solution for this problem (using e-graphs), and showed how to generate massive synthetic datasets of equivalent expressions starting with only a small initial set of clean mathematical expressions. I immediately knew that I must try it out.

This demo is my attempt at putting my idea into practice, and build a search engine that actually understands mathematical expressions.

E-Graphs & E-Gen Overview
#

How Do We Get Good Embeddings of Mathematical Expressions?
#

The key insight is that embeddings need to capture semantic equivalence, not just syntactic similarity. If two expressions are mathematically identical, like \(\sin^2(x) + \cos^2(x)\) and \(1\), their embeddings should be close together in vector space. But how do you teach a neural network what “mathematically equivalent” means? The answer is to train it on pairs (or clusters) of equivalent expressions. By showing the model many (!) examples of expressions that mean the same thing but look different, it learns to recognize the underlying mathematical structure rather than just memorizing symbol patterns. As I mentioned, the main challenge is in the creation of a large enough corpus of such equivalence clusters, so that a model can actually read some signal off of the data.

SemEmb took this approach by generating equivalent expression pairs using SymPy’s simplification functions. The problem is that SymPy is designed to find the most simplified form directly, without generating intermediate steps. This meant SemEmb was limited to cluster sizes of just 2 (pairs of expressions), missing out on the rich diversity of equivalent expressions that exist between the original and simplified forms.

E-Gen’s Innovation: E-Graphs
#

E-Gen solves this limitation using e-graphs (equality graphs), a data structure originally invented in 1980 by Nelson & Oppen for automated theorem proving. The idea of equality saturation (applying all possible equalities within an e-graph until saturation) was later leveraged for program optimization by Tate et al. (2009), and more recently, Willsey et al. (2021) developed the egg library, which made equality saturation fast and practical (via new techniques like efficient rebuilding and e-class analyses). Instead of producing just a pair of expressions, equality saturation starts with a seed expression and systematically applies mathematical rewrite rules to explore the entire space of equivalent forms. The e-graph compactly represents all these equivalences in “e-classes”, where each e-class contains expressions that are mathematically identical (see this blogpost for a really nice introduction to e-graphs).

This enables E-Gen to generate dozens or even hundreds of equivalent forms per seed expression, creating rich training datasets where each expression becomes a large cluster of mathematically equivalent variants. A transformer trained on these massive clusters using contrastive learning (pulling equivalent expressions together, pushing unrelated ones apart) learns to capture deep semantic relationships rather than surface-level syntactic patterns.

Overview of the E-Gen framework and its cluster-based training setup
Figure 1: Overview of E-Gen and the cluster-based training framework. Equivalent expressions of each initial expression are generated using an e-graph-based approach, forming clusters of equivalent expressions. The original E-Gen paper implemented both a seq2seq model (trained on equivalent expression pairs) and a contrastive learning model (trained on triplets). For IntegralIndx, I chose to focus on the contrastive learning approach because it’s more efficient for similarity search tasks, learning embeddings directly without requiring a decoder. Source: Zheng et al. (2025), “E-Gen: Leveraging E-Graphs to Improve Continuous Representations of Symbolic Expressions.” Figure 2.

The key insight is that expressions like \(x^2 + 2x + 1\) and \((x + 1)^2\) are mathematically identical, and their embeddings should reflect this equivalence. E-graphs provide the machinery to systematically generate and exploit these equivalences during training, going far beyond what simple rewrite rules can achieve.

Data Collection & Processing Pipeline
#

Of course, good embeddings mean little without actual data to embed. I turned to Math StackExchange for the data, knowing that it contains thousands of high-quality integrals from real problems, that people asked about and cared to solve. Better yet, each integral can be linked to its source discussion, which often includes the context in which this integral arises, possible closed-forms, and a variety of solution attempts.

When I started this project, I thought the data part would be straightforward. Scrape the integrals from MSE, throw them in a database, and move on to the interesting ML work. Naive me.

Data processing is easily the hardest part of this entire project. Real-world LaTeX from MSE is messy, inconsistent, and filled with edge cases I never imagined. People write integrals in dozens of different ways, use custom macros, nest them in complex equation environments, and mix them with narrative text. I needed to convert all of this dirty, real-world LaTeX into a clean, normalized form that could be reliably parsed.

Why can’t we just use the LaTeX as is?
#

LaTeX is designed for typesetting, not semantic analysis. The expression \(x^2\) can be written as x^2, x^{2}, {x}^{ 2 }, and many other variations which result in the same visuals. These different strings would be treated as unrelated expressions if we were to tokenize LaTeX directly. SymPy provides semantic parsing: a canonical tree representation that stays the same regardless of how the expression was typeset. This semantic representation is useful here for two reasons: first, it gives an easy way to convert the expression to prefix notation (pow x 2), which is a good format to apply tokenization to, and second, it allows us to use SymPy’s simplification functions to deduplicate integrals by their canonical integrand.

But getting to that point required building custom parsing logic to clean the raw MSE data. After applying a plethora of hand-tailored normalization and filtering rules (which I’ll describe below), we still need to convert the cleaned LaTeX into SymPy format. While there are some good LaTeX-to-SymPy parsers out there, nothing exactly fit my requirements. I ended up forking the latex2sympy2_extended package (which is itself a fork of previous latex2sympy versions) and adding custom parsing capabilities for some special functions. Even then, I had to be pretty restrictive: blacklisting certain LaTeX commands that caused parsing issues, setting timeouts on the parser (20 seconds per expression), and rejecting anything that looked remotely ambiguous. I’m sure I lost thousands of potentially valid integrals in the process, but reliability was more important than coverage.

What started as “just scrape and parse” became a multi-stage pipeline with normalization, validation, deduplication, and variable canonicalization. Let me walk you through it.

Pipeline Overview
#

Four stages take the corpus from 206k raw strings down to 12,337 distinct integrands.

Scraping. I queried the Math StackExchange API across 20 integral-related tags (closed-form, integration, definite-integrals, special-functions, polylogarithm, and so on), taking 80 pages per tag at 100 questions per page, sorted by votes. Questions and answers together gave 206,328 raw LaTeX strings.

LaTeX normalization. MSE posts wrap their mathematics in align and equation environments, chain several forms of the same quantity together, and tack conditions onto the end. So the raw strings are parsed into structure first: environments unwrapped, relation chains split into their members (so \(A = B = C\) becomes \(\{A, B, C\}\), which conveniently hands us equivalent forms for free), and parametric conditions like “for \(x > 0\)” separated from the expression they constrain.

Extraction and validation. Definite and indefinite integrals are pulled out of the normalized strings and handed to SymPy, which acts as the arbiter: anything it refuses to parse, or that reaches for a function outside the vocabulary, is dropped. After quality filtering and deduplication, 26,730 integrals survived.

Canonicalization and grouping. Two integrals that differ only in their choice of letters are the same integral. So every integration variable becomes \(x\), free parameters are renamed in alphabetical order as \(a, b, c\) (at most three), and what remains is grouped by the hash of the simplified integrand. That collapsed 23,638 instances into 12,337 distinct groups.

StageExpressions surviving
Raw MSE strings206,328
Parsed and validated integrals26,730
After canonicalization23,638
Unique integrand groups12,337

I do hope to find the time in the future to scale up this database, and create similar databases for sums, products, and special functions.

Model Architecture & Training
#

Transformer Architecture
#

IntegralIndx uses an encoder-only transformer architecture for generating mathematical expression embeddings. The model processes tokenized expressions in prefix notation and produces vector representations via mean pooling. Unlike seq2seq, this architecture directly optimizes for embedding quality through contrastive learning, making it ideal for similarity search tasks.

ComponentSpecification
Encoder Layers6
Hidden Dimension512
Attention Heads8
Feed-Forward Dimension2048
Dropout0.1
Positional EncodingSinusoidal
Pooling StrategyMean
Output Embedding Dimension512
Vocabulary Size62 tokens
Total Parameters18,946,048 (~19M)
Transformer encoder architecture with mean pooling
Figure 2: The encoder. Tokens pass through 6 transformer layers, then mean-pooling collapses them to a single 512-dimensional embedding. (Made with draw.io.)

Contrastive Learning
#

The model is trained using contrastive learning with the InfoNCE loss (temperature = 0.1). This is a self-supervised approach: rather than requiring manual labels, the model learns from equivalence clusters generated via E-Gen. Given a query expression and its positive equivalent, the loss maximizes their cosine similarity while minimizing similarity to negative samples (randomly sampled from other clusters). This forces the encoder to learn representations where mathematically equivalent expressions cluster together in the 512-dimensional embedding space.

Training Data Generation
#

Training data was generated through a three-stage pipeline:

  1. Seed Selection: 1,793 seed expressions were frozen for training:
    • 337 hand-crafted synthetic seeds covering common patterns (polynomials, trig identities, logarithms, etc.)
    • 1,456 expressions extracted from the IntegralIndx database with max token length = 8
    • Token limit ensures E-Gen can generate diverse equivalents without timing out
  2. E-Gen Equivalence Generation: Apply E-Gen to each seed. Of the 1,793 seeds, 1,243 seeds successfully generated equivalents (69.3% success rate), producing an average of 154 equivalents per seed (median: 74). This resulted in 191,394 total equivalent expressions across all clusters. The variability in cluster sizes reflects the mathematical complexity of different expressions: simple expressions often yield larger clusters, while complex expressions may have fewer equivalent forms within the token limit.
  3. TSV Construction: Split seeds 80/10/10 (train/val/test). For each seed, generate all pairwise combinations (query, positive) and sample 3 negatives from other clusters within the same split (clusters with more than 200 equivalents are restricted to 70 positives per query via random sampling to prevent over-representation). The dataset is stored in TSV (tab-separated values) format for efficient loading.
    • Train: 12.68M lines (994 seeds)
    • Validation: 1.59M lines (124 seeds)
    • Test: 1.46M lines (125 seeds)
    • Total: 15.73M training quintuples (query, positive, neg1, neg2, neg3)

Training Procedure
#

The model was trained for 4 epochs over 49 hours on a rented L40S GPU via Vast.ai (totaling $35). The production model uses checkpoint 175,000 (3.5 epochs, 43 hours), as the final checkpoint was accidentally deleted (sigh). Training used the AdamW optimizer with cosine annealing and a 1-epoch warmup schedule. The warmup phase linearly increases the learning rate from 1e-5 to 1e-4, after which the learning rate decays via cosine annealing to a minimum of 1e-6.

HyperparameterValue
OptimizerAdamW (\(\beta_1 = 0.9\), \(\beta_2 = 0.999\), \(\varepsilon = 10^{-8}\))
Learning Rate (max)1e-4
Weight Decay0.01
LR ScheduleCosine Annealing + Linear Warmup
Warmup Epochs1
Min Learning Rate1e-6
Batch Size256
Gradient Clippingmax_norm = 1.0
Loss FunctionInfoNCE
Temperature0.1
Epochs4

Training Results
#

The model converges steadily across 3.5 epochs, with training loss decreasing from 1.18 (initial) to ~0.0015 and validation loss from 0.0131 (end of epoch 1) to ~0.009. Validation loss tracks training loss closely with minimal overfitting, indicating good generalization to unseen equivalence clusters.

Training and validation loss curves over 198k iterations
Figure 3: Training and validation loss curves over ~198k iterations (3.5 epochs). The bump at iteration ~49k corresponds to the warmup schedule transitioning from 1e-5 to 1e-4. Both losses decrease steadily, indicating successful contrastive learning of mathematical equivalence. Validation is evaluated every 10k iterations (marked with orange dots).

FAISS Similarity Search#

Once the transformer model has generated 512-dimensional embeddings for all integrand groups in the database, the next challenge is efficient similarity search: given a query embedding, how do we quickly find the most similar integrands among thousands of candidates? This is where FAISS (Facebook AI Similarity Search) comes in. FAISS is a library developed by Facebook AI Research for efficient similarity search and clustering of dense vectors. It’s optimized for large-scale vector search operations and is widely used in recommendation systems, image retrieval, and natural language processing. FAISS provides both exact and approximate nearest neighbor search algorithms, with support for CPU and GPU acceleration.

IntegralIndx uses IndexFlatIP (Flat Inner Product), which performs exact search using dot product similarity. Note that mathematically, via L2-normalization, dot product similarity is the same as cosine similarity. The flat index guarantees exact nearest neighbors (no false negatives), which naturally requires more compute (a flat index requires \(O(n)\) comparisons), but with our \(n = 12\text{k}\) database this is less than 10ms on a modern CPU. For larger datasets, approximate indexes like IVFFlat or HNSW would be faster.

Search Pipeline
#

One thing to get out of the way first: all that LaTeX machinery was for building the database, not for serving it. A query is entered as a SymPy expression and handed straight to sympify, so the search side never touches LaTeX at all. What it does share with the corpus is everything downstream of that, and that is the part that matters: the same variable normalization, the same prefix notation, the same tokenizer, the same encoder. That is what puts a query and the database in one space.

\[ \begin{aligned} \text{query} &\xrightarrow{\ \texttt{sympify} + \text{validate}\ } e \xrightarrow{\ \text{normalize}\ } \tilde{e} \xrightarrow{\ \text{prefix}\ } (t_1, \ldots, t_n) \\ &\xrightarrow{\ \text{tokenize}\ } (i_1, \ldots, i_n) \xrightarrow{\ E_\theta,\ \text{mean-pool}\ } v \in \mathbb{R}^{512} \xrightarrow{\ v \,/\, \lVert v \rVert\ } \hat{v} \end{aligned} \]

The first arrow parses and rejects: anything SymPy cannot read, anything reaching for a symbol outside the vocabulary, and anything with multi-letter variable names gets turned away with a message rather than silently mangled. The second is the canonicalization from earlier, integration variable renamed to \(x\) and free parameters to \(a, b, c\), so a query written in \(t\) still finds integrands stored in \(x\). The third and fourth flatten the expression tree into prefix notation and look those tokens up in the 62-token vocabulary. The fifth is the encoder \(E_\theta\), mean-pooling its hidden states into a single 512-dimensional vector. The last puts that vector on the unit sphere, which is what makes the inner product FAISS computes a cosine similarity.

FAISS then returns the top-\(k\) nearest integrand groups by inner product against \(\hat{v}\), and those come back with their similarity scores attached.

Closing Thoughts
#

So that’s IntegralIndx. From an idea I had years ago, to a working semantic search engine built on e-graphs and contrastive learning. It’s far from perfect. The database is still small, the normalization pipeline could be more efficient, training could be longer, and I’m certain there are parsing errors lurking in edge cases I haven’t encountered yet. But it does what I wanted: you can type in an integral, and it actually understands what you’re looking for, not just what characters you typed. Whether you’re a student stuck on a homework problem or a researcher hunting for closed forms, I hope this makes finding relevant integrals a little less frustrating than it was for me.

References
#

  1. E-Gen. Zheng, H., Wang, S., Gangwar, N., & Kani, N. (2025). “E-Gen: Leveraging E-Graphs to Improve Continuous Representations of Symbolic Expressions.” NAACL 2025. arXiv:2501.14951 · code (CC BY-NC-SA 4.0) · patent US20240135148A1 (University of Illinois System). This project is built upon the foundational research and implementation provided by the E-Gen team.
  2. MathBERT. Peng, S., Yuan, K., Gao, L., & Tang, Z. (2021). “MathBERT: A Pre-trained Language Model for General NLP Tasks in Mathematics Education.” arXiv:2105.00377
  3. SemEmb. Gangwar, N., & Kani, N. (2023). “Semantic Representations of Mathematical Expressions in a Continuous Vector Space.” TMLR. arXiv:2211.08142
  4. E-graphs (original). Nelson, G., & Oppen, D. C. (1980). “Fast Decision Procedures Based on Congruence Closure.” Journal of the ACM, 27(2), 356–364. doi:10.1145/322186.322198
  5. Equality saturation. Tate, R., Stepp, M., Tatlock, Z., & Lerner, S. (2009). “Equality Saturation: A New Approach to Optimization.” POPL 2009, 264–276. doi:10.1145/1480881.1480915 · PDF. An extended journal version appeared as Logical Methods in Computer Science 7(1) (2011), arXiv:1012.1802.
  6. egg (fast equality saturation). Willsey, M., Nandi, C., Wang, Y. R., Flatt, O., Tatlock, Z., & Panchekha, P. (2021). “egg: Fast and Extensible Equality Saturation.” PACMPL, 5(POPL), 1–29. (Distinguished Paper Award, POPL 2021.) doi:10.1145/3434304 · arXiv:2004.03082 · egraphs-good.github.io

Data source
#

All integral expressions in the dataset are sourced from Math StackExchange. User-contributed content there is licensed under CC BY-SA 4.0. I gratefully acknowledge the MSE community for creating and curating this valuable mathematical content.

License & disclaimer
#

IntegralIndx is licensed under CC BY-NC-SA 4.0. Repository: github.com/noamshh/IntegralIndx.

Non-commercial use only. This is a personal research project for educational purposes. No warranty is provided. Users should independently verify all mathematical expressions and results. The dataset may contain parsing errors or inaccuracies from the source data. Always verify results before relying on them for academic or professional work.


  1. Mostly closed forms for integrals and series. See publications. ↩︎