메뉴
HN
Hacker News • 52일 전

8달러 마이크로컨트롤러(ESP32-S3)에서 구동하는 SLM

IMP
7/10
핵심 요약

고가의 GPU나 데이터센터 없이도, 단 8달러하는 마이크로컨트롤러(ESP32-S3) 자체에서 트랜스포머 모델을 처음부터 끝까지 직접 학습(Training)할 수 있음을 증명한 실험입니다. 사전 학습된 모델을 단순히 실행(추론)하는 것을 넘어, 현장에 설치된 기기가 주변 환경 데이터를 실시간으로 학습해야 하는 '온디바이스(On-device) 학습'의 가능성을 여는 중요한 사례입니다.

번역된 본문

이 글은 AI의 도움을 받아 작성되었습니다. 주의할 점: AI의 도움을 받았다는 것은 AI가 글을 썼다는 뜻이 아닙니다. 이는 AI가 교정하고, 검토하고, 일부 내용을 채워 넣었을 뿐 작성자는 인간(이라고 나는 믿습니다)이라는 뜻입니다.

Qapla' (클링온어) 프로젝트 이것은 8달러짜리 ESP32-S3에서 트랜스포머(Transformer)를 처음부터 학습시키는 방법에 대한 이야기입니다. 아무도 원하지 않았지만 모두에게 필요했던 (클링온어) GPT입니다. 그렇다면 왜 우리에게 그것이 필요했을까요? 모델 학습에는 GPU나 데이터센터가 필요하다고 우리는 당연하게 생각하기 때문입니다. 하지만 항상 그런 것은 아닙니다. 때로는 8달러짜리 소형 마이크로컨트롤러만으로도 모델을 처음부터 학습시키기에 충분합니다.

다시 한번 읽어보세요. '학습'입니다. 처음부터(training from scratch)입니다. 미리 만들어진(pre-cooked) 모델을 실행하는 것이 아니라 '학습'입니다. 순전파(forward pass), 역전파(backprop), 가중치 업데이트(weight updates)가 칩 내부에서 일어납니다.

Qapla' 프로젝트란 무엇인가? 엣지 AI(Edge AI)는 새로운 것이 아닙니다. TinyML은 수년 동안 마이크로컨트롤러에서 추론을 수행해 왔으며, 안드레이 카르파시(Andrej Karpathy)의 미니멀리즘 프로젝트인 llama2.c의 커뮤니티 포팅판은 약 26만 개의 매개변수(parameters)를 가진 트랜스포머를 ESP32에 탑재했습니다. 그리고 최근에는 훌륭한 프로젝트를 통해 약 2,900만 개의 매개변수를 가진 모델을 8달러짜리 ESP32-S3에서 구동시키는 데 성공했습니다. 이들은 훌륭한 작업 성과이며, 비록 시기상으로 이번 실험과 겹치긴 했지만 우리가 추구하던 모델은 아니었습니다.

Slava S.(slvDev)의 esp32-ai 프로젝트 및 다른 유사한 프로젝트들은 모두 한 가지 공통점이 있습니다. 바로 '추론(inference)'이라는 것입니다. 모델은 GPU나 데이터센터와 같은 다른 곳에서 탄생하여 데이터로 학습된 후, 양자화(quantization)되고 나서야 비로소 칩에 로드되어 구동됩니다. 즉, '두뇌'는 외부에서 조리된 후 칩 위에 올려지는 것입니다.

우리는 다른 질문을 던졌습니다. 만약 모델이 외부에서 탄생할 수 없다면 어떻게 될까요? 만약 기기가 설치될 장소에 가서야 비로소 학습에 필요한 데이터가 생성되기 때문에, 모델이 사전 학습(pre-trained)될 수 없다면 어떻게 될까요? 또한 그 데이터를 미리 가지고 올 수도 없고, 다운로드할 인터넷 환경도 갖추지 못했다면 어떻게 될까요?

여러분이 무슨 생각을 하는지 압니다. "알겠는데... 도대체 왜 누군가 ESP32에서 트랜스포머를 학습시켜야 하죠?" 이는 타당한 질문입니다. 어쩌면 대답은 "아무 이유도 없다"일 수 있습니다. 하지만... 한번 상상의 나래를 펴본다면 이런 상황을 떠올려 보십시오. 한가운데 있는 농기계 부품에 볼트로 고정된 센서가 특정 기계만의 정상적인 진동(세상의 다른 어떤 기계와도 다른)을 학습하여, 고장 나기 전에 문제를 감지하고 유지보수 일정을 잡아야 하는 상황입니다 (아니요, 저를 낚으려 하지 마세요. 인터넷이 없다고 말했지만... LoRa 통신이 있다면? 😉). 또는 특정 토양이 어떻게 마르는지(그 땅의 흙, 햇빛, 배수 상태)를 학습하여 식물이 스트레스를 받기 전에 언제 물을 줘야 할지 예측하는 밭의 센서를 상상해 보십시오.

