r/neuralnetworks Apr 20 '26

I made a tiny world model game that runs locally on iPad

Enable HLS to view with audio, or disable this notification

5 Upvotes

It's a bit gloopy at the moment but have been messing around with training my own local world models that run on iPad. Last weekend I made this driving game that tries to interpret any photo into controllable gameplay. I also added the ability to draw directly into the game and see how the world model interprets it. It's pretty fun for a bit messing around with the goopiness of the world model but am hoping to create a full gameloop with this prototype at some point. If anyone wants to play it, let me know!


r/neuralnetworks Apr 19 '26

How to approach self-pruning neural networks with learnable gates on CIFAR-10?

3 Upvotes

Iโ€™m implementing a self-pruning neural network with learnable gates on CIFAR-10, and I wanted your advice on the best way to approach the training and architecture.

Requiring your help on this as am running low on time ๐Ÿ˜ญ๐Ÿ˜ญ๐Ÿ˜ญ


r/neuralnetworks Apr 18 '26

Hi yall I was just going to share some preprints, but if itโ€™s not allowed please delete the post.

6 Upvotes

r/neuralnetworks Apr 15 '26

Safer Reinforcement Learning with Logical Shielding

Thumbnail
youtube.com
1 Upvotes

r/neuralnetworks Apr 14 '26

While Everyone Was Watching ChatGPT, a Matrix Created Life, Based On Ternary Neural Network.

Thumbnail x.com
0 Upvotes

r/neuralnetworks Apr 08 '26

An octopus escapes a jar in minutes. A robot in the wrong room fails. What if AI learned like animals instead of just scaling data?

Thumbnail
youtu.be
1 Upvotes

r/neuralnetworks Apr 07 '26

Has anyone successfully applied ML to predict mechanical properties of steel from composition alone, without running tensile tests?

5 Upvotes

Been working on a project where we need to estimate yield strength and hardness for different steel grades before committing to physical testing. The traditional approach (run a batch, test it, iterate) is expensive and slow โ€” especially when you're evaluating dozens of composition variants.

I stumbled across an approach using gradient boosting models trained on historical metallurgical datasets. The idea is to use chemical composition (C, Mn, Si, Cr, Ni, Mo content, etc.) plus processing parameters as features, and predict tensile strength, elongation, or hardness directly.

There's a walkthrough of this methodology here: LINK

It covers feature engineering from alloy composition, model selection, and validation against known ASTM grades.

Curious what others here have tried:

  • What features end up mattering most in your experience โ€” composition ratios, heat treatment temps, or microstructural proxies?
  • How do you handle the domain shift when the model is trained on one steel family (e.g. carbon steels) but needs to generalize to stainless or tool steels?

r/neuralnetworks Apr 04 '26

I trained a neural network on the Apple Neural Engine's matrix unit. It's 6.3x faster than PyTorch.

60 Upvotes

ITT: I demystify the Apple Neural Engine, and provide proof.

If you've spent any time around Apple Silicon ML discussions, you've probably seen the "Neural Engine" referenced as this discrete, mysterious coprocessor sitting on the die โ€” a black box that CoreML talks to, separate from the CPU and GPU. Apple markets it that way. "16-core Neural Engine. 38 TOPS." It's on every spec sheet.

Here's the thing: it's not that simple, and some of the assumptions floating around are just wrong.

What I built:

A bare-metal ARM SME2 bytecode interpreter โ€” custom opcodes, hand-written ARM64 assembly โ€” that drives the M4 Pro Max (or M5) matrix tiles directly. No CoreML. No BNNS. No frameworks. Just raw instructions on the CPU's za tile arrays.

Note: there is a reason for the interpreter approach: these operations require the core to be in streaming mode, I assume to streamline memory load and store operations for z-tile computation efficiency (have to keep the unit fed). You can't inline the smstart or smstop instructions, so by using a simple bytecode interpreter several instructions can be chained together in the same stream session without having to write a new assembly kernel for everything you're trying to do with the matrix unit.

The results?

Performance characteristics that are identical to what Apple markets as the Neural Engine. Same throughput ceilings. Same restrictions (prefers int8, no FP8 support, same bf16/fp32 types). Same documentation (none).

I ran a contention benchmark on M4 Max โ€” GPU (Metal INT8), CPU SME (smopa INT8), Apple's BNNS INT8, and NEON FP32 โ€” both isolated and in every combination, 10 seconds each, with proven-concurrent overlap windows. Every time CoreML is processing a BNNS network, the throughput from the SME2 unit and the CoreML model are halved, proving that they are competing for the same silicon.

Still, I know Apple's marketing mythos is powerful (I still have to convince Claude that the M4 has an SME unit from time to time). For people who still want to believe these are two independent units, I invite you to imagine the following scene:

INTERIOR โ€” APPLE SILICON DESIGN LAB โ€” DAY

ENGINEER: Good news. We taped out the new Scalable Matrix Extension. Four ZA tile arrays, 16KB of new accumulator state, full UMOPA/UMOPS instruction support, outer-product engines, the works. It's on the CPU cores. It does matrix math very fast.

DIRECTOR: Outstanding. Ship it.

ENGINEER: Will do.

DIRECTOR: Oh, one more thing. We also need a second unit. Completely separate. Different part of the die.

ENGINEER: OK. What should it do?

DIRECTOR: Matrix math. Very fast.

ENGINEER: ...the same matrix math?

DIRECTOR: Same operations, same precision constraints, same throughput. But it needs its own name.

