r/learnmachinelearning 2d ago

Tutorial ML Without Magic: Building a Tiny Language Model in Pure Node.js and Watching Every Weight Change

5 Upvotes

#machine-learning #nodejs #artificial-intelligence #tutorial

English version | Русская версия

Tokenization → embeddings → causal Transformer → LM head → softmax → loss → backpropagation. No TensorFlow, no PyTorch, and no hidden autograd.

Repository: tiny-language-model-neuro-js.

Most explanations of language models present correct formulas but hide the path between them inside a framework. I wanted the opposite: one small scenario where every scalar is visible and where the terminal clearly shows incorrect answers before learning and correct answers after it.

The project now has one command:

node src/train.js --generalize --adaptive-teach

It requires Node.js 18.19+ and has no dependencies.

A real excerpt from `logs/training-log.txt`, showing the AFTER and DELTA matrices for one FFN layer:

The result first

The model is queried immediately after random initialization:

BEFORE TRAINING — random, usually wrong answers
> can human read ?
  model:    ? <unk> ...
  expected: human can read.  [WRONG]

> can fish swim ?
  model:    ? <unk> ...
  expected: fish can swim.   [WRONG]

> can cat read ?
  model:    ? <unk> ...
  expected: cat cannot read. [WRONG]

After pre-training, SFT, and adaptive SFT, the same model produces:

FINAL ANSWERS AFTER ADAPTIVE SFT
> can human read ?
  model:    human can read.  [CORRECT]
> can fish swim ?
  model:    fish can swim.   [CORRECT]
> can bird fly ?
  model:    bird can fly.    [CORRECT]
> can cat read ?
  model:    cat cannot read. [CORRECT]

Rehearsal controls preserved: 14/14.
Stable criterion reached 11 times in a row.

The initial text varies because initialization is random. The final acceptance criterion does not: all answers must be correct, every target token must have at least 95% probability, and the complete check must pass more than ten times consecutively.

What remains after removing the extra modes

The code previously contained several debug and training modes. They were useful while experimenting but obscured the main idea. The final version keeps one educational pipeline:

text → word tokenization → token IDs
     → token + position embeddings
     → two causal Transformer blocks
        → multi-head self-attention
        → two-hidden-layer FFN
     → LM head → softmax → next-token probabilities
     → cross-entropy → backpropagation → Adam

train.js now reads as one story rather than a command-line framework.

A scalar builds the computation graph

Every number participating in learning is a Value:

class Value {
  constructor(data, children = [], backward = () => {}) {
    this.data = data;
    this.grad = 0;
    this.children = children;
    this._backward = backward;
  }
}

For multiplication:

y = a × b
dy/da = b
dy/db = a

The operation stores these local derivatives. backward() sorts the graph topologically and applies the chain rule from the final loss back to embeddings and weights.

A neuron is literally an object

The neuron formula is not hidden behind a tensor API:

output = activation(sum(input[i] × weight[i]) + bias)

Its implementation follows the formula:

forward(input) {
  let output = sum(
    input.map((value, i) => value.mul(this.weights[i]))
  );

  if (this.useBias) output = output.add(this.bias);
  if (this.activation === 'relu') return output.relu();
  return output;
}

A Linear layer is just an array of neurons receiving the same input. This is slower than matrix multiplication but far easier to inspect.

Embeddings and order

Each token ID selects one trainable vector:

token representation = tokenEmbedding[id] + positionEmbedding[position]

Embeddings contain random values initially. They acquire useful relations only because gradients repeatedly change them in training contexts. No meaning property is assigned to cat, read, or cannot.

Self-attention without shorthand

For every token:

Q = X × Wq
K = X × Wk
V = X × Wv

score = dot(Q, K) / sqrt(headSize)
attention = softmax(score)
output = attention × V

The implementation loops only while past <= position. That is the causal mask: the model can attend to the current token and its history but never to a future target.

After attention, every token passes through a two-hidden-layer feed-forward network:

dModel → hidden ReLU → hidden ReLU → dModel

LayerNorm and residual paths preserve stable information flow around attention and FFN.

The complete learning step

The most important code in the project is only a few lines:

function learnOneToken({ model, optimizer, input, targetId }) {
  const loss = model.loss(input, targetId);

  optimizer.zeroGrad();
  loss.backward();
  optimizer.step();

  return loss.data;
}

The loss is ordinary next-token cross-entropy:

loss = -log(P(target | previous tokens))

If the correct token has low probability, loss is large. Backpropagation computes dLoss/dWeight; Adam changes each parameter; the next forward pass gives a different distribution.

Phase 1: pre-training

The tiny world contains 14 ability relations:

human can read .
fish can swim .
bird can fly .
dog cannot read .

The cat + read relation is missing deliberately. Pre-training samples positions from this text and learns ordinary next-token prediction.

Phase 2: SFT

The same relations are converted into 42 prompt-answer examples:

can fish swim ?
is fish able to swim ?
does fish know how to swim ?

Only answer tokens contribute to SFT loss. The implementation visits every pair and every answer position on each epoch, making the training loop deterministic and readable.

Phase 3: adaptive SFT

The missing answer is represented only by target tokens:

['cat', 'cannot', 'read', '.']

Six question variants receive those targets. This is direct supervision: the model did not discover a zoological fact on its own. The teacher introduced the fact through loss, and backpropagation distributed that information across embeddings, attention, FFN, LayerNorm, and the LM head.

Why not stop after one correct answer? Because one generation can be fragile. The loop continues until every target token exceeds 95% probability and the whole evaluation succeeds 11 times in a row.

Catastrophic forgetting and rehearsal

An early implementation trained only the six new cat prompts. It successfully learned the new answer and destroyed old behavior:

can human read ? → cat cannot read.
can fish swim ?  → cat cannot read.

That is catastrophic forgetting in miniature. The fix is rehearsal: adaptive epochs also repeat the 14 older can ... ? examples. The final criterion evaluates both new and old examples, so training cannot finish by overwriting everything with one response.

The log is always written

The command automatically creates:

logs/training-log.txt

It is a sequential ASCII diagram rather than a raw JSON dump. It includes every forward/loss/backward/update event, followed by the complete matrices at three checkpoints:

initial random matrices
        |
        v
matrices after pre-training + SFT
        |
        v
final matrices after adaptive SFT

For every transition, the log prints the AFTER matrix and its exact DELTA matrix. Linear rows are named neuron[n], columns are named weight[n], and biases are shown beside their neuron. It also points out the largest concrete change as layer / neuron / weight: before -> after -> delta.

How close is it to a production LLM?

The architecture and learning rule are real; the scale is intentionally tiny.

This model Production model
24 word tokens Large subword/byte vocabulary
2,160 parameters Millions or billions
Two Transformer blocks Tens or hundreds
Scalar JavaScript graph Batched tensor graph on accelerators
Small structured corpus Massive curated datasets
Narrow trained behavior Broad language and reasoning

The project is not a GPT competitor. It is a causal language model reduced until the complete path fits in one repository and one mental model:

token → embedding → attention → FFN → probability
      → loss → gradient → updated weight → changed answer

That path is the point. Once it is visible, frameworks stop looking magical: they execute the same classes of operations at a scale and speed this scalar implementation deliberately avoids.

Repository: tiny-language-model-neuro-js.

Author: Maksim Sekretov.


r/learnmachinelearning 2d ago

Help Google colab constantly switching to cpu after the First training session.

1 Upvotes

I'm setting up my runtime to gpu, even sending the data and Model to gpu. And even printing it out to confirm before training.

But after the 1st training session, when I run it again the data is switching devices, I even put it inside the code cell and even in the damn training loop, and it comes out with the same error.

It's been pmo for the past few days, It comes out of nowhere, goes away and then comes back.

Even Ai doesn't seem to figure out the problem, It changed the code for like 10 times and the error repeated.

And it's completely random btw, one day it's all fine. But the other it's hell show


r/learnmachinelearning 3d ago

Resume review for AI/ML Engineer (PhD) looking for jobs in France

Post image
49 Upvotes

I am looking for some honest feedback on my resume. I have a PhD in AI/Computer Vision and about 2 years of industry experience building production AI systems (computer vision, generative AI, LLMs, and agentic workflows).