이러한 경우(우리가 생각할 수 있는 다른 경우들도 마찬가지로)에는 기기가 설치되기 전까지는 데이터가 존재하지 않습니다. 즉, 누구도 미리 모델을 학습시킬 수 없었습니다. 칩은 스스로, 그것도 제자리에서 즉각적으로 학습해야만 합니다.

안타깝게도 우리 주변에는 실험해 볼 농기계가 없었습니다. 그래서 ESP32의 실제 학습 능력을 테스트하기 위해, 우리가 가지고 있는 유일한 데이터인 '언어'를 중심으로 실험을 설계했습니다. 아무의 도움도 없이 8달러짜리 칩이 처음부터 언어를 학습하는 데 어디까지 갈 수 있을까요?

마이크로컨트롤러에서의 학습이 실제로 의미하는 바는 무엇일까요? 8달러짜리 마이크로컨트롤러 내부에서의 학습은 데이터센터에는 없는 게임의 규칙을 부과합니다. 그리고 이러한 규칙들이 다른 모든 것을 결정짓습니다:

첫째, 다시 한번 강조하지만 메모리가 핵심입니다. ESP32-S3은 기가바이트(GB)가 아닌 몇 메가바이트(MB)의 RAM/PSRAM만을 가지고 있습니다. 이는 모델의 크기를 제한합니다. 우리는 수백만 개가 아닌 수십만 개 수준의 매개변수를 이야기하고 있는 것입니다. 칩에 맞아들어가고(fit) 학습될 수 있는 모델은 필연적으로 작을 수밖에 없습니다.

둘째, 작은 모델이 수행할 작업을 지배합니다. 이 정도 크기의 모델은 언어의 구조(단어가 만들어지는 방식, 음운론, 일부 문법)는 학습할 수 있지만, 전체 언어의 심층적인 의미(semantics)까지는 학습할 수 없습니다. 그러므로 수행해야 할 작업(task) 역시 모델의 크기에 맞게 축소되어야 합니다.

셋째, 말뭉치(corpus)가 결과를 지배합니다. 작은 모델에는 기가바이트 단위의 텍스트가 필요하지 않습니다. 콤팩트하고, 정제되며, 구조화된 말뭉치가 필요합니다. 또한, 이를 퍼블릭하게 공개하려면 저작권 골칫거리가 없어야 합니다.

이 세 가지 제약 조건, 즉 '작은 모델, 제한적인 작업, 정제되고 콤팩트한 말뭉치'를 합치면, 우리가 던졌던 질문... (중략)