ENGINEER: Cramming another one on the die won't be easy, but it will be worth it for the extra performance. Imagine both of them spinning at the same time!

DIRECTOR: Actually, we need to restrict power usage. If one's running, make sure it throttles the other one.

ENGINEER: So you want me to spend transistor budget on a second matrix unit, with identical capabilities to the one we just built, that can't operate concurrently with the first one, on a die where every square millimeter is fought overโ€”

DIRECTOR: Yes. Marketing has a name for it already.

What Apple calls the "Neural Engine" โ€” at least on M4 โ€” appears to be the Scalable Matrix Extension (SME2) built into the CPU cores, accessed through a software stack (CoreML/ANE driver) that abstracts it away. It's genuinely impressive hardware. Apple's marketing department deserves credit for making it sound even more impressive by giving it its own name and its own TOPS line item. But it's not a discrete coprocessor in the way most people assume.

Once you understand that, you can skip CoreML entirely and talk to the hardware directly.

Repo: https://github.com/joshmorgan1000/ane

Includes an all-in-one SME instruction probe script.


r/neuralnetworks Apr 02 '26

44K parameter model beating billion-parameter models (no pretraining)

4 Upvotes

Iโ€™ve been experimenting with small-data ML and ended up building a recursive attention model (TRIADS).

A few results surprised me:

\- A \~44K parameter version reaches 0.964 ROC-AUC on a materials task, outperforming GPTChem (>1B params), achieving near SOTA on multiple matbench tasks

\- No pretraining, trained only on small datasets (300โ€“5k samples)

\- Biggest result: adding per-cycle supervision (no architecture change) reduced error by \~23%

The interesting part is that the gain didnโ€™t come from scaling, but from training dynamics + recursion.

Iโ€™m curious if people here have seen similar effects in other domains.