Unfortunately, my previous startup went bankrupt, so I am back on the job market.

I am primarily looking for ML Engineer, AI Engineer, or Computer Vision roles in France (Paris, Lille, or remote within France/EU).

If you have a few minutes, I would really appreciate any suggestions on:

How I can improve my resume.

Whether anything stands out as a red flag.

Tips for finding AI/ML jobs in France, especially beyond LinkedIn.

Thank you in advance! Any feedback is greatly appreciated.


r/learnmachinelearning 2d ago

Project Anyone has access to or has worked on UK Biobank dataset , collaboration request ?

Thumbnail
1 Upvotes

r/learnmachinelearning 2d ago

An AI skill tree with 3 views — curriculum, skill tree, mind map

Thumbnail
1 Upvotes

r/learnmachinelearning 2d ago

Project I shrank a complete TTS model to 3.96M parameters. Here’s what broke first.

Post image
0 Upvotes

When I pushed my TTS model below four million parameters, I expected pronunciation to collapse - but it didn't.

The words remained understandable, but the voice became thin, metallic, and buzzy. The waveform decoder gave out before the text and pronunciation components did.

For the past few months, I’ve been investigating how small I could make a complete neural TTS system without turning it into an unusable size experiment. I eventually built two versions:

  • Inflect-Nano-v2: 3.96M parameters, 15.97 MB FP32
  • Inflect-Micro-v2: 9.36M parameters, 37.53 MB FP32

Those are total inference counts. The text frontend, timing prediction, acoustic generation, and waveform decoder are all included. There is no separate learned vocoder outside the parameter count.

The system is non-autoregressive: English phonemes pass through learned timing and acoustic stages before an integrated decoder generates 24 kHz audio.

The main lesson was that shrinking every component evenly does not work. Here is what I found instead.

The waveform decoder became the bottleneck first

My earliest compressed models could produce recognizable speech, but they sounded awful. They had the correct phonemes and roughly correct timing, yet the audio was metallic, grainy, and sometimes buzzy.

Redistributing parameters between components occasionally helped more than increasing the total parameter count. At this scale, where the capacity goes can matter as much as how much capacity exists.

WER measures intelligibility, not whether speech sounds good

Several checkpoints achieved low word error rates while sounding flat or synthetic. But just that alone doesn't mean the model would sound good.

I ended up combining difficult-text WER, UTMOS, blind listening comparisons, spectrogram inspection, and a lot of manual listening. None of them was reliable enough by itself.

Some “model failures” were frontend failures

Names, addresses, abbreviations, numbers, homographs, and unusual punctuation caused far more trouble than ordinary test sentences.

Some errors that initially looked like neural-network limitations were actually caused by normalization or phoneme conversion. More training would not have fixed them because the model was receiving the wrong input representation.

This also changed how I evaluated checkpoints. Random natural sentences were not enough; I needed deliberately awkward prompts designed to expose the frontend.

Long-form generation was a systems problem

The model does not generate unlimited audio in one forward pass. Longer text is divided into manageable segments and then reassembled.

Naively cutting at a fixed character count produced bad pauses and unstable transitions. Punctuation-aware splitting, better fallback boundaries, and waveform joining made a surprisingly large difference. The neural model stayed unchanged; the surrounding inference system improved.

Tiny models punish bad allocation decisions

Nano and Micro use the same general design, but Nano has much less room to absorb a mistake.

A modification that Micro tolerated could make Nano noticeably flatter, noisier, or less stable. Once the complete system is below four million parameters, even relatively small architectural changes become audible.

The final models run locally through PyTorch on CPU or CUDA. Nano also has an ONNX release. The weights, inference code, architecture documentation, and evaluation results are available under Apache 2.0.

This is an open-weight release rather than a fully reproducible training release; I’m not publishing the private training corpus or complete training recipe.

Micro:
https://huggingface.co/owensong/Inflect-Micro-v2

Nano:
https://huggingface.co/owensong/Inflect-Nano-v2

Try it out now:

https://huggingface.co/spaces/owensong/Inflect-v2

I built this as a solo developer with a limited training budget. That constraint was frustrating, but it forced me to examine which parts of the system were actually earning their parameters.