원문 보기
원문 보기 (영어)
This text was written with the assistance of an AI. Careful: assistance doesn't mean the AI wrote it. It means it corrected, reviewed and filled in some parts, but the author is human (or so I believe). Léeme en español Qapla' Project This is how you train a transformer from scratch on an eight-buck ESP32-S3. The (Klingon) GPT nobody asked for but everybody needed. And why did we need it? Because we take for granted that training a model requires a GPU or a datacenter. Not always: sometimes something as small and as cheap as an eight-buck micro is enough to train one from scratch. Read that again: train. From scratch. Not run a pre-cooked model. Train. Forward pass, backprop and weight updates, inside the chip. What is Qapla'? Edge AI is nothing new. TinyML has been doing inference on microcontrollers for years, community ports of llama2.c — Andrej Karpathy's minimalist project — put ~260K-parameter transformers on an ESP32, and just recently a brilliant project got a model of almost 29 million parameters running on an $8 ESP32-S3. They're excellent pieces of work, and although they happen to have overlapped in time with this experiment, they weren't the model we were following. The esp32-ai project by Slava S. (slvDev), and others like it, all share one thing: they are inference. The model is born somewhere else — a GPU, a datacenter — trained on its data, quantized, and only then loaded onto the chip so it can run it. The brain is cooked outside and served on-chip. We asked ourselves a different question: what happens when the model can't be born outside? What happens when it can't come pre-trained — because the data it needs to learn doesn't exist until the device is in place — can't carry that data with it, and has no internet to download it? We know what you're thinking: "Fine, but… why would anyone need to train a transformer on an ESP32?" And it's a fair question. Maybe the answer is "no reason at all". But… if we're going to get creative, picture this: a sensor bolted to a piece of farm machinery in the middle of a field, which has to learn the normal vibration of that specific machine (different from any other machine in the world) to spot when something's going wrong and schedule maintenance before it breaks (and no, you won't catch me out: I said there's no internet, but… LoRa? ;). Or picture a sensor in a plot of land that learns how that particular soil dries out — its earth, its sun, its drainage — and predicts when it'll need watering, before the plants suffer. In those cases (and others we can think of) the data didn't exist until the device was installed: nobody could have pre-trained it. The chip has to learn on the fly, alone, right where it stands. We don't have a piece of farm machinery lying around to experiment with. So, to put the real learning ability of an ESP32 to the test, we designed the experiment around the only thing we did have: language. How far can an eight-buck chip get, learning a language from scratch, with nobody's help? What does training on a micro actually mean? Training inside an eight-buck micro imposes rules of the game a datacenter doesn't have. And those rules dictate everything else: Once again, memory rules. An ESP32-S3 has a few MB of RAM/PSRAM, not gigabytes. That caps the size of the model: we're talking hundreds of thousands of parameters here, not millions. A model that "fits" and trains on the chip is, by necessity, small. The small model rules the task. A model this size can learn the structure of a language (how words are built, its phonotactics, some grammar), but not the deep semantics of an entire tongue. The task has to be cut to the model's size. And the corpus rules the result. With a small model you don't need gigabytes of text. You need a corpus that is compact, clean and structured. And, if you're going to publish it, you need it free of copyright headaches. Put the three constraints together — small model, narrow task, clean and compact corpus — and the question becomes concrete: which language ticks all of those at once? I could tell you we ran a brainstorming session to decide which language to experiment with in this first phase, but sometimes it's better to stick to the old "the first idea is usually the good one"… and in this particular case, the first language that came to mind… was Klingon. The Klingon language Yes, Klingon. The language of the Star Trek warriors. And if you keep reading you'll find the choice has less of the nerd about it and more of the engineer than it seems. Klingon isn't gibberish that spits out alien-sounding noises and calls it a day. It was created by the linguist Marc Okrand in 1984, and it is a constructed language with systematic phonology, grammar and morphology: it has an unusual word order (object-verb-subject) and a morphology with strict rules. In other words: it has real structure to learn, which is exactly what a small model needs in order to prove it's really learning and not just memorising noise. And it fits our constraints: Rich structure, bounded vocabulary. Enough grammar for the model to have something to capture, but a corpus small enough to fit the micro's rules. Reduced alphabet. Working character by character, a vocabulary of ~30 symbols keeps the model tiny — exactly what the ESP32's memory demands. A clean, free corpus. There's a community dictionary under an open licence (boQwI'), so we could train and share without stepping on anyone else's legal turf. Put another way: Klingon is an ideal testbed. A real language, with real grammar, but of a size that fits in the palm of your hand. The perfect lab in which to squeeze the engine before taking it — perhaps in another phase of the project — to real minority languages, with real speakers. Sami? Quechua? Nahuatl? That… is another story. Oh, and yes: it's undeniably cool. A low-cost chip whispering Klingon on a 1.3" OLED has something of the nerd about it, but something of magic too. But that… is just the bonus. qapla'. (Klingon for "success". It seemed like the right name.) What it is NOT (let's be honest) So nobody walks away with the wrong idea, and because rigour matters: It is not a pocket ChatGPT. It doesn't chat, doesn't answer questions, doesn't reason. It's a tiny generative model that learns the shape of a language, not its meaning. It does not produce semantically perfect Klingon. It learns structure — prefixes, suffixes, word order, how phrases sound — and produces text that looks like Klingon and respects many of its rules. But don't expect fully meaningful sentences that a Klingon scholar would sign off on without complaint (if someone aboard the Enterprise received a message from our ESP32, it would probably end up causing a diplomatic incident). And in any case, there isn't enough Klingon in the world to pull that off, nor would the model it would take fit on the chip. It is not inference in disguise. There is no pre-trained model hidden anywhere. The chip starts with random weights and no prior knowledge of Klingon, and learns from scratch. What you're seeing is real learning, not a model cooked somewhere else and served here. It is not fast. Let's be serious: we've said it to death, but… it's an eight-buck micro, not a GPU! Training takes hours. That's precisely the point: that it's slow and still works. What it is : proof that a humble microcontroller with a maker's spirit can train a language model from scratch, entirely on board. No more, no less. Which is no small thing. How it works Here's what really matters, and what you can verify for yourself in the code. The entire learning cycle happens on board: Inside the ESP32-S3: ✓ Random initialisation of the weights (mind the seed, ahem) ✓ Reading and tokenising the corpus ✓ Forward pass ✓ Loss computation (cross-entropy) ✓ Backpropagation (gradients derived by hand) ✓ Weight updates (SGD with momentum + cosine LR) ✓ Saving a checkpoint to flash (LittleFS) ✓ Text generation with the learned weights Outside the ESP3