Zero Labs
Industry News / AI

Building Neumathway: Marrying GNNs with Symbolic Engines for Zero Hallucinations

Source · Towards AI By Christopher Alberto Hamonangan

From the publisher’s feed, collected in the ZeroLabs newsroom.

Building Neumathway: Neuro-Symbolic Math with Zero HallucinationsMade by Christopher Alberto Hamonangan*Neumathway is an experimental, open-source project, and contributions from the community are welcome.GitHub: https://github.com/christopherhamonangan/NeumathwayHugging Face: https://huggingface.co/BhinnekaAI/neumathwork-v1*Research paper in progress. A formal paper documenting the architecture, methodology, and experimental evaluation of Neumathway is currently under development.IntroductionArtificial Intelligence (AI) has become a major force in modern technological development, encompassing fields such as Machine Learning (ML), Computer Vision (CV), and Natural Language Processing (NLP). Within this landscape, Large Language Models (LLMs) have emerged as a significant advancement in the ability of machines to process and generate human language. A major milestone was the introduction of GPT-1 by OpenAI in 2018, which demonstrated the potential of generative pre-training using Transformer-based neural networks. Subsequent developments accelerated the adoption of generative AI, transforming language models from research systems into widely accessible tools for education, software development, scientific research, and other practical applications. However, this progress was not the result of a single model, but rather a series of advances in neural architectures, training methods, computational resources, and data availability.The evolution of modern LLMs has been shaped by several important milestones. The Transformer architecture, introduced in 2017, established attention mechanisms as a foundation for many contemporary language models. GPT-1 and BERT followed in 2018, while GPT-2 and T5 advanced text generation and language understanding in 2019. In 2020, GPT-3 demonstrated the capabilities of large-scale language modeling with 175 billion parameters. The public release of ChatGPT in 2022 expanded access to conversational AI, followed by systems such as GPT-4, Claude, and Gemini in subsequent years. Developments in 2024 and 2025 further emphasized multimodal processing, reasoning capabilities, and more efficient training approaches. Despite their differences, these systems share a common foundation in learning representations from data and using those representations to perform language-related tasks.History of Large Language Models (LLM). Source: https://www.scribbledata.io/At the technical level, an LLM typically processes text through a sequence of numerical transformations. A tokenizer first divides input text into tokens, which are mapped to numerical identifiers and subsequently converted into embedding vectors. Positional information is incorporated to represent token order. These representations are then processed by neural network layers, commonly using a decoder-only Transformer architecture in autoregressive language models. Within each Transformer block, self-attention uses Query, Key, and Value representations to determine how information from preceding tokens contributes to the contextual representation of each position. Feed-forward networks, residual connections, and normalization layers further transform these representations. By stacking multiple blocks, the model learns increasingly complex contextual patterns that support the generation of coherent sequences. Implementation techniques such as Grouped-Query Attention, FlashAttention, and mixed-precision computation can also improve computational or memory efficiency.Internal Architecture of a Transformer. Source: https://deeprevision.github.io/posts/001-transformer/#ref-vaswani2017attentionThe capabilities of an LLM are developed through training, during which model parameters are optimized using large datasets. Generative models commonly employ a next-token prediction objective, learning to estimate the probability distribution of the next token given the preceding context. The resulting loss is used to update model parameters through backpropagation and optimization algorithms such as AdamW. Depending on the model, additional stages may include supervised fine-tuning, preference optimization, or reinforcement learning to improve instruction following and task performance. During inference, the model generates an output by repeatedly predicting and selecting subsequent tokens according to a decoding strategy. This process enables flexible language generation, but it also means that the model’s output depends on learned statistical representations rather than automatically following explicit computational rules. Model architecture, training data, optimization methods, and inference settings all contribute to its resulting capabilities.LLM Training and Pipeline. Source: https://livephysics.com/infographics/cs-how-llms-trained/Today, LLMs support a wide range of applications, including educational assistance, code generation, scientific literature analysis, document processing, and conversational interfaces. Multimodal systems have further extended these capabilities to inputs such as images, audio, and video, while tool integration allows certain models to interact with external software and computational systems. These developments demonstrate the versatility of neural language models and their growing role in modern AI. Understanding their architectures, training procedures, and inference mechanisms provides an important foundation for investigating other computational approaches and specialized AI systems. This broader context establishes the technical background for examining how different model architectures can be designed and evaluated for specific problem domains.MotivationMathematical reasoning is an essential capability in artificial intelligence because it requires more than recognizing patterns or generating plausible sequences of text. Mathematical tasks involve structured expressions, well-defined operators, algebraic relationships, and rules that constrain which transformations are valid. From elementary arithmetic to linear algebra and calculus, a solver must interpret an input, identify the appropriate operation or strategy, and produce a result consistent with mathematical rules. These capabilities are relevant to scientific computing, engineering, education, and automated problem-solving. Consequently, mathematical computation provides an important domain for investigating how AI systems can combine learned representations with structured operations to solve problems reliably.Despite substantial progress in Large Language Models (LLMs), mathematical reasoning remains an active research area. LLMs can solve many mathematical problems through learned patterns, multi-step generation, and tool-assisted reasoning, but their performance does not guarantee consistent correctness across different problem formulations. The GSM-Symbolic study by Mirzadeh et al. (2025), for example, found that model performance could vary when numerical values were changed and could deteriorate when irrelevant clauses were introduced into problems. These findings illustrate why benchmark accuracy alone may not fully characterize the robustness of mathematical reasoning. Moreover, generating a plausible solution and executing a mathematically valid computation are not necessarily equivalent processes. Although external calculators, computer algebra systems, and other tools can improve reliability, they introduce additional design questions concerning tool selection, intermediate representations, and the coordination between learned reasoning and exact computation. (Mirzadeh et al., 2025).Illustration of robustness challenges in language-model-based mathematical reasoning.One potential direction is to combine neural learning with symbolic computation. Neural networks can learn representations from examples, recognize structural patterns, and predict useful operations or strategies without requiring every decision to be manually specified. Symbolic systems, in contrast, manipulate explicit mathematical expressions according to defined rules and can provide exact results for supported operations. For example, a neural component may help identify an appropriate procedure for an equation, while a symbolic engine performs the corresponding algebraic transformation. This division of responsibilities creates an opportunity to combine adaptive decision-making with explicit computational procedures. However, integration is not automatically beneficial: a neural component can select an unsuitable strategy, a symbolic engine may not support every expression, and errors in translating between representations can propagate through the system. Designing an effective neuro-symbolic architecture therefore requires careful coordination between its components rather than simply placing a neural network and a symbolic solver in the same pipeline.Conceptual overview of the complementary roles of neural learning and symbolic computation in mathematical problem-solving. Source: https://allegrograph.com/what-is-neuro-symbolic-ai/A related research opportunity concerns the design of specialized mathematical models. General-purpose LLMs are trained to support a broad range of language tasks, whereas a mathematical solver can be designed around structured numerical and symbolic inputs. Such specialization makes it possible to investigate alternative representations, task-specific prediction mechanisms, and computational pathways without requiring every stage to operate through natural-language generation. A model may, for instance, represent an expression as a structured graph, predict the operator or strategy required at a given step, and delegate supported calculations to an explicit symbolic engine. Nevertheless, specialization should not be assumed to guarantee better performance or lower resource consumption. Its value must be evaluated against appropriate alternatives using consistent datasets, comparable task coverage, and measurements of accuracy, latency, memory consumption, and generalization. This makes computational efficiency and mathematical reliability measurable research objectives rather than presumed advantages.The central research question is therefore not simply whether neural networks and symbolic computation can be combined, since neuro-symbolic systems have already been investigated across multiple domains. Instead, the question is how their components can be organized to support a dedicated mathematical solver across several categories of operations while balancing predictive flexibility, computational correctness, and resource requirements. In particular, it is worth investigating whether structured expression representations, learned operator prediction, strategy selection, and symbolic execution can work together within a unified processing pipeline. A meaningful evaluation must determine where this combination is effective, which types of operations remain difficult, and whether any improvements persist on unseen examples rather than only on familiar training patterns. Establishing this research gap requires comparison with existing mathematical solvers and relevant neural or neuro-symbolic baselines, rather than assuming that the proposed combination is inherently novel. The objective is to identify and test a specific architectural approach whose behavior can be measured and reproduced.Motivated by these questions, this research investigates Neumathway (NMN), a specialized neuro-symbolic system designed to process mathematical expressions and operations. NMN explores the integration of structured expression representations, a relation-aware graph neural network, a recurrent controller, neural operator prediction, a neural matrix computation component, and a symbolic engine for supported calculations. Its design also incorporates strategy selection and a memory mechanism intended to reuse previously established solutions where applicable. Rather than treating the entire problem-solving process as unrestricted text generation, NMN investigates how neural components can help select computational actions while symbolic procedures handle operations covered by their explicit rules. The system is evaluated across multiple mathematical categories, including arithmetic, linear equations, systems of equations, quadratic equations, differentiation, integration, limits, matrix operations, and specialized discrete functions. The experiments examine mathematical accuracy, operator prediction, generalization, inference latency, and memory usage. Through this investigation, NMN aims to provide an empirical case study of how neural learning and symbolic computation can be coordinated in a resource-conscious mathematical solver, with its contributions determined by reproducible results and comparisons against relevant baselines.Conceptual architecture of Neumathway, illustrating the coordination between neural prediction and symbolic computation.Introducing Neumathway (NMN)1. What Is Neumathway?Neumathway (NMN) is an experimental neuro-symbolic AI system designed to explore a different approach to mathematical computation. Instead of treating mathematical problem-solving primarily as a process of generating text, NMN organizes the task around structured mathematical representations, learned computational decisions, and explicit symbolic operations. The central idea is to investigate how neural networks and symbolic computation can work together within a specialized system that processes mathematical expressions.The motivation behind NMN is not simply to build another calculator or reproduce the general capabilities of a large language model. Conventional calculators already perform many numerical operations efficiently, while general-purpose language models can address mathematical questions alongside numerous other tasks. NMN explores a different design question: can a dedicated computational architecture coordinate learned predictions and explicit mathematical procedures across multiple categories of mathematical operations?To investigate this question, NMN combines several components, including a graph-based representation of mathematical expressions, a relation-aware graph neural network, a recurrent controller, neural operator prediction, neural matrix computation, strategy selection, and a symbolic engine for supported operations. These components have different responsibilities, allowing the system to investigate how structural representations, learned decisions, and rule-based computation can be coordinated.NMN should therefore be understood as an ongoing experimental system rather than an established replacement for existing mathematical tools. Its value depends on what its architecture can demonstrate through reproducible experiments, how well it generalizes beyond familiar training examples, and whether its design offers measurable advantages under clearly defined evaluation conditions.2. How Does Neumathway Work?At a conceptual level, NMN processes mathematical expressions through a sequence of structured representations and computational decisions. Consider the expression 12 + 8 × 2. Although it appears simple, solving it correctly requires respecting operator precedence: multiplication must be evaluated before addition, producing the result 28.The process can be understood through the following stages:Expression Representation. The input is converted into a structured graph containing numerical values, operators, and their relationships. NMN uses eight-dimensional node features in its graph representation.Structural Processing. A relation-aware graph neural network processes the graph to learn representations of the mathematical structure.Operation Prediction and Strategy Selection. A recurrent controller with cross-attention supports contextual decision-making. Neural Operator Prediction (NOP) predicts mathematical operations, while the strategy router selects a computational approach.Numerical or Symbolic Computation. Neural Matrix Computation (NMC) provides a learned numerical computation pathway, while the symbolic engine executes operations covered by its explicitly implemented rules.Result Generation. The selected computational pathway produces the output for the given expression.For the example 12 + 8 × 2, a valid symbolic execution is:The table illustrates the mathematical procedure, not a claim that every NMN input follows this exact pathway. The neural and symbolic components have different responsibilities, and the route taken may depend on the operation and the system’s implementation.The central principle is to coordinate learned computational decisions with explicit mathematical procedures wherever applicable. Whether this design improves reliability or efficiency must be established through experimental evaluation.Conceptual workflow of Neumathway, from structured mathematical input to computational output.3. Why Combine Neural Networks with Symbolic Computation?Neural networks and symbolic systems offer different computational properties. Neural networks can learn patterns from examples and use those patterns to make predictions in situations that may not have been explicitly programmed. However, a learned prediction is not automatically equivalent to a mathematically valid operation. A neural component may select an inappropriate operator, produce an inaccurate numerical estimate, or fail when an input differs substantially from the examples encountered during training.Symbolic computation takes a different approach. It manipulates mathematical expressions according to explicit rules. For supported operations, a symbolic engine can perform defined transformations without having to learn those rules from numerical examples. This can provide a more controlled computational pathway, although its reliability still depends on implementation correctness, input parsing, domain restrictions, and the operations it actually supports.NMN explores how these complementary properties can be coordinated. Its neural components are intended to help interpret mathematical structure, predict operations, and select strategies, while the symbolic engine executes supported mathematical procedures. In principle, this arrangement could reduce reliance on unconstrained numerical prediction for operations that can be handled explicitly. However, the benefits depend on whether the neural decisions are appropriate and whether the symbolic engine can execute the selected operations correctly.The combination also introduces its own challenges. Neural predictions and symbolic operations must use compatible representations, and errors at the interface between them can propagate through the computation. Some mathematical problems may require operations outside the symbolic engine’s supported scope, while learned components may behave differently on unseen expressions. Consequently, neuro-symbolic integration is not automatically more accurate or efficient than either approach in isolation. It is an architectural hypothesis that requires careful implementation and empirical evaluation.Conceptual comparison of neural learning and symbolic computation in NMN.4. What Makes NMN Different from a Conventional Calculator or an LLM?NMN explores a specialized approach to mathematical computation. To understand its intended role, it helps to compare its design with conventional calculators and general-purpose large language models (LLMs).This comparison describes general design characteristics rather than universal properties of every system in each category.The main distinction is that NMN investigates how learned decisions can be organized around structured mathematical expressions and coordinated with explicit symbolic operations. Unlike a conventional calculator, it incorporates neural components for predicting operations and computational strategies. Unlike a general-purpose LLM, its architecture is specifically organized around mathematical computation rather than unrestricted language generation.However, these differences do not establish that NMN is more accurate, faster, or more resource-efficient. Such conclusions require controlled comparisons using relevant baselines, equivalent tasks, and clearly documented evaluation conditions.5. What Happens Inside NMN?At a conceptual level, Neumathway organizes mathematical problem-solving around three complementary functions:Structural representation: The input expression is transformed into a structured representation that captures the relationships between mathematical symbols and operations.Neural decision-making: Neural components learn to identify relevant operations, predict computational actions, and guide the problem-solving process.Symbolic computation: A symbolic component executes supported mathematical operations according to explicit rules, helping maintain computational consistency.These functions are intended to work together rather than operate as isolated components. Neural learning provides flexibility in selecting and organizing computational steps, while symbolic computation provides a rule-based mechanism for executing supported operations.Illustration of structured mathematical expression representation in Neumathway.6. What Is NMN Designed to Solve?Neumathway is designed to investigate whether a specialized computational model can solve mathematical expressions through a combination of learned decision-making and explicit mathematical operations.Its intended scope extends beyond basic arithmetic to several categories of mathematical problems, including:Arithmetic: Evaluating expressions involving multiple operations and nested parentheses.Algebra: Solving linear and quadratic equations, as well as systems of equations.Calculus: Handling selected differentiation, integration, and limit problems.Linear algebra: Working with matrices and related operations.Discrete and specialized functions: Evaluating mathematical functions defined by particular rules or conditions.This scope represents the system’s intended problem domains, not a claim that every problem within these categories has been solved reliably. Actual performance depends on the supported operations, training data, implementation, and evaluation procedure.7. What Do We Want to Find Out?The central question behind NMN is whether neural prediction and symbolic computation can be coordinated effectively within a specialized mathematical solver. The investigation considers not only whether the system produces correct answers, but also how its internal computational decisions contribute to those outcomes. Operator prediction, strategy selection, numerical computation, and symbolic execution represent different stages of the process, and each may introduce distinct sources of error.A second question concerns generalization. A model may learn recurring patterns in its training data without developing a reliable approach to unfamiliar expressions. Evaluating NMN therefore requires examining performance on data that was not used to train the model and determining whether the evaluation examples meaningfully differ from the training examples. Category-level results and error analysis can help reveal whether the system handles a broad range of operations or relies heavily on particular patterns.Computational efficiency is another important consideration. A specialized system may be useful in resource-constrained environments if it can provide acceptable mathematical reliability while keeping inference latency and memory consumption manageable. However, these properties must be measured under documented hardware and software conditions. Comparisons are meaningful only when the tested workloads and measurement procedures are sufficiently consistent.Ultimately, NMN is an investigation into a particular architectural approach, not a claim that neuro-symbolic computation has already solved the challenges of mathematical reasoning. Its significance depends on reproducible implementation details, transparent evaluation, and an honest account of both successful results and remaining limitations. With these questions established, the next chapter moves from the conceptual overview to the technical details of NMN’s architecture, training process, and experimental evaluation.Inside Neumathway: Architecture, Training, and Experiments1. Architecture: From Mathematical Expressions to ComputationNeumathway (NMN) is an experimental neuro-symbolic mathematical computation system designed to combine structured mathematical representations, neural decision-making, numerical prediction, and rule-based symbolic execution. Its architecture is intended to address mathematical computation as a structured process rather than treating every problem solely as a sequence of textual tokens. The system brings together several computational components, including a typed expression graph, a relation-aware Graph Attention Network (GAT), a recurrent controller, Neural Operator Prediction (NOP), Neural Matrix Computation (NMC), a soft decision-tree strategy router, a symbolic engine, and Strategy Memory. Each component has a distinct intended role, but the overall behavior depends on how their outputs and intermediate representations interact. Accordingly, NMN should be understood as an integrated computational pipeline rather than simply a collection of neural network modules.Detailed architectural overview of Neumathway, illustrating the flow from mathematical input and graph construction through neural processing, strategy selection, computation, memory retrieval, and output generation. The connections must reflect the actual implementation, including conditional branches and fallback paths.The first stage transforms a mathematical expression into a typed expression graph. Instead of representing an expression only as a flat sequence, this graph captures relationships between mathematical elements through nodes and edges. NMN uses eight-dimensional node features, which provide the initial information associated with individual graph nodes. For example, the expression (12+8x2) must preserve the precedence of multiplication over addition. Its expression tree therefore places addition at the root, with (12) as one operand and multiplication as the other; the multiplication node then connects to (8) and (2). This representation makes the relationships between operators and operands explicit before the neural components process them. For reproducibility, the implementation must specify the meaning and ordering of all eight node features, the supported node types, the edge-relation definitions, the parser’s supported syntax, and the handling of parentheses, negative numbers, and malformed expressions.Transformation of (12+8x2) into a structured expression graph, showing operator precedence, operand relationships, node types, and the corresponding graph connections. Feature labels should be included only if their exact definitions are available in the implementation.def ast_to_matrix_8d(root): nodes, edges = [], [] def traverse(curr, depth=0, is_left=0.0, is_right=0.0, in_lhs=1.0): curr_id = len(nodes) degree = (1.0 if curr.left else 0.0) + (1.0 if curr.right else 0.0) token_id = float(TOKENS[curr.token_type]) is_op = 1.0 if curr.token_type not in ['NUM', 'x', 'y'] else 0.0 norm_val = math.copysign(math.log1p(abs(float(curr.val))), float(curr.val)) if curr.token_type == 'NUM' else 0.0 nodes.append([is_op, token_id, norm_val, float(depth), is_left, is_right, degree, in_lhs]) if curr.left: edges.append((curr_id, traverse(curr.left, depth+1, 1.0, 0.0, in_lhs))) if curr.right: edges.append((curr_id, traverse(curr.right, depth+1, 0.0, 1.0, in_lhs))) return curr_id traverse(root) # ... tensor construction with shape (MAX_NODES, 8)Include a short excerpt from the actual source code showing how a mathematical input is parsed, converted into graph nodes and edges, and assigned its eight-dimensional node features. The excerpt should make the graph construction procedure understandable without reproducing the entire parser. If the feature vector contains categorical or numerical fields, briefly identify the encoding of each field in the surrounding text.Once constructed, the graph is processed by a four-layer relation-aware residual Graph Attention Network. The purpose of this component is to generate contextual node representations by aggregating information from related parts of the mathematical expression. In a general graph-attention formulation, the representation of node (i) at layer (l+1) can be expressed aswhere h_i at layer l represents the hidden state of node i, N(i) denotes its neighborhood, r identifies an edge relation, W_r at layer l denotes a relation-dependent transformation where applicable, and alpha_ij represents the attention weight assigned to information from a neighboring node. This equation is a general explanatory formulation, not a verified transcription of NMN’s exact forward pass. The final technical account should document how edge relations affect attention, how residual connections are implemented, whether multiple attention heads are used, whether normalization or dropout is applied, and how graph-level information is obtained for downstream processing. These details determine the actual computational behavior and should be taken from the implemented graph encoder rather than inferred from the term relation-aware GAT alone.class RelationAwareGAT(nn.Module): def forward(self, h, adj): h_proj = self.W(h).view(B, N, self.num_heads, self.head_dim).transpose(1, 2) attn = self.leaky_relu(torch.matmul(h_proj, self.a_src) + torch.matmul(h_proj, self.a_dst).transpose(-2, -1)) mask = adj.unsqueeze(1).repeat(1, self.num_heads, 1, 1) attn = attn.masked_fill(mask == 0, -1e4) attn_weights = torch.softmax(attn, dim=-1) out = torch.matmul(attn_weights, h_proj).transpose(1, 2).contiguous().view(B, N, D) return self.norm(self.relu(out) + h) # Residual connectionInclude the actual GAT layer definition and the configuration that establishes the four-layer encoder. Show how relation information enters message aggregation, how residual connections are applied, and how the encoder returns its representations. Include the relevant tensor dimensions and any pooling operation used downstream. Do not include unrelated training code.The encoded graph information is then used by NMN’s recurrent decision-making components. The architecture includes a two-layer Gated Recurrent Unit (GRU) controller and a cross-attention mechanism. The GRU maintains a recurrent state across computational steps, while cross-attention allows the controller to incorporate relevant information from another representation, such as encoded graph features. Together, these mechanisms are intended to support sequential decisions based on the expression structure and the current computational context. To describe this process precisely, the implementation must establish what enters the controller at each step, how its hidden state is initialized and updated, which tensors serve as the query and context in cross-attention, and how the resulting representation is passed to the prediction heads. The article should also identify the tensor shapes at these interfaces, because the number of layers alone does not fully specify the controller’s behavior.def forward(self, node_features, adj_matrix, node_mask): h = self.gat4(self.gat3(self.gat2(self.gat1(self.in_proj(node_features), adj_matrix), adj_matrix), adj_matrix), adj_matrix) graph_summary = (h * node_mask.unsqueeze(-1)).sum(dim=1) / node_mask.sum(dim=1).unsqueeze(-1) gru_out, _ = self.controller(graph_summary.unsqueeze(1)) cross_out, _ = self.cross_attn(query=gru_out, key=h, value=h, key_padding_mask=~node_mask) reasoned_state = gru_out + cross_out return reasoned_state # Contextualized reasoning stateInclude the actual two-layer GRU configuration, hidden-state update, cross-attention calculation, and the interface between the controller and the prediction components. Add comments or surrounding prose that identify the relevant tensor dimensions. Do not invent a hidden dimension or attention-head count if it cannot be confirmed from the source code.Two distinct prediction components operate within this broader neural pipeline: Neural Operator Prediction (NOP) and Neural Matrix Computation (NMC). NOP produces predictions over 16 defined action classes, while NMC produces continuous numerical predictions using a signed-log representation. Their outputs therefore have different meanings and should not be treated as interchangeable. NOP’s categorical output represents a choice among the action classes implemented by the model, whereas NMC’s continuous output represents a numerical prediction in its defined output space. A complete technical description must enumerate all 16 NOP classes, explain how each class is interpreted by the execution pipeline, and specify how NMC encodes targets, transforms predictions back to the intended numerical domain, and handles zero or negative values. It should also clarify whether NMC predicts an intermediate value, a final answer, or another numerical quantity in each supported computational path.The NMC training objective uses Smooth L1 loss, according to the stated design. Its general definition iswhere (e) is the difference between the predicted value and its target in the space where the loss is evaluated. If the model is trained against signed-log-transformed targets, the article must explicitly state that the loss is calculated in the transformed space; it should not imply that the loss is necessarily applied directly to the original numerical values. The implementation should also establish how the categorical NOP objective is defined, whether NOP and NMC are trained jointly or separately, and how their losses are combined if a joint objective is used. Those details belong to the actual training implementation and will be examined further in Section 4.2.Functional overview of NMN’s main components. The exact input and output interfaces must be checked against the implementation before publication. In particular, the table should distinguish a model’s predicted action from the actual execution of that action.The soft decision-tree router provides a mechanism for selecting or coordinating computational strategies. Its purpose is to connect the model’s current representation to an appropriate execution path, but the exact routing behavior depends on the implemented decision function and its integration with NOP, NMC, and symbolic execution. A reproducible description must specify the router’s input features, the meaning of its branches or strategy classes, the mathematical operation used to calculate routing decisions, and whether routing remains soft during inference or is converted into a discrete selection. It must also explain what happens when the selected strategy cannot handle an expression. Without these details, describing the component as a soft decision tree identifies its general design but does not establish how it controls the complete system.# NOP Path with Temperature Scalingnop_attn, _ = self.nop_mha(reasoned_state, reasoned_state, reasoned_state)raw_logits = self.nop_head(nop_attn.squeeze(1))calibrated_logits = raw_logits / torch.clamp(self.temperature, 0.1, 2.0)# NMC Pathnmc_attn, _ = self.nmc_mha(reasoned_state, reasoned_state, reasoned_state)norm_val_pred = self.nmc_head(nmc_attn.squeeze(1)).squeeze(-1)# Router Outputroute_weight = self.router(reasoned_state.squeeze(1))Include the actual router definition and the code that connects its output to the relevant computational paths. Show how the routing decision is represented, how the chosen strategy is dispatched, and what fallback behavior exists when a strategy is unavailable or fails. If the router and NOP serve different decision-making purposes, make that distinction explicit.The symbolic engine provides a rule-based mechanism for executing mathematical operations supported by its implementation. For applicable rational arithmetic, NMN uses Python’s Fraction representation, which can preserve exact rational results instead of immediately converting them into floating-point approximations. For example, (1/3+1/6=1/2) can be evaluated exactly when the operands and operation are handled through rational arithmetic. This exactness is limited to operations and domains supported by the symbolic implementation; it does not establish universal correctness for arbitrary equations, calculus expressions, matrices, or other mathematical problems. The technical description should therefore identify which operations are implemented symbolically, how operands are converted and validated, how domain restrictions are enforced, and how unsupported expressions or execution errors are handled. It should also clarify whether symbolic results are returned directly or passed back to the neural controller for additional decisions.@staticmethoddef execute_step(node): l_val, r_val = node.left.val, node.right.val if node.token_type == '+': return True, l_val + r_val, "OK" # Uses Python Fraction if node.token_type == '/': if r_val == 0: return False, None, "ZeroDivisionError" return True, l_val / r_val, "OK" if node.token_type == 'fact': return True, Fraction(math.factorial(int(float(node.left.val))), 1), "OK"Include one representative symbolic execution path from the actual source code. Show how an operation is identified, how supported operands are processed, how a result is produced, and how unsupported or invalid inputs are handled. Use one short example that demonstrates exact rational arithmetic, but do not imply that every operation in the dataset uses Fraction.Strategy Memory provides another potential execution path by retrieving information associated with previously encountered computational strategies. Unlike learned model parameters, which encode patterns in the trained weights, a memory mechanism stores or indexes information that can be retrieved during execution. Its practical role depends on what the implementation stores: a complete answer, an intermediate result, a reusable strategy, or another representation. The article must specify the memory key, the stored information, the matching procedure, the conditions for accepting a retrieval, and the behavior when no sufficiently reliable match is found. It should also explain how retrieved information is checked before being used and whether a successful retrieval bypasses part of the normal neural or symbolic pipeline. These distinctions are necessary to determine whether Strategy Memory is primarily a caching mechanism, a strategy-reuse mechanism, or a combination of the two.def solve_expression_or_equation(model, device, ast_root, beam_width=4, max_steps=12): # 1. Memory Lookup macro_ops = GLOBAL_MEMORY.recall(ast_root) # 2. Matching Mechanism, If a pattern exists, attempt to execute it if macro_ops: print(f"Macro-Operators: {macro_ops}") curr_tree = copy.deepcopy(ast_root) valid_fast_path = True for op_target in macro_ops: # 3. Verify if the cached sequence is still valid for this specific node redexes = find_reducible_nodes(curr_tree) target_node = next((n for n in redexes if n.token_type == op_target), None) if target_node: # 4. Retrieval & Execution: Perform symbolic reduction via truth engine is_valid, result_val, _ = SymbolicVerifier.execute_step(target_node) # 5. Match Acceptance: Proceed only if the symbolic verifier confirms validity if is_valid: curr_tree = reduce_tree_at(curr_tree, target_node, result_val) else: valid_fast_path = False break else: valid_fast_path = False break # Final Verification if valid_fast_path and curr_tree.token_type == 'NUM': return curr_tree.val # 6. Execute Neural Multi-Path Beam Search on cache miss or rejection print("[*] Cache miss or validation failed. Falling back to Neural Multi-Path Beam Search...") beam = [SearchState(copy.deepcopy(ast_root), history=[ast_root.to_string()], cumulative_score=0.0)] # ... (Beam search implementation continues here)Include the actual memory lookup and retrieval procedure, the conditions used to accept a match, and the fallback path for a cache miss or rejected result. If the implementation validates a retrieved result, show the relevant validation step. Do not describe the memory as guaranteeing correctness unless that guarantee is established by the implementation and evaluation.Taken together, these components define NMN’s architecture as a system that represents mathematical structure explicitly, learns contextual representations through graph attention, uses recurrent neural processing to support computational decisions, and provides distinct neural prediction and symbolic execution mechanisms. The router and Strategy Memory can influence which computational path is taken, depending on their implemented behavior. The final output is produced through the system’s actual execution and output-handling logic. To make this architecture reproducible, the implementation accompanying this article should identify the model configuration, the eight node-feature definitions, graph relations, GAT dimensions, GRU and cross-attention interfaces, the complete set of NOP action classes, the NMC transformation, the router’s decision procedure, the symbolic engine’s supported operations, and the Strategy Memory retrieval conditions. The corresponding source excerpts should be selected from the active implementation used to produce the reported checkpoint, rather than from an earlier or experimental version. This section describes the design and implementation; training procedures are discussed in Section 4.2, while measured accuracy, latency, resource consumption, and other experimental outcomes are reserved for Section 4.3.2. Training NMNNeumathway was trained on a dataset containing approximately 8.27 million (only for training dataset) generated mathematical samples, organized into train_shards, with validation samples stored separately in val_shards. The dataset was designed to cover multiple mathematical domains, ranging from elementary arithmetic to selected algebraic, calculus, matrix, and discrete-function operations. This diversity is intended to expose the model to different expression structures and computational patterns rather than limiting its learning to simple numerical calculations.The dataset is divided into nine categories. Specialized and discrete functions account for the largest proportion of samples, followed by linear equations and elementary arithmetic. This distribution is important when interpreting evaluation results because aggregate metrics can be influenced by the relative frequency of each category.Table 2. Approximate distribution of NMN’s training samples. Values are rounded and should be reconciled against the dataset manifest before publication.The training pipeline must be documented in terms of the actual optimization procedure used to produce the reported checkpoint. This includes the optimizer, learning rate, batch size, training duration, gradient-handling strategy, and checkpoint-selection criteria. NOP produces categorical predictions over itqs defined action classes, whereas NMC predicts continuous numerical values. Consequently, their training objectives may differ. NMN’s stated design uses Smooth L1 loss for NMC, but the article should identify the exact NOP loss and explain whether the objectives are optimized jointly, separately, or through a more complex training procedure. The loss calculation must also specify whether numerical targets are represented in the original domain or transformed using the signed-log representation.If evolutionary optimization was used to produce the final checkpoint, its role must be distinguished from gradient-based model training. The reported configuration includes an evolutionary arena with 32 agents and a six-to-one polygenic synthesis mechanism. The article should explain what constitutes an agent, how candidates are evaluated, how selection occurs, and what the synthesis mechanism combines. It should also clarify whether evolution modifies model parameters, selects strategies, optimizes configurations, or operates at another level. These distinctions determine whether evolutionary optimization is part of the model-training process or a separate search procedure.Training workflow showing dataset generation, train-validation separation, neural optimization, any evolutionary optimization stage, checkpoint selection, and final evaluation. The order and connections must match the actual implementation.def train_nmn(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 1. Configuration & Data Loader train_dataset = ShardedMathDataset('data/train_shards') train_loader = DataLoader(train_dataset, batch_size=256, shuffle=False, collate_fn=collate_fn, pin_memory=True) model = NeumathworkModel(in_features=8, hidden_dim=256, num_heads=4, num_classes=16).to(device) loss_module = AdaptiveMultiTaskLoss().to(device) optimizer = torch.optim.AdamW([ {'params': model.parameters(), 'lr': 1e-3, 'weight_decay': 1e-4}, {'params': loss_module.parameters(), 'lr': 1e-3} ]) epochs = 8 total_steps = len(train_loader) * epochs scheduler = get_cosine_warmup_scheduler(optimizer, warmup_steps=len(train_loader), total_steps=total_steps) # 2. Forward Pass & Loss Combination (NOP + NMC via Adaptive Multi-Task Loss) for epoch in range(epochs): model.train() for feat, adj, mask, target_ops, _, norm_vals in train_loader: feat, adj, mask = feat.to(device, non_blocking=True), adj.to(device, non_blocking=True), mask.to(device, non_blocking=True) target_ops, norm_vals = target_ops.to(device, non_blocking=True), norm_vals.to(device, non_blocking=True) optimizer.zero_grad() with torch.amp.autocast('cuda', enabled=True): op_logits, norm_val_pred, _ = model(feat, adj, mask) loss, loss_nop, loss_nmc = loss_module(op_logits, norm_val_pred, target_ops, norm_vals) loss.backward() optimizer.step() scheduler.step() # 3. Checkpoint Selection & Model Saving torch.save(model.state_dict(), 'nmn_checkpoint.pth')Include the implemented optimizer configuration, loss computation, validation loop, and checkpoint-saving criteria. If evolutionary optimization is used, include a separate short excerpt showing candidate evaluation and selection.A critical methodological requirement is to prevent evaluation leakage. Validation samples should not contribute to gradient-based parameter updates or be used to repeatedly tune the model until the reported validation result becomes an implicit training target. The dataset-generation procedure should also be examined for duplicated expressions, equivalent mathematical forms, and related samples that may appear across training and validation partitions. For example, two differently formatted expressions may represent the same underlying computational problem. Such overlap does not automatically invalidate an experiment, but it can make the evaluation easier than testing on genuinely unseen structures.The final training description should therefore report the dataset-generation rules, partitioning method, relevant optimization settings, checkpoint-selection process, and any evolutionary procedures used. These details provide the context needed to interpret the experimental results presented next.3. Experimental ResultsNMN’s experimental evaluation should distinguish four dimensions: categorical prediction, numerical accuracy, symbolic execution reliability, and computational efficiency. These dimensions measure different properties and should not be combined into a single claim of mathematical competence. The results currently reported for NMN are presented below as preliminary measurements that require clearly specified evaluation protocols and reproducible evidence.Preliminary results reported for NMN. These values are not independently verified and must be accompanied by metric definitions, evaluation sample counts, and measurement conditions.The reported 100% NOP top-1 accuracy and macro F1 indicate perfect categorical predictions on the evaluated sample. However, these results must be interpreted in the context of the evaluation size, class distribution, data-splitting methodology, and potential overlap with training samples. Reporting the number of evaluated examples and per-class performance would help establish whether these results reflect generalization beyond familiar mathematical patterns.NMC’s reported median absolute error of 0.0338 measures the median difference between predicted and target numerical values. Its interpretation depends on whether the error is calculated in the original numerical domain or the signed-log-transformed domain. Additional metrics, such as mean absolute error and category-level error distributions, would provide a more complete assessment of numerical accuracy.The reported mean inference latency of 0.0183 milliseconds per step and throughput of 19,459 operations per second also require clearly defined measurement conditions. In particular, the evaluation should specify what constitutes an operation or computational step, the hardware and software configuration, and whether timing includes parsing, neural inference, symbolic execution, and Strategy Memory retrieval. These factors can substantially affect the reported performance.Finally, the symbolic contract pass rate of 96.55%, reasoning-turn reduction of 57.5%, Strategy Memory speedup of 38.5×-85×, and peak RAM usage of 893 MB should each be supported by explicit metric definitions and appropriate baselines. Together, these measurements provide an initial profile of NMN’s predictive performance, execution reliability, and computational efficiency. However, stronger conclusions about generalization or superiority over existing systems require reproducible evaluation and controlled comparisons.def run_deep_rigorous_benchmark(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') val_dataset = ShardedMathDataset('data/val_shards') # Held-out test dataset val_loader = DataLoader(val_dataset, batch_size=512, shuffle=False, collate_fn=collate_fn, pin_memory=True) model = NeumathworkModel(in_features=8, hidden_dim=256, num_heads=4, num_classes=16).to(device) model.load_state_dict(torch.load('nmn_checkpoint.pth', map_location=device)) model.eval() all_targets, all_preds, all_mae, latencies_ms = [], [], [], [] with torch.no_grad(): for feat, adj, mask, target_ops, raw_vals, _ in val_loader: feat, adj, mask = feat.to(device, non_blocking=True), adj.to(device, non_blocking=True), mask.to(device, non_blocking=True) target_ops, raw_vals = target_ops.to(device, non_blocking=True), raw_vals.to(device, non_blocking=True) # Speed Measurement (Latency & Throughput) t0 = time.perf_counter() op_logits, norm_val_pred, _ = model(feat, adj, mask) t1 = time.perf_counter() batch_sz = len(target_ops) latencies_ms.extend([(t1 - t0) * 1000 / batch_sz] * batch_sz) # NOP Metrics Collection preds = torch.argmax(op_logits, dim=-1) all_preds.extend(preds.cpu().numpy()) all_targets.extend(target_ops.cpu().numpy()) # NMC Metrics Collection (Median Absolute Error vs Ground Truth) recon_val = invert_signed_log(norm_val_pred) mae = torch.abs(recon_val - raw_vals) all_mae.extend(mae.cpu().numpy()) # Final Computations targets = np.array(all_targets) preds = np.array(all_preds) mae_arr = np.array(all_mae) nop_exact_accuracy = np.mean(preds == targets) * 100 nmc_median_mae = np.median(mae_arr) mean_latency = np.mean(latencies_ms) throughput = len(val_dataset) / (sum(latencies_ms) / 1000) # Reliability / Success tracking success_cases = np.sum(preds == targets) failure_cases = len(targets) - success_cases print(f"NOP Accuracy: {nop_exact_accuracy:.4f}% | NMC Med-MAE: {nmc_median_mae:.6f}") print(f"Latency: {mean_latency:.4f} ms | Throughput: {throughput:,.2f} problems/sec") print(f"Reliability - Success: {success_cases:,} | Failures: {failure_cases:,}")Include the actual evaluation loop, metric calculations, timing procedure, and resource-measurement logic. The code should show how predictions are compared with reference results and how failed or unsupported cases are counted.For stronger evidence, future experiments should compare NMN against appropriate baselines on identical held-out expressions. These may include a conventional calculator for supported arithmetic, a symbolic mathematics engine for applicable symbolic operations, and a neural baseline for learned action prediction. Each comparison should use equivalent inputs, clearly defined success criteria, and comparable measurement conditions. Ablation experiments should separately evaluate the contributions of the graph encoder, neural controller, symbolic engine, strategy router, and Strategy Memory where technically feasible.Taken together, the reported results provide an initial profile of NMN’s predictive behavior, numerical error, execution characteristics, and resource consumption. They do not, by themselves, establish superiority over existing mathematical systems or reliable generalization across all intended domains. Such conclusions require reproducible benchmarks, held-out evaluation, and clearly documented baselines. These findings and methodological constraints provide the foundation for the limitations and future directions discussed in Section 4.4.4. Limitations and Future DirectionsDespite its initial results, Neumathway remains an experimental system with several limitations that must be addressed before its capabilities can be fully established. Its current performance metrics provide an initial perspective on neural prediction, symbolic execution, and computational efficiency, but further experiments are necessary to determine how reliably the system generalizes to unfamiliar mathematical problems.4.1 Generalization and Dataset CoverageNMN was trained on approximately 8.27 million generated mathematical samples across nine categories. However, dataset size alone does not guarantee that a model can solve previously unseen expressions or unfamiliar combinations of operations. Similar structures may occur across training and evaluation samples, potentially making some predictions easier than genuinely novel problems.Future experiments should evaluate NMN on structurally distinct expressions, more complex combinations of operations, and carefully separated test sets. Performance should also be reported by mathematical category rather than relying exclusively on aggregate metrics. This would help establish whether NMN learns reusable computational patterns or primarily recognizes structures similar to those encountered during training.4.2 Numerical Representation and PrecisionIn its current form, NMN may convert decimal values and mathematical constants, such as π, into their nearest integer representations during processing. This conversion can discard important numerical information, reducing accuracy in calculations that require decimal precision or the preservation of mathematical constants.Consequently, the system’s current capabilities should not be interpreted as covering all forms of numerical computation. Future development should investigate support for decimal values, rational numbers, and symbolic constants, allowing the system to preserve numerical information throughout the computation pipeline and apply rounding only when explicitly required.4.3 Neural Prediction and Symbolic ReliabilityHigh operator-prediction accuracy does not necessarily guarantee that an entire expression will be solved correctly. Errors in parsing, action selection, numerical prediction, or symbolic execution can propagate through subsequent computational steps. Furthermore, the symbolic engine can only reliably execute operations covered by its implemented rules.Future versions should strengthen result verification, improve the handling of unsupported expressions, and evaluate complete problem-solving success rather than measuring individual components in isolation. An explicit failure-handling mechanism would also help prevent uncertain or unsupported results from being presented as verified answers.4.4 Computational Efficiency and BenchmarkingThe reported latency, throughput, memory consumption, and Strategy Memory speedup should be evaluated under clearly documented conditions. Comparisons with conventional calculators, symbolic mathematics engines, and relevant neural baselines would help establish where NMN offers practical advantages and where existing approaches remain more appropriate.Such comparisons should use equivalent workloads and transparent measurement procedures. Ablation studies could additionally isolate the contributions of the graph encoder, neural controller, numerical prediction component, symbolic engine, strategy router, and Strategy Memory. This would help determine whether each component provides a measurable benefit or introduces unnecessary computational overhead.4.5 Future Research DirectionsThe limitations identified above suggest four priorities for subsequent research:Generalization testing: Evaluate NMN on unseen mathematical structures and independently held-out test sets.Numerical precision: Extend numerical representation to support decimal values, rational numbers, and symbolic constants without unnecessary information loss.Architectural ablation: Measure the individual and combined contributions of NMN’s neural and symbolic components.Reproducible benchmarking: Establish transparent comparisons with appropriate baselines using consistent evaluation protocols.Together, these experiments would provide stronger evidence regarding NMN’s reliability, computational efficiency, and practical value.Neumathway should be viewed as an ongoing exploration of how neural prediction and symbolic computation can be coordinated within a specialized mathematical system. Its contribution will depend not only on the reported metrics but also on its ability to demonstrate reliable generalization, numerical accuracy, and measurable advantages under controlled evaluation.Addressing these limitations will provide a stronger foundation for determining NMN’s practical value and its potential contribution to research in neural-symbolic computation.Building Neumathway: Marrying GNNs with Symbolic Engines for Zero Hallucinations was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.