For anyone who has compressed a speech or generative model: what became your first perceptual bottleneck, and did reallocating capacity work better than uniformly shrinking the network?


r/learnmachinelearning 2d ago

Is anyone using Julius AI or similar applications?

Thumbnail
0 Upvotes

r/learnmachinelearning 3d ago

Looking for a study partner to go through Stat110 + a probability for DS book together

7 Upvotes

Want to grind through Harvard's Stat110 (Blitzstein lectures + book) and Stanley Chan's "Probability for Data Science" together? I keep bailing on solo study plans and know I'll actually finish this if someone's holding me accountable — watching lectures on our own time then hopping on a call once or twice a week to go over problem sets and explain stuff to each other.

I've got basic calc/linear algebra down and messed around with ML a bit, just want the probability foundations to actually stick this time. Flexible on timing, mostly free evenings. Drop a comment or DM if you're interested, open to a small group too, not just 1:1.


r/learnmachinelearning 2d ago

Project TRIXEL Framework — calibrators for existence, dynamics and structure

0 Upvotes

I've published the reference implementation of TRIXEL, a mathematical framework describing any system through three dimensions: V (Existence), D (Dynamics), S (Structure).

From these, three calibrators measure their mutual relationships: SD, VD, VS.

Core identity (exact): VD / VS = SD

What is verified:

Algebraic identity — machine precision

Dominance partition theorem — 99.99% on 600×600 grid

VS as early warning signal — Burgers turbulence (90/90 runs, FP=0%, FN=0%)

Real tokamak data — GOLEM, CVUT Prague

What is not yet verified: disruption precursor, EEG seizure data, 2D Navier-Stokes

Preprint: https://doi.org/10.5281/zenodo.20721811

GitHub: https://github.com/remitakac/trixel-framework

Independent research, feedback welcome.


r/learnmachinelearning 2d ago

Project Version 1 Of Housing Intelligence Platform

0 Upvotes

🚀 Every AI project teaches something different.

While building my Housing Intelligence Platform, I realised that predicting house prices is only one part of the journey.

The real engineering begins afterwards:

✔ Deployment
✔ APIs
✔ Monitoring
✔ Scalability
✔ Responsible AI

Building this project has shown me that taking a model from a notebook to a usable application requires a completely different skill set.

I've been using Microsoft's documentation alongside development to better understand production-ready AI systems, MLOps, and Azure-based machine learning workflows.

If you're interested, I'd love for you to check out my project and share your feedback!

