| import torch |
| import torch.nn as nn |
| import gradio as gr |
| import numpy as np |
|
|
| |
| class NeuralAccumulator(nn.Module): |
| def __init__(self, in_features, out_features): |
| super(NeuralAccumulator, self).__init__() |
| self.W_hat = nn.Parameter(torch.Tensor(out_features, in_features)) |
| self.M_hat = nn.Parameter(torch.Tensor(out_features, in_features)) |
| nn.init.kaiming_uniform_(self.W_hat) |
| nn.init.kaiming_uniform_(self.M_hat) |
|
|
| def forward(self, x): |
| |
| W = torch.tanh(self.W_hat) * torch.sigmoid(self.M_hat) |
| return torch.matmul(x, W.t()) |
|
|
| class MathAI(nn.Module): |
| def __init__(self): |
| super(MathAI, self).__init__() |
| |
| self.nac = NeuralAccumulator(2, 1) |
|
|
| def forward(self, x): |
| return self.nac(x) |
|
|
| |
| model = MathAI() |
| with torch.no_grad(): |
| |
| model.nac.W_hat.fill_(2.0) |
| model.nac.M_hat.fill_(2.0) |
|
|
| |
| def ai_calculate(num1, num2, operation): |
| try: |
| |
| x = torch.tensor([[float(num1), float(num2)]], dtype=torch.float32) |
| |
| |
| if operation == "Subtract": |
| with torch.no_grad(): |
| model.nac.W_hat[:, 1] = -2.0 |
| else: |
| with torch.no_grad(): |
| model.nac.W_hat[:, 1] = 2.0 |
| |
| |
| prediction = model(x) |
| result = prediction.item() |
| |
| return f"{result:g}" |
| except Exception as e: |
| return f"Neural Error: {str(e)}" |
|
|
| |
| with gr.Blocks(theme=gr.themes.Monochrome()) as demo: |
| gr.Markdown("# 🧠 True Neural Math Engine") |
| gr.Markdown("This app uses a **Neural Accumulator (NAC)** to process numbers through weighted layers.") |
| |
| with gr.Row(): |
| n1 = gr.Number(label="Input A", value=16667.0001) |
| n2 = gr.Number(label="Input B", value=1.0) |
| |
| op = gr.Radio(["Add", "Subtract"], label="Neural Operation", value="Add") |
| out = gr.Textbox(label="AI Output") |
| |
| btn = gr.Button("Process through Neural Layers") |
| btn.click(ai_calculate, [n1, n2, op], out) |
|
|
| if __name__ == "__main__": |
| demo.launch() |