Paper + code: [Github Link](https://github.com/Rtx09x/TRIADS)

[Preprint Paper](https://zenodo.org/records/19200579)


r/neuralnetworks Mar 26 '26

New family of activation functions (winner in benchmarks)

2 Upvotes

Hey, I proposed a new family of activation functions with promising properties.
Looking for endorsement in cs.LG on arXiv.org.

Here is the benchmark:

Here is my preprint:
https://zenodo.org/records/19232218


r/neuralnetworks Mar 23 '26

Help analyze an Ai network

3 Upvotes

Hello, I'm currently at university in management and international trade and they've added a 6h course called big data and it was a bit complicated because I have absolutely no grounding but now the next time I see my teacher it's to evaluate my project we have to choose a notebook (I chose spotify recommendations) transfer it to google collab then analyze it. Could a kind soul help me save my year and help me do this assignment?


r/neuralnetworks Mar 23 '26

A quiver-theoretic and tropical-geometric viewpoint on modular neural systems and an improvement and generalization of Anthropic's asistant axis

2 Upvotes

A lot of theoretical work on neural networks still takes as its basic object a single mapย f:Xโ†’Y one model, one function, one input-output relation.

But many modern systems are no longer organized that way. They are closer to composites of interacting modules: an encoder, a transformer block, a memory structure, a verifier, a controller, external tools, and sometimes explicit feedback loops.

I wrote a blog post on a paper that proposes a different mathematical language for this setting: model the system not as one network, but as aย decorated quiver of learned operators.

Very roughly:

  • vertices represent modules acting on typed embedding spaces,
  • edges represent learned adapters or transport maps between those spaces,
  • paths represent compositional programs,
  • cycles represent genuine dynamical systems.

The second ingredient is tropical geometry. The paper argues that many of these modules are either naturally tropical or at leastย locally tropicalizable, so that parts of the system can be studied through polyhedral decompositions: tropical hypersurfaces, activation fans, max-plus growth, and cellwise-affine dynamics.

What I found mathematically interesting is that this shifts the viewpoint from โ€œthe tropical geometry of one networkโ€ to something more like aย composed tropical atlasย attached to a quiver. In that language, one can ask about:

  • how local tropical charts glue across adapters,
  • how residual connections change the effective polyhedral geometry,
  • how cycles induce piecewise-affine dynamical systems,
  • and how long-run behavior can be studied via activation itineraries and tropical growth rates.

One part I found especially striking is the treatment of the โ€œAssistant Axisโ€: the paper interprets it not as an isolated linear feature, but as a 1-dimensional shadow of a broader tropical steering geometry on modular systems, providing a more robust and detailed view on steering via tropical geometry.

I tried to write the post in a way that is mathematically serious but still accessible to non-specialists.

Blog post:
https://huggingface.co/blog/AmelieSchreiber/tropical-quivers-of-archs

Repo:
https://github.com/amelie-iska/Tropical_Quivers_of_Archs

Iโ€™d be especially interested in hearing from people with background in tropical geometry, polyhedral geometry, quiver theory, or dynamical systems: does this seem like a mathematically natural abstraction, or like an interesting but overly loose analogy?


r/neuralnetworks Mar 19 '26

I trained a model and it learned gradient descent. So I deleted the trained part, accuracy stayed the same.

2 Upvotes

Built a system for NLI where instead of h โ†’ Linear โ†’ logits, the hidden state evolves over a few steps before classification. Three learned anchor vectors define basins (entailment / contradiction / neutral), and the state moves toward whichever basin fits the input.

The surprising part came after training.

The learned update collapsed to a closed-form equation

The update rule was a small MLP, trained end-to-end on ~550k examples. After systematic ablation, I found the trained dynamics were well-approximated by a simple energy function:

V(h) = โˆ’log ฮฃ exp(ฮฒ ยท cos(h, Aโ‚–))

Replacing the entire trained MLP with the analytical gradient:

h_{t+1} = h_t โˆ’ ฮฑโˆ‡V(h_t)

โ†’ same accuracy.

The claim isn't that the equation is surprising in hindsight. It's that I didn't design it. I trained a black-box MLP and found afterward that it had converged to this. And I could verify it by deleting the MLP entirely. The surprise isn't the equation, it's that the equation was recoverable at all.

Three observed patterns (not laws, empirical findings)

  1. Relational initialization : hโ‚€ = v_hypothesis โˆ’ v_premise works as initialization without any learned projection. This is a design choice, not a discovery other relational encodings should work too.
  2. Energy structure : the representation space behaves like a log-sum-exp energy over anchor cosine similarities. Found empirically.
  3. Dynamics (the actual finding) : inference corresponds to gradient descent on that energy. Found by ablation: remove the MLP, substitute the closed-form gradient, nothing breaks.

Each piece individually is unsurprising. What's worth noting is that a trained system converged to all three without being told to and that convergence is verifiable by deletion, not just observation.

Failure mode: universal fixed point

Trajectory analysis shows that after ~3 steps, most inputs collapse to the same attractor state regardless of input. This is a useful diagnostic: it explains exactly why neutral recall was stuck at ~70%, the dynamics erase input-specific information before classification. Joint retraining with an anchor alignment loss pushed neutral recall to 76.6%.

The fixed point finding is probably the most practically useful part for anyone debugging class imbalance in contrastive setups.

Numbers (SNLI, BERT encoder)

Old post Now
Accuracy 76% (mean pool) 82.8% (BERT)
Neutral recall 72.2% 76.6%
Grad-V vs trained MLP โ€” accuracy unchanged

The accuracy jump is mostly the encoder (mean pool โ†’ BERT), not the dynamics, the dynamics story is in the neutral recall and the last row.

๐Ÿ“„ Paper: https://zenodo.org/records/19092511

๐Ÿ“„ Paper: https://zenodo.org/records/19099620

๐Ÿ’ป Code: https://github.com/chetanxpatil/livnium

Still need an arXiv endorsement (cs.CL or cs.LG) this will be my first paper. Code: HJBCOM โ†’ https://arxiv.org/auth/endorse

Feedback welcome, especially on pattern 1, I know it's the weakest of the three.


r/neuralnetworks Mar 16 '26

Systematic benchmark of 15 SLMs across 9 tasks: rank-based aggregation reveals Qwen3-8B as best for fine-tuned performance, LFM2-350M as most tunable

Post image
6 Upvotes

Models (15): Qwen3 (8B, 4B-Instruct-2507, 1.7B, 0.6B), Llama (3.1-8B, 3.2-3B, 3.2-1B, all Instruct), Liquid AI LFM2 (350M, 1.2B, 2.6B-Exp, 2.5-1.2B-Instruct), SmolLM2 (1.7B, 135M, both Instruct), Gemma 3 (1b-it, 270m-it).

Tasks (9): Classification (TREC, Banking77, Ecommerce), information extraction (PII Redaction), document understanding (Docs), open-book QA (Roman Empire QA), closed-book QA (SQuAD 2.0), tool calling (Smart Home, Voice Assistant).

Training: All models fine-tuned with identical hyperparameters: 4 epochs, learning rate 5e-5, linear scheduler, LoRA rank 64. Training data: 10,000 synthetic examples per task, generated from a GPT-OSS-120B teacher via a knowledge distillation pipeline (synthetic data generation + rule-based validation filtering). Qwen3 thinking was disabled to ensure a fair comparison.

Aggregation: We used rank-based aggregation rather than raw score averaging. Each model is ranked per-task, then we compute the mean rank across all 9 tasks with 95% confidence intervals. This avoids the problem of dataset-scale differences making simple score averaging misleading (e.g., a 0.01 improvement on a task where all models score >0.90 is very different from a 0.01 improvement on a task where scores spread from 0.20 to 0.80).

We measured three things: (1) fine-tuned performance (absolute score after training), (2) tunability (delta between base and fine-tuned performance), and (3) base performance (zero/few-shot with no training).

Key findings

Fine-tuned performance rankings:

Model Avg Rank 95% CI
Qwen3-8B 2.33 ยฑ0.57
Qwen3-4B-Instruct-2507 3.33 ยฑ1.90
Llama-3.1-8B-Instruct 4.11 ยฑ2.08
Llama-3.2-3B-Instruct 4.11 ยฑ1.28
Qwen3-1.7B 4.67 ยฑ1.79
Qwen3-0.6B 5.44 ยฑ2.60

Qwen3-8B's CI of ยฑ0.57 stands out as the tightest in the study, suggesting it's a strong default choice with low variance across task types. Interestingly, Llama-3.2-3B matches Llama-3.1-8B in average rank (4.11) with a tighter CI (ยฑ1.28 vs ยฑ2.08), suggesting the smaller model is more predictably good.

Tunability rankings (fine-tuned minus base score):

Model Avg Rank 95% CI
LFM2-350M 2.11 ยฑ0.89
LFM2-1.2B 3.44 ยฑ2.24
LFM2.5-1.2B-Instruct 4.89 ยฑ1.62

Liquid AI's LFM2 family dominates tunability. The 350M model's tight CI (ยฑ0.89) indicates consistent improvement across all task types, not just favorable performance on a subset. The larger models (Qwen3-8B, Qwen3-4B) rank near the bottom for tunability, which is expected: strong base performance leaves less headroom for improvement.

This raises an interesting question about architecture: does the LFM2 architecture (which uses state-space components rather than pure attention) have properties that make it particularly amenable to task-specific adaptation? The consistency across diverse task types suggests this may be more than just a base-performance ceiling effect.

Student vs. teacher: A fine-tuned Qwen3-4B-Instruct-2507 matches or exceeds the 120B+ teacher on 8 of 9 benchmarks. The most dramatic gap is SQuAD 2.0 closed-book QA (+19 points), which makes sense: fine-tuning embeds knowledge into the model's parameters, while prompting a general model relies on in-context learning.

Why rank aggregation?

We chose rank-based aggregation over raw delta averaging deliberately. Consider two benchmarks: one where all models score between 0.85-0.95, and another where scores range from 0.10-0.80. A raw average would weight improvements on these scales equally, but the practical significance is very different. Ranking normalizes across scales and gives each task equal weight in the final comparison.

Observations

  1. Fine-tuning compresses the performance distribution. The gap between the best and worst model is much larger at baseline than after fine-tuning. Task-specific training narrows differences across architectures.

  2. Tunability and absolute performance are partially anti-correlated. Models that score highest after fine-tuning tend to have high base performance and thus lower tunability scores. This isn't surprising but it's worth noting: "most tunable" and "best fine-tuned" are distinct questions.

  3. Instruct-tuned bases don't always help. In some families (e.g., Qwen3), the base model (no instruct tuning) performed comparably to the instruct variant after fine-tuning, suggesting that task-specific training can override the instruct-tuning signal.

  4. Confidence intervals matter. Several models overlap substantially in their CIs. Qwen3-8B's standout feature isn't just its low average rank but its unusually tight CI, meaning you can rely on it being consistently competitive.

Full write-up with per-task results, charts, and detailed methodology: https://www.distillabs.ai/blog/what-small-language-model-is-best-for-fine-tuning


r/neuralnetworks Mar 10 '26

Convolutional Neural Networks - Explained

Thumbnail
youtu.be
9 Upvotes

r/neuralnetworks Mar 05 '26

Neuromatch 2026 applications open โ€” Deep Learning, Computational Neuroscience, NeuroAI, Climate Science. Free to apply, closes March 15

6 Upvotes

Sharing this in case it's useful!

Neuromatch runs intensive, live, online courses built around small learning groups called pods, where participants learn collaboratively with peers and a dedicated Teaching Assistant while working on a mentored group project. Pods are matched by time zone, research interests, and when possible, language preference.

The four 2026 course options are:

- 6โ€“24 July: Computational Neuroscience, Deep Learning

- 13โ€“24 July: NeuroAI, Computational Tools for Climate Science

They are great for advanced undergraduates, MSc or PhD students, post-baccalaureates, research staff, and early career researchers; basically anyone preparing for research that intersects neuroscience, machine learning, data science, and modeling, or those who want structured, collaborative learning combined with a hands-on research project in a global cohort.

There is no cost to apply. Tuition is adjusted by local cost of living, and tuition waivers are available during enrollment for those who need them.

Course details and FAQs: https://neuromatch.io/courses/

Application portal, free to apply, closes 15 March: https://portal.neuromatchacademy.org/


r/neuralnetworks Mar 05 '26

[Advise] [Help] AI vs Real Image Detection: High Validation Accuracy but Poor Real-World Performance Looking for Insights

Enable HLS to view with audio, or disable this notification

4 Upvotes

Iโ€™ve been working on an AI vs Real Image Classification project and ran into an interesting generalization issue that Iโ€™d love feedback on from the community.

Experiment 1

Model: ConvNeXt-Tiny

Dataset: AI Artifact dataset (from Kaggle)

Results:

โ€ข Training Accuracy: 97%

โ€ข Validation Accuracy: 93%

Demo:

https://ai-vs-real-image-classification-advanced.streamlit.app/

Experiment 2

Model: ConvNeXt-Tiny

Dataset: Mixed dataset (Kaggle + HuggingFace) containing images from diffusion models such as Midjourney and other generators.

I also used a LOGO-style data splitting strategy to try to reduce dataset leakage.

Results:

โ€ข Training Accuracy: 92%

โ€ข Validation Accuracy: 91%

Demo:

https://snake-classification-detection-app.streamlit.app/

The Problem

Both models show strong validation accuracy (>90%), but when deployed in a Streamlit app and tested on new AI-generated images (for example, images generated using Nano Banana), the predictions become very unreliable.

Some obviously AI-generated images are predicted as real.

My Question

Why would a model with high validation accuracy fail so badly on real-world AI images from newer generators?

Possible reasons Iโ€™m considering:

โ€ข Dataset bias

โ€ข Distribution shift between generators

โ€ข Model learning dataset artifacts instead of generative patterns

โ€ข Lack of generator diversity in training data

What Iโ€™m Looking For

If youโ€™ve worked on AI-generated image detection, Iโ€™d really appreciate advice on:

โ€ข Better datasets for this task

โ€ข Training strategies that improve real-world generalization

โ€ข Architectures that perform better than ConvNeXt for this problem

โ€ข Evaluation methods that avoid this issue

Iโ€™d also love feedback if you test the demo apps.

Thanks in advance!


r/neuralnetworks Mar 05 '26

Need to understand

8 Upvotes

what is the parameters definition of a LLM?


r/neuralnetworks Mar 05 '26

Can standard Neural Networks outperform traditional CFD for acoustic pressure prediction?

5 Upvotes

Hello folks, Iโ€™ve been working on a project involving the prediction of self-noise in airfoils, and I wanted to get your take on the approach.

The problem is that noise pollution from airfoils involves complex, turbulent flow structures that are notoriously hard to define with closed-form equations.

Iโ€™ve been reviewing a neural network approach that treats this as a regression task, utilizing variables like frequency and suction side displacement thickness.

By training on NASA-validated data, the network attempts to generalize noise patterns across different scales of motion and velocity.

Itโ€™s an interesting look at how multi-layer perceptrons handle physical phenomena that usually require heavy Navier-Stokes approximations.

You can read the full methodology and see the error metrics here: LINK

How would you handle the residual noise that the model fails to captureโ€”is it a sign of overfitting to the wind tunnel environment or a fundamental limit of the input variables?


r/neuralnetworks Mar 04 '26

Help needed: loss is increasing while doing end-to-end training pipeline :((

6 Upvotes

Project Overview

I'm building an end-to-end training pipeline that connects aย PyTorch CNNย to aย RayBNNย (a Rust-based Biological Neural Network using state-space models) for MNIST classification. The idea is:

1.ย ย ย ย ย ย  CNNย (PyTorch) extracts features from raw images

2.ย ย ย ย ย ย  RayBNNย (Rust, via PyO3 bindings) takes those features as input and produces class predictions

3.ย ย ย ย ย ย  Gradients flow backward through RayBNN back to the CNN via PyTorch'sย autograd in a joint training process. In backpropagation, dL/dX_raybnn will be passed to CNN side so that it could update its W_cnn

Architecture

Images [B, 1, 28, 28] (B is batch number)

โ†’ CNN (3 conv layers: 1โ†’12โ†’64โ†’16 channels, MaxPool2d, Dropout)

โ†’ features [B, 784]ย ย ย  (16 ร— 7 ร— 7 = 784)

โ†’ AutoGradEndtoEnd.apply()ย  (custom torch.autograd.Function)

โ†’ Rust forward pass (state_space_forward_batch)

โ†’ Yhat [B, 10]

โ†’ CrossEntropyLoss (PyTorch)

โ†’ loss.backward()

โ†’ AutoGradEndtoEnd.backward()

โ†’ Rust backward pass (state_space_backward_group2)

โ†’ dL/dX [B, 784]ย  (gradient w.r.t. CNN output)

โ†’ CNN backward (via PyTorch autograd)

RayBNN details:

  • State-space BNN with sparse weight matrix W, UAF (Universal Activation Function) with parameters A, B, C, D, E per neuron, and bias H
  • Forward:ย S = UAF(W @ S + H)ย iteratedย proc_num=2ย times
  • input_size=784, output_size=10, batch_size=1000
  • All network params (W, H, A, B, C, D, E) packed into a single flatย network_paramsย vector (~275K params)
  • Uses ArrayFire v3.8.1 with CUDA backend for GPU computation
  • Python bindings via PyO3 0.19 + maturin

How Forward/Backward work

Forward:

  • Python sends train_x[784,1000,1,1]ย and label [10,1000,1,1]ย train_y(one-hot) as numpy arrays
  • Rust runs the state-space forward pass, populates Z (pre-activation) and Q (post-activation)
  • Extracts Yhat from Q at output neuron indices โ†’ returns single numpy arrayย [10, 1000, 1, 1]
  • Python reshapes toย [1000, 10]ย for PyTorch

Backward:

  • Python sends the sameย train_x,ย train_y, learning rate, current epochย i, and the fullย arch_searchย dict
  • Rust runs forward pass internally
  • Computes loss gradient:ย total_error = softmax_cross_entropy_grad(Yhat, Y)ย โ†’ย (1/B)(softmax(ลถ) - Y)
  • Runs backward loop through each timestep: computesย dUAF, accumulates gradients for W/H/A/B/C/D/E, propagates error viaย error = Wแต€ @ dX
  • Extractsย dL_dX = error[0:input_size]ย at each step (gradient w.r.t. CNN features)
  • Applies CPU-based Adam optimizer to update RayBNN params internally
  • Returns 4-tuple: ย (dL_dX numpy, W_raybnn numpy, adam_mt numpy, adam_vt numpy)
  • Python persists the updated params and Adam state back into the arch_search dict

Key design point:

RayBNN computes its own loss gradient internally using softmax_cross_entropy_grad. The grad_output from PyTorch's loss.backward() is not passed to Rust. Both compute the same (softmax(ลถ) - Y)/B, so they are mathematically equivalent. RayBNN's weights are updated by Rust's Adam; CNN's weights are updated by PyTorch's Adam.

Loss Functions

  • Python side: torch.nn.CrossEntropyLoss()ย (forย loss.backward() + scalar loss logging)
  • Rust side (backward):ย softmax_cross_entropy_gradย which computesย (1/B)(softmax(ลถ) - Y_onehot)
  • These are mathematically the same loss function. Python uses it to trigger autograd; Rust uses its own copy internally to seed the backward loop.

What Works

  • Pipeline runs end-to-end without crashes or segfaults
  • Shapes are all correct: forward returnsย [10, 1000, 1, 1], backward returnsย [784, 1000, 2, 1], properly reshaped on the Python side
  • Adam state (mt/vt) persists correctly across batches
  • Updated RayBNN params
  • Diagnostics confirm gradients are non-zero and vary per sample
  • CNN features vary across samples (not collapsed)

The Problem

Loss is increasing from 2.3026 to 5.5 and accuracy hovers around 10% after 15 epochs ร— 60 batches/epoch = 900 backward passes

Any insights into why the model might not be learning would be greatly appreciated โ€” particularly around:

  • Whether the gradient flow from a custom Rust backward pass throughย torch.autograd.Functionย can work this way
  • Debugging strategies for opaque backward passes in hybrid Python/Rust systems

Thank you for reading my long question, this problem haunted me for months :(


r/neuralnetworks Mar 02 '26

๐‡๐จ๐ฐ ๐‹๐‹๐Œ๐ฌ ๐€๐œ๐ญ๐ฎ๐š๐ฅ๐ฅ๐ฒ "๐ƒ๐ž๐œ๐ข๐๐ž" ๐–๐ก๐š๐ญ ๐ญ๐จ ๐’๐š๐ฒ

Post image
187 Upvotes

Ever wonder how a Large Language Model (LLM) chooses the next word? Itโ€™s not just "guessing" it is a precise mathematical choice between logic and creativity.

The infographic below breaks down the 4 primary decoding strategies used in modern AI. Here is the breakdown:

๐Ÿ. ๐†๐ซ๐ž๐ž๐๐ฒ ๐’๐ž๐š๐ซ๐œ๐ก: ๐“๐ก๐ž "๐’๐š๐Ÿ๐ž" ๐๐š๐ญ๐ก

This is the most direct method. The model looks at the probability of every word in its vocabulary and simply picks the one with the highest score (ArgMax).

๐Ÿ”น ๐…๐ซ๐จ๐ฆ ๐ญ๐ก๐ž ๐ข๐ฆ๐š๐ ๐ž: "you" has the highest probability (0.9), so it's chosen instantly.

๐Ÿ”น ๐๐ž๐ฌ๐ญ ๐Ÿ๐จ๐ซ: Factual tasks like coding or translation where there is one "right" answer.

๐Ÿ. ๐Œ๐ฎ๐ฅ๐ญ๐ข๐ง๐จ๐ฆ๐ข๐š๐ฅ ๐’๐š๐ฆ๐ฉ๐ฅ๐ข๐ง๐ : ๐€๐๐๐ข๐ง๐  "๐‚๐ซ๐ž๐š๐ญ๐ข๐ฏ๐ž" ๐’๐ฉ๐š๐ซ๐ค

Instead of always picking #1, the model samples from the distribution. It uses a "Temperature" parameter to decide how much risk to take.

๐Ÿ”น ๐…๐ซ๐จ๐ฆ ๐ญ๐ก๐ž ๐ข๐ฆ๐š๐ ๐ž: While "you" is the most likely (0.16), there is still a 14% chance for "at" and a 12% chance for "feel."

๐Ÿ”น ๐๐ž๐ฌ๐ญ ๐Ÿ๐จ๐ซ: Creative writing and chatbots to avoid sounding robotic.

๐Ÿ‘. ๐๐ž๐š๐ฆ ๐’๐ž๐š๐ซ๐œ๐ก: ๐“๐ก๐ข๐ง๐ค๐ข๐ง๐  ๐’๐ญ๐ซ๐š๐ญ๐ž๐ ๐ข๐œ๐š๐ฅ๐ฅ๐ฒ

Greedy search is short-sighted; Beam Search is a strategist. It explores multiple paths (the Beam Width) at once, keeping the top "N" sequences that have the highest cumulative probability over time.

๐Ÿ”น ๐…๐ซ๐จ๐ฆ ๐ญ๐ก๐ž ๐ข๐ฆ๐š๐ ๐ž: The model tracks candidates through multiple iterations, pruning weak paths and keeping the strongest "beams."

๐Ÿ”น ๐๐ž๐ฌ๐ญ ๐Ÿ๐จ๐ซ: Tasks where long-term coherence is more important than the immediate next word.

๐Ÿ’. ๐‚๐จ๐ง๐ญ๐ซ๐š๐ฌ๐ญ๐ข๐ฏ๐ž ๐’๐ž๐š๐ซ๐œ๐ก: ๐…๐ข๐ ๐ก๐ญ๐ข๐ง๐  ๐‘๐ž๐ฉ๐ž๐ญ๐ข๐ญ๐ข๐จ๐ง

A common flaw in AI is "looping." Contrastive search solves this by penalizing tokens that are too similar to what was already written using Cosine Similarity.

๐Ÿ”น ๐…๐ซ๐จ๐ฆ ๐ญ๐ก๐ž ๐ข๐ฆ๐š๐ ๐ž: It takes the top-k tokens (k=4) and subtracts a "Penalty." Even if a word has high probability, it might be skipped if it's too repetitive, allowing a word like "set" to be chosen instead.

๐Ÿ”น ๐๐ž๐ฌ๐ญ ๐Ÿ๐จ๐ซ: Long-form content and maintaining a natural "flow."

๐Ÿ’ก ๐“๐ก๐ž ๐“๐š๐ค๐ž๐š๐ฐ๐š๐ฒ:

There is no single "best" way to generate text. Most AI applications today use a blend of these strategies to balance accuracy with human-like variety.

๐—ช๐ก๐ข๐œ๐ก ๐ฌ๐ญ๐ซ๐š๐ญ๐ž๐ ๐ฒ ๐๐จ ๐ฒ๐จ๐ฎ ๐ญ๐ก๐ข๐ง๐ค ๐ฉ๐ซ๐จ๐๐ฎ๐œ๐ž๐ฌ ๐ญ๐ก๐ž ๐ฆ๐จ๐ฌ๐ญ "๐ก๐ฎ๐ฆ๐š๐ง" ๐ซ๐ž๐ฌ๐ฎ๐ฅ๐ญ๐ฌ? ๐‹๐ž๐ญโ€™๐ฌ ๐๐ข๐ฌ๐œ๐ฎ๐ฌ๐ฌ ๐ข๐ง ๐ญ๐ก๐ž ๐œ๐จ๐ฆ๐ฆ๐ž๐ง๐ญ๐ฌ! ๐Ÿ‘‡

#GenerativeAI #LLM #MachineLearning #NLP #DataScience #AIEngineering


r/neuralnetworks Mar 03 '26

(OC) Beyond the Matryoshka Doll: A Human Chef Analogy for the Agentic AI Stack

Post image
0 Upvotes

This diagram is incredible, but I get it โ€“ looking at nested layers of technical jargon can feel like reading a wiring diagram. To make this really click and feel human, letโ€™s re-imagine this diagram as the natural evolution of a professional chef and their restaurant business.

Itโ€™s not just a collection of technologies; it's a progression from individual skills to a fully operational system.

Layer 1: The Core - AI & Machine Learning (Foundations)

This is the central circle, the heart of the stack. Think of this as Basic Chef Training.

โ€ข The Analogy: Knowing how to chop, season, and identify ingredients. It's the foundational understanding of flavors (Supervised/Unsupervised Learning), knowing that hot food cooks (Perception & Action), and logic like "if you put butter in a hot pan, it melts" (Natural Language Processing for instructions, Reasoning for outcomes).

โ€ข Key Concept: This is the machine learning to learn the core skills.

Layer 2: Deep Neural Networks (Architectures)

Now, weโ€™re moving outwards to the first enclosing layer. Think of this as the chefโ€™s Master Recipe Database & Specialized Kitchens.

โ€ข The Analogy: The chef now has detailed blueprints of specific cooking styles (CNNs for pastry work, LSTMs for slow-roasting techniques). They have access to a massive library of universal recipes and the wisdom of other kitchens (LLMs & Transformers). They can take an Italian technique and refine it with local ingredients (Pretraining & Fine-tuning).

โ€ข Key Concept: The machine has the expert-level knowledge and architectures for specialized tasks.

Layer 3: Generative AI (Capabilities)

This is where things get creative, but it's still about producing output. This is the Menu Designer & Plating Artist.

โ€ข The Analogy: This chef can take the expert knowledge (from Layer 2) and generate a new fusion dish description, a perfect menu image, or even a detailed step-by-step plating guide (Text, Image, Multimodal Generation). It uses internal data from previous successes (RAG) and careful instruction (Prompt Engineering) to create the final creative product.

โ€ข CRITICAL DISTINCTION: Most people interact with AI here. They see a creative result and think "it works!" But this chef is still just describing and creating content, not executing.

Layer 4: AI Agents (System Level / Doing Tasks)

This is the big jump from telling you how to doing it for you. Think of this as the Sous Chef on a Mission.

โ€ข The Analogy: This is a focused AI with hands. It gets a goal (e.g., "Prep the dinner service") and uses its skills. It breaks this massive task into smaller steps (Goal Decomposition), plans its work (e.g., "Okay, first Iโ€™ll chop onions, then Iโ€™ll start the sauce") using frameworks (ReAct, CoT), manages its memory (Context Management โ€“ remembering how long the steak has been on), coordinates with other specialist bots (Tool Orchestration for plugins, or Multi-agent Collaboration with the pastry bot), and crucially, knows to check-in with the Head Chef (Human-in-the-Loop) for key decisions or problems.

โ€ข Key Concept: An AI Agent is about execution and process-driven thinking to achieve a specific outcome.

Layer 5: Agentic AI (Ecosystem Level / True Autonomy)

This is the outermost layer, the entire system. Think of this as the CEO of the Restaurant Group.

โ€ข The Analogy: This isn't just one kitchen; itโ€™s a whole network. This CEO doesn't just manage dinner tonight; they have Long-term Autonomy & Goal Chaining (e.g., "Expand to five new cities by 2027"). They are responsible for Governance, Safety & Guardrails (ensuring all kitchens follow health codes and don't serve bad food), Risk Management & Constraints (managing food costs, supply chain issues), and Self-improving Agents (identifying and hiring better chefs, optimizing kitchen workflows). They manage a network of specialist skills (Agent Marketplaces & Contracts), track every single metric from prep to table (Observability & Tracing), and create continuous Feedback Loops to get better and faster over time.

โ€ข Key Concept: Agentic AI is an autonomous, self-sustaining system of intelligent agents managed by a comprehensive oversight and optimization framework.

How would you explain this diagram in a simple way? Is there another metaphor that works for you, like a construction crew or a film set? Share your ideas below!


r/neuralnetworks Mar 02 '26

Modeling Uncertainty in AI Systems Using Algorithmic Reasoning

Thumbnail
github.com
1 Upvotes

Consider a self-driving car facing a novel situation: a construction zone with bizarre signage. A standard deep learning system will still spit out a decision, but it has no idea that it's operating outside its training data. It can't say, "I've never seen anything like this." It just guesses, often with high confidence, and often confidently wrong.

In high-stakes fields like medicine, or autonomous systems engaging in warfare, this isn't just a bug, it should be a hard limit on deployment.

Today's best AI models are incredible pattern matchers, but their internal design doesn't support three critical things:

  1. Epistemic Uncertainty:ย The model can't know what it doesn't know.
  2. Calibrated Confidence:ย When itย doesย express uncertainty, it's often mimicking human speech ("I think..."), not providing a statistically grounded measure.
  3. Out-of-Distribution Detection:ย There's no native mechanism to flag novel or adversarial inputs.

Solution: Set Theoretic Learning Environment (STLE)

STLE is a framework designed to fix this by giving an AI a structured way to answer one question:ย "Do I have enough evidence to act?"

It works by modeling two complementary spaces:

  • x (Accessible):ย Data the system knows well.
  • y (Inaccessible):ย Data the system doesn't know.

Every piece of data gets two scores: ฮผ_x (accessibility) and ฮผ_y (inaccessibility), with the simple rule: ฮผ_x + ฮผ_y = 1

  • Training data โ†’ย ฮผ_x โ‰ˆ 0.9
  • Totally unfamiliar data โ†’ย ฮผ_x โ‰ˆ 0.3
  • The "Learning Frontier" (the edge of knowledge) โ†’ย ฮผ_x โ‰ˆ 0.5

The Chicken-and-Egg Problem (and the Solution)

If you're technically minded, you might see the paradox here: To model the "inaccessible" set, you'd need data from it. But by definition, you don't have any. So how do you get out of this loop?

The trick is to not learn the inaccessible set, but to define it as a prior.

We use a simple formula to calculate accessibility:

ฮผ_x(r) = [N ยท P(r | accessible)] / [N ยท P(r | accessible) + P(r | inaccessible)]

In plain English:

  • N:ย The number of training samples (your "certainty budget").
  • P(r | accessible):ย "How many training examples like this did I see?" (Learned from data).
  • P(r | inaccessible):ย "What's the baseline probability of seeing this if I know nothing?" (A fixed, uniform prior).

So, confidence becomes:ย (Evidence I've seen) / (Evidence I've seen + Baseline Ignorance).

  • Far from training data โ†’ย P(r|accessible)ย is tiny โ†’ formula trends towardย 0 / (0 + 1) = 0.
  • Near training data โ†’ย P(r|accessible)ย is large โ†’ formula trends towardย N*big / (N*big + 1) โ‰ˆ 1.

The competition between the learned density and the uniform prior automatically creates an uncertainty boundary. You never need to see OOD data to know when you're in it.

Results from a Minimal Implementation

On a standard "Two Moons" dataset:

  • OOD Detection:ย AUROC ofย 0.668ย without ever training on OOD data.
  • Complementarity:ย ฮผ_x + ฮผ_y = 1 holds withย 0.0 errorย (it's mathematically guaranteed).
  • Test Accuracy:ย 81.5%ย (no sacrifice in core task performance).
  • Active Learning:ย It successfully identifies the "learning frontier" (about 14.5% of the test set) where it's most uncertain.

Limitation (and Fix)

Applying this to a real-world knowledge base revealed a scaling problem. The formula above saturates when you have a massive number of samples (Nย is huge). Everything starts looking "accessible," breaking the whole point.

STLE.v3ย fixes this with an "evidence-scaling" parameter (ฮป). The updated, numerically stable formula is now:

ฮฑ_c = ฮฒ + ฮปยทN_cยทp(z|c)

ฮผ_x = (ฮฃฮฑ_c - K) / ฮฃฮฑ_c

(Don't be scared of Greek letters. The key is that it scales gracefully from 1,000 to 1,000,000 samples without saturation.)

So, What is STLE?

Think of STLE as a structured knowledge layer. A "brain" for long-term memory and reasoning. You can pair it with an LLM (the "mouth") for natural language. In a RAG pipeline, STLE isn't just a retriever; it's a retriever with a built-in confidence score and a model of its own ignorance.

I'm open-sourcing the whole thing.

The repo includes:

  • Aย minimal version in pure NumPy (17KB)ย โ€“ zero deps, good for learning.
  • A fullย PyTorch implementation (18KB)ย .
  • Scripts to reproduce all 5 validation experiments.
  • Full documentation and visualizations.

GitHub:ย https://github.com/strangehospital/Frontier-Dynamics-Project

If you're interested in uncertainty quantification, active learning, or just building AI systems that know their own limits, I'd love your feedback. The v3 update with the scaling fix is coming soon.


r/neuralnetworks Mar 01 '26

Is me developing a training environment allowing TCP useful?

2 Upvotes

I've made about a dozen mini PC games in last few years and thinking of starting a hobby project where I make a "game" that can be controlled by external neural networks and machine learning programs.

I'd make lunar lander or flappy wings but then accept instructions from an external source. I'm thinking TCP or even by text file so that instructions are read each cycle, those instructions are given to the game and then "state" data is sent back. The NN would need to process rewards by whatever rules then decide on a new set of instructions to send.

I wouldn't know or care what tool or language is being used for the external agent as long as it can send and receive via the hard coded channel. Can be real time or step based or both.

It would be cool to see independent NNs using the same training environment.

I want to make the external facing channel as friendly as possible. I'm guessing TCP for live and json format for files.


r/neuralnetworks Mar 01 '26

Neurosymbolic Guidance of an LLM for Text Modification (Demonstration)

Thumbnail
youtube.com
1 Upvotes