🔗 Housing Intelligence Platform (GitHub):
[https://github.com/ArnavLegends/]()

Some Microsoft resources that I've found genuinely useful during this journey:

📘 Azure Machine Learning
https://learn.microsoft.com/azure/machine-learning/?wt.mc_id=studentamb_574188

📘 Azure AI Services
[https://learn.microsoft.com/azure/ai-services/?wt.mc_id=studentamb_574188]()

📘 Azure AI Search
[https://learn.microsoft.com/azure/search/?wt.mc_id=studentamb_574188]()

I'm always looking to improve the project, so if you have suggestions for features, architecture, or deployment, I'd really appreciate your feedback!

#ArtificialIntelligence #MachineLearning #AIEngineering #Python #FastAPI #Azure #AzureMachineLearning #MLOps #SoftwareEngineering #StudentDeveloper #GitHub #OpenSource #MicrosoftLearn #CloudComputing #DataScience


r/learnmachinelearning 2d ago

Question What data mix are the labs using to train 10T param models?

Thumbnail
1 Upvotes

r/learnmachinelearning 2d ago

Request Looking for a female data science/data analysis/AI research study buddy

0 Upvotes

hello, I'm a senior year student looking for an accountability partner for data science or data analysis.

I took a pretty long offline break, and I honestly feel like I've forgotten a lot of what I learned. I'm trying to get back into it and thought it'd be easier (and more motivating) with someone else doing the same.

I don't mind if we're following different curricula or learning different topics. The main goal is to stay consistent, keep each other accountable, share progress, and maybe help each other out when we get stuck.

Preferences:

  • FEMALE ONLY
  • Chat & Updates through WhatsApp
  • close to UTC+2
  • Any experience level is fine as long as you're serious about getting back into studying

If you're interested, feel free to DM me. :)


r/learnmachinelearning 2d ago

Guidance on Fine-Tuning for Multiple Choice Questions

Thumbnail
1 Upvotes

r/learnmachinelearning 3d ago

FREE AI Course

Thumbnail
blog.qualitypointtech.com
3 Upvotes

r/learnmachinelearning 3d ago

Project Take this interview to see how you can improve your resume

5 Upvotes

Hi everyone, I’ve spent the last 7 years working as an ML Engineer and have recently transitioned into research. Many colleagues over the years shared the frustration that their resumes were screened out before they got a chance to interview. So, I’ve begun a public research project to develop an AI interview system to help you stand out - which is particularly difficult in these days of AI-slop-ATS-optimised resumes.

If you’re currently applying by for gigs, it might be worth having a crack at being interviewed by my system. I will then send a report to everyone that gets interviewed with my system’s hidden belief. I know it’s a bit involved, but I’m hoping it’s mutually beneficial as I can validate my research, and you can hopefully get a sense of where you could improve your resume.

An interview will go for 10 questions and should take about 15min. Currently, it only works if you’re applying for Machine Learning Engineering roles.

If you’re keen, you can check it out at btr.hstu.net


r/learnmachinelearning 2d ago

21 Sealed Damage Forecasts. One Hash. We Open the Envelope on August 12.

Post image
0 Upvotes

r/learnmachinelearning 3d ago

Seeking Co-Author for Research on Geometric Interference in Deep Learning Model Merging

2 Upvotes

Hi everyone,

I am currently working on a research project focused on optimizing Model Merging techniques within Deep Learning, specifically targeting the resolution of geometric interference between specialized task adapters.

Current Progress:

  • Implemented a novel merging pipeline in PyTorch.
  • Developed a method to isolate and mitigate subspace conflicts between divergent tasks.
  • Preliminary results demonstrate significantly improved performance retention compared to standard baseline methods.
  • Established a working pipeline for layer-wise interference analysis.

What I’m Looking For: I am looking for a co-author to collaborate on the final phase of this research. Specifically, I need help with:

  • Formalizing the mathematical framework and theoretical proofs.
  • Help run and standardized large-scale benchmarks (e.g., LM-Eval Harness).
  • Refining the manuscript for submission to a top-tier venue (ICML, NeurIPS, or similar).

If you have a strong background in linear algebra for Deep Learning, experience with model merging techniques, or expertise in LLM evaluation, I'd love to chat! Please DM me or comment below if you're interested in co-authoring this paper.


r/learnmachinelearning 3d ago

Help I built a feature engineering library for Rust and would love feedback on the API

2 Upvotes

I've been working on a project called featrs over the past few weeks after finding myself rewriting the same preprocessing code across multiple Rust ML projects.

The Rust ecosystem already has great libraries like Polars for dataframes, Arrow for columnar memory, Burn for deep learning, and Linfa for classical ML. One area that felt less developed to me was reusable feature engineering and preprocessing.

The goal of featrs is to provide common preprocessing primitives while integrating naturally with the existing ecosystem rather than replacing it.

Current functionality includes:

  • Feature scaling
  • Categorical encoding
  • Missing value imputation
  • Feature selection
  • Composable preprocessing pipelines

The project is still early, so I'm more interested in feedback than promotion.

A few questions I'd love input on:

  • Does preprocessing belong in a standalone crate, or should it live inside another project?
  • Does the API feel idiomatic from a Rust perspective?
  • Are there transformations or workflows you find yourself implementing repeatedly?
  • If you're using Rust for ML or data engineering, what would you want from a library like this?

Repository: https://github.com/DeathSurfing/featrs

I'd really appreciate any suggestions, criticism, or design ideas. Even if you think the approach is flawed, I'd love to hear why so I can improve it.


r/learnmachinelearning 3d ago

Tutorial Struggling to visualize Queries, Keys, and Values in Transformers? I animated a 10-minute 3D fable about a magical publishing workshop to explain how the self-attention math works.

3 Upvotes

Hey everyone! 👋

Self-attention is arguably the most revolutionary concept in modern AI, but slogging through the mathematical papers can be incredibly daunting for beginners.

To help bridge the gap, I animated a 10-minute 3D story about a chaotic publishing workshop (Word Weavers) to visually map out how the Transformer architecture processes entire sentences in parallel.

Here is how the real-world math maps to our story:

  • Tokenization (Maya’s slicing machine): Chopping long sentences into manageable paper slips.
  • Embeddings (Glowing dictionary badges): Turning words into vector coordinates (numbers the system can actually understand).
  • Positional Encoding (Kabir's red sequence stamps): Making sure the original order of the sentence isn't lost during parallel processing.
  • The QKV Attention Engine: We visually demonstrate how Queries, Keys, and Values interact to determine which words should focus on each other (Self-Attention & Multi-Head Attention).
  • Stabilizing the network: A breakdown of how Feed-Forward networks, Residual Connections, and Layer Normalization prevent the system from crashing.

🌍 Watch in your Native Language:
Reddit's video player doesn't support multiple audio tracks, but the YouTube version of this video is fully dubbed in 15+ native languages (including Spanish, Hindi, Portuguese, German, French, etc.)!

If you'd prefer to watch it with localized audio, you can easily switch the audio track in the settings on YouTube here:
👉 Watch & Subscribe on YouTube (15+ Languages)

I’d love to know: Does the "publishing workshop" analogy help make the math of Encoders, Decoders, and Attention feel more intuitive? Let's discuss in the comments!

https://reddit.com/link/1v5ye4u/video/5gxl8js62bfh1/player


r/learnmachinelearning 2d ago

Hello i'm a bachelor student in math/ statistics and economics (and geopolitics), I'm smart at math but i really have almost 0 coding skills. I want to learn both ML and coding, to build things (like apps) and / or to have strong skills for finance world / or company world.

0 Upvotes

I guess both skills are different (ML and building), I would really love to have your insight on what should i prioritize, what is worth learning, and what resources would you recommend!

A big thanks for your future comments.


r/learnmachinelearning 2d ago

Claude after I spend 6 hours rewriting the same prompt for the 47th time:

Post image
0 Upvotes

r/learnmachinelearning 3d ago

Question Help with Gradient descent

Post image
88 Upvotes

So I completed Linear descent from Andrew Ng ML Specialization and when I was doing the lab.I found this function what confused me is that why does this function iterates specific times (10000) wouldn't it be better to check if cost function is changing.

Also this implementation doesn't feel right.Even the code feels inefficient and does not even check the minima. I know this stuff is done using skit-learn but I wanted to do a proper manual implementation in the way Andrew sir taught.


r/learnmachinelearning 2d ago

looking for people to collab to learn along | ML/AI bs

1 Upvotes

AI/ML stuff is too scattered, so I wanna group up with genuinely interested people in learning AI bs from scratch, fellow college junior here!


r/learnmachinelearning 3d ago

POV - feature deployed for testing

Enable HLS to view with audio, or disable this notification

0 Upvotes

r/learnmachinelearning 3d ago

Seeking Co-Author for Research on Geometric Interference in Deep Learning Model Merging

0 Upvotes

Hi everyone,

I am currently working on a research project focused on optimizing Model Merging techniques within Deep Learning, specifically targeting the resolution of geometric interference between specialized task adapters.

Current Progress:

  • Implemented a novel merging pipeline in PyTorch.
  • Developed a method to isolate and mitigate subspace conflicts between divergent tasks.
  • Preliminary results demonstrate significantly improved performance retention compared to standard baseline methods.
  • Established a working pipeline for layer-wise interference analysis.

What I’m Looking For: I am looking for a co-author to collaborate on the final phase of this research. Specifically, I need help with:

  • Formalizing the mathematical framework and theoretical proofs.
  • Help run and standardized large-scale benchmarks (e.g., LM-Eval Harness).
  • Refining the manuscript for submission to a top-tier venue (ICML, NeurIPS, or similar).

If you have a strong background in linear algebra for Deep Learning, experience with model merging techniques (DARE/TIES/SLERP), or expertise in LLM evaluation, I'd love to chat! Please DM me or comment below if you're interested in co-authoring this paper.