--- license: cc-by-nc-4.0 language: - en - pl - ru tags: - math - algebra - equation-solver - pytorch - onnx - safetensors - gguf - rnn - gru pipeline_tag: feature-extraction ---
# 🤖 Stupid-Equation-Solver ### Solving 1st–4th Degree Polynomials from Raw Text *No CAS. No symbolic engine. Just a neural network that learned algebra from scratch.* [![Params](https://img.shields.io/badge/Params-3.73M-blue.svg)]() [![Hardware](https://img.shields.io/badge/Trained%20on-Intel%20Arc%20A770-0071C5.svg)]() [![OS](https://img.shields.io/badge/OS-Arch%20Linux-1793D1.svg)]() [English](#english) · [Polski](#polski) · [Русский](#russian) ## 📜 License **Weights:** Released under [CC-BY-NC-4.0](https://creativecommons.org/licenses/by-nc/4.0/) for non-commercial use. **Training code & data:** Not publicly available. All rights reserved.
--- ## 🇬🇧 English ### 📖 Description A lightweight neural network that solves algebraic polynomial equations of **1st to 4th degree** (both complete and incomplete) — directly from raw character text. The model infers **real roots without any external CAS or symbolic algebra engine**. It learned polynomial factorization, discriminant calculation, sign switching, and root extraction directly from ASCII strings. > 💡 *Think of it as a tiny neural calculator that reads equations like a human would — and just knows the answer.* ### 🏗️ Architecture & Training | Property | Value | |---|---| | **Architecture** | 2-layer Bidirectional GRU (BiGRU) + Deep MLP regression head | | **Parameters** | `embed_dim=32`, `hidden_dim=384`, `max_roots=4` | | **Dataset** | 1,000,000+ synthetic equations | | **Variable names** | x, y, a, t, z, ... (randomized) | | **Coefficients** | Non-monic scales from −6 to +12 | | **Root range** | [-20, 20] | | **Hardware** | Intel Arc A770 (16GB GDDR6) | | **OS** | Arch Linux | | **Backend** | PyTorch XPU (oneAPI / Level Zero) | | **Loss** | Custom Masked MSE (penalizes only valid real roots) | ### 🎯 Benchmark Results (100 Unseen Test Equations) | Degree | Type | MAE | Notes | |:---:|:---:|:---:|---| | **1** | Linear | **0.33** | Solid | | **2** | Quadratic | **0.27** | Handles irrationals, e.g. 1 − √2 ≈ −0.41 | | **3** | Cubic | **0.60** | Reliable | | **4** | Quartic | **1.17** | Best effort | | — | **Overall** | **~0.69 – 0.75** | | --- ## 🇵🇱 Polski ### 📖 Opis Lekki model neuronowy rozwiązujący równania algebraiczne wielomianowe od **1. do 4. stopnia** (zarówno zupełne, jak i niezupełne) bezpośrednio z surowego tekstu znakowego. Model wyznacza **pierwiastki rzeczywiste bez użycia zewnętrznych silników symbolicznych (CAS)** — uczy się wyznaczania wyróżnika (delty), rozkładu na czynniki, reguły znaków i pierwiastkowania wprost z ciągów znaków ASCII. > 💡 *Wyobraź sobie mały neuronowy kalkulator, który czyta równania jak człowiek — i po prostu zna odpowiedź.* ### 🏗️ Architektura i Trening | Właściwość | Wartość | |---|---| | **Architektura** | 2-warstwowy dwukierunkowy GRU (BiGRU) + głęboka regresyjna głowica MLP | | **Parametry** | `embed_dim=32`, `hidden_dim=384`, `max_roots=4` | | **Zbiór danych** | Ponad 1 000 000 syntetycznych równań | | **Nazwy zmiennych** | x, y, a, t, z, ... (losowe) | | **Współczynniki** | Skala od −6 do +12 | | **Zakres pierwiastków** | [-20, 20] | | **Sprzęt** | Intel Arc A770 (16GB GDDR6) | | **System** | Arch Linux | | **Backend** | PyTorch XPU (oneAPI / Level Zero) | | **Funkcja straty** | Masked MSE (uwzględnia tylko istniejące pierwiastki) | ### 🎯 Wyniki testowe (100 równań) | Stopień | Typ | MAE | Uwagi | |:---:|:---:|:---:|---| | **1** | Liniowe | **0.33** | Stabilnie | | **2** | Kwadratowe | **0.27** | Radzi sobie z niewymiernymi, np. 1 − √2 ≈ −0.41 | | **3** | Sześcienne | **0.60** | Niezawodnie | | **4** | 4. stopnia | **1.17** | Zadowalająco | | — | **Ogólnie** | **~0.69 – 0.75** | | --- ## 🇷🇺 Русский ### 📖 Описание Лёгкая нейросеть, решающая алгебраические полиномиальные уравнения **1–4 степени** (полные и неполные) прямо из сырого текста. Модель находит **действительные корни без сторонних систем компьютерной алгебры (CAS)** — она выучила формулы Виета, дискриминант, смену знаков и извлечение корней напрямую из ASCII-строк. > 💡 *Представьте крошечный нейронный калькулятор, который читает уравнение как человек — и просто знает ответ.* ### 🏗️ Архитектура и обучение | Параметр | Значение | |---|---| | **Архитектура** | 2-слойная двунаправленная GRU (BiGRU) + полносвязная голова MLP | | **Размерности** | `embed_dim=32`, `hidden_dim=384`, `max_roots=4` | | **Датасет** | 1 000 000+ синтетических уравнений | | **Переменные** | x, y, a, t, z, ... (случайные) | | **Коэффициенты** | Немонические, от −6 до +12 | | **Диапазон корней** | [-20, 20] | | **Железо** | Intel Arc A770 (16GB GDDR6) | | **ОС** | Arch Linux | | **Бэкенд** | PyTorch XPU (oneAPI / Level Zero) | | **Функция потерь** | Кастомный Masked MSE (штрафует только за существующие корни) | ### 🎯 Метрики качества (бенчмарк на 100 уравнениях) | Степень | Тип | MAE | Заметки | |:---:|:---:|:---:|---| | **1** | Линейные | **0.33** | Стабильно | | **2** | Квадратные | **0.27** | Справляется с иррациональными, напр. 1 − √2 ≈ −0.41 | | **3** | Кубические | **0.60** | Надёжно | | **4** | 4-й степени | **1.17** | На пределе | | — | **Общая** | **~0.69 – 0.75** | | --- ## 💻 Quick Start ### Install dependencies ```bash pip install onnxruntime numpy ``` ### Solve equations in Python ```python import json import numpy as np import onnxruntime as ort # 1. Load ONNX model and metadata # Исправлено: используем equation_embedded.onnx вместо model.onnx session = ort.InferenceSession("equation_embedded.onnx") with open("config.json", "r", encoding="utf-8") as f: config = json.load(f) vocab = config["vocab"] max_len = config["max_len"] # 2. Inference function def solve(equation: str): equation = equation.strip() if "=" not in equation: equation += " = 0" # Determine polynomial degree if "^4" in equation: deg = 4 elif "^3" in equation: deg = 3 elif "^2" in equation: deg = 2 else: deg = 1 tokens = [vocab.get(ch, 1) for ch in equation] tokens = tokens[:max_len] + [0] * max(0, max_len - len(tokens)) input_data = np.array([tokens], dtype=np.int64) # Run inference (проверь, что имена входов и выходов в ONNX совпадают) preds = session.run(["roots"], {"tokens": input_data})[0][0] return [round(float(r), 2) for r in preds[:deg]] # 3. Test examples print(solve("3x^2 - 4x - 15 = 0")) # -> [2.96, -1.59] (Exact: 3.0, -1.67) print(solve("x^2 - 2x - 1 = 0")) # -> [2.03, -0.41] (Exact: 2.41, -0.41) print(solve("x^2 - 16 = 0")) # -> [3.85, -4.02] (Exact: 4.0, -4.0) print(solve("a^3 - 3a^2 + 2a = 0")) # -> [2.09, 0.84, -0.14] (Exact: 2.0, 1.0, 0.0) ``` --- ⚠️ Limitations · Regression, not symbolic. Outputs are continuous approximations, not exact fractions. Values like 2.96 instead of 3.0 are expected. · Degree cap. Trained exclusively on 1st–4th degree polynomials. Fifth-degree and higher are out of scope for this version. · Real roots only. Complex roots are not modeled. · Root range. Best performance within [-20, 20]. · No repeat roots detection. Multiplicity is not reported — only the value. --- 🚀 Roadmap ☐ v2: Token-classification head for exact integer roots ☐ v2: Variable-length output (no fixed max_roots) ☐ v3: Extend to 5th+ degree polynomials ☐ v3: Complex root support ---
⚡ Part of XIV AI A startup from Poland, building AI models from scratch. License: MIT · Trained on: Intel Arc A770 · Framework: PyTorch XPU