<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luiz Neto on Medium]]></title>
        <description><![CDATA[Stories by Luiz Neto on Medium]]></description>
        <link>https://medium.com/@luizcf14?source=rss-d9269c051ed9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CB-WNiUAxn9vzjCh.</url>
            <title>Stories by Luiz Neto on Medium</title>
            <link>https://medium.com/@luizcf14?source=rss-d9269c051ed9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:30:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luizcf14/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Feature Maps on Demand: Serving a Landsat Foundation Model to Google Earth Engine]]></title>
            <link>https://medium.com/@luizcf14/feature-maps-on-demand-serving-a-landsat-foundation-model-to-google-earth-engine-98966705c5f4?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/98966705c5f4</guid>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 22:05:30 GMT</pubDate>
            <atom:updated>2026-11-24T22:06:47.145Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We now call a land-cover model trained on 40 years of Landsat mosaics directly from a Google Earth Engine script, and get back a 30-channel feature map for every 30 m pixel on the screen. No exports, no downloads, no local GPU: the map asks, a model on Vertex AI answers, and the result is an ordinary </em><em>ee.Image you can classify, cluster or export.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8dGK38rb28v7Tn8Dqn3kw.png" /></figure><p>Getting there took a self-supervised model, a lot of batch processing, and a surprising number of small infrastructure traps. This post covers all three:</p><ul><li><strong>What the feature maps are</strong> and why they are more useful than another classified map.</li><li><strong>How the model is built</strong>, and the lessons from producing these maps over large areas: seams, quantization, dead channels and an int8 experiment that did not pay off.</li><li><strong>How to serve the model on Vertex AI and call it from Earth Engine</strong>, including every error we hit on the way and the fix for each one.</li></ul><p>If you work with Earth Engine and have a TensorFlow model of your own, the second half is a recipe you can reuse almost line by line.</p><h3>Feature maps: a better starting point than a simple mosaic</h3><p>A feature map gives every pixel a short vector that describes what the model sees there, instead of a single class label. Ours has 30 numbers per 30 m pixel. Pixels that look alike in context (mangrove next to mangrove, a mining pit next to another pit) end up with similar vectors, even if no one ever labelled them.</p><p>That changes how mapping work starts. Instead of training a deep network for every new class, you collect a few hundred points, sample the feature map under them and fit a small classifier, often a Random Forest, inside Earth Engine. The heavy learning has already been done once; each new map reuses it.</p><p>Google made this idea mainstream with the <a href="https://developers.google.com/earth-engine/datasets/catalog/GOOGLE_SATELLITE_EMBEDDING_V1_ANNUAL">Satellite Embedding dataset</a> produced by AlphaEarth Foundations: 64 dimensions at 10 m, available for 2017 to 2024. Our model fills a different niche:</p><p>AlphaEarth:</p><ul><li><strong>Input:</strong> Optical, radar, LiDAR and other sources</li><li><strong>Pixel Size: </strong>10 m</li><li><strong>Years: </strong>2017 to 2024</li><li><strong>Dimensions:</strong> 64</li><li><strong>Access:</strong> precomputed dataset</li></ul><p>Our Model (low budget version):</p><ul><li><strong>Input: </strong>Landsat annual mosaics + elevation</li><li><strong>Pixel Size: </strong>30 m</li><li><strong>Years: </strong>any year with a Landsat mosaic, back to the 1980s</li><li><strong>Dimensions:</strong> 30 (uint8)</li><li><strong>Access: </strong>precomputed in batch, or computed live from your own mosaic</li></ul><p>Because the model runs on a plain Landsat mosaic, it can produce embeddings for the long Landsat archive and for mosaics you build yourself, on demand.</p><h3>The model: small, self-supervised, multi-task</h3><p>The model has 5.6 million parameters and costs about 3.9 billion multiply-adds per 256 × 256 patch, small enough to run on a simple CPU. It reads seven bands of an annual Landsat mosaic (green, red, NIR, SWIR1, NDVI, MNDWI) plus elevation, and returns a 32-channel feature map at the input resolution.</p><p>The architecture has four parts:</p><ol><li><strong>Encoder:</strong> MobileNetV3-Large, initialised from ImageNet, with its first convolution replaced to accept 7 channels.</li><li><strong>Bottleneck:</strong> the 8 × 8 encoder output becomes 64 tokens with a learned position embedding, passed through two Transformer blocks with 8 attention heads. Every pixel can now see the whole 7.7 km patch.</li><li><strong>Decoder:</strong> U-Net style, with four skip connections. Each skip is projected to 32 channels first, so the shallow layers cannot outvote the deep ones, and upsampling is bilinear to avoid checkerboard artifacts.</li><li><strong>Heads:</strong> the shared 32-channel layer feeds a reconstruction head (the 6 optical bands) and a segmentation head (MapBiomas land-cover classes). That shared layer is the feature map.</li></ol><p>Training is masked autoencoding. We hide 50% of the optical input in 16 × 16-pixel blocks (480 m on the ground) and charge the reconstruction loss only on the hidden blocks. Copying through a skip connection is useless there, because the hidden input is zero, so the network has to infer what is under the mask from the surroundings. The segmentation head adds the land-cover vocabulary. A final short fine-tune runs without masking, so the model also behaves well on complete images.</p><p>For storage and serving, each channel is quantized to uint8 (1 to 255, 0 = no data) with a scale frozen across years and sensors. Two of the 32 channels are inactive after training, so 30 channels are kept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUwlGPHx9fVs163dp_4CXg.png" /><figcaption>Internal of Feature Map generator, submitted to SBSR</figcaption></figure><h3>What you can do with them</h3><p>The main use so far is turning a new mapping question into a small classification problem inside Earth Engine. Two examples from our own work:</p><ul><li><strong>Aquaculture on the Brazilian coast.</strong> A Random Forest trained on the feature maps, with aquaculture samples drawn from the MapBiomas reference map and non-aquaculture samples from hand-drawn polygons, validated with the stratified area estimators of Olofsson et al. (2014).</li></ul><figure><img alt="Accuracy assessment metrics, wall to wall." src="https://cdn-images-1.medium.com/max/640/1*IUNTlHK1ma2Kfm5SV5CESw.png" /><figcaption>Wall to Wall — Accuracy Assessment Metrics by Year. Accuracy of a second step Random Forest classifing aquacultures over a Feature Maps mosaic.</figcaption></figure><ul><li><strong>Inside the mining class.</strong> The same approach separates vegetation and water within areas already mapped as mining, a level of detail the original classification does not have.</li></ul><p>Other uses follow from the same property, that similar places get similar vectors:</p><ul><li><strong>Similarity search:</strong> pick a pixel and find everything that looks like it in context.</li><li><strong>Unsupervised exploration:</strong> cluster the 30 channels to find structure before any labelling.</li><li><strong>Change detection:</strong> compare the vectors of the same pixel in two years. Because the quantization scale is frozen across years and sensors, a difference in the numbers is a difference on the ground, not a change of scale.</li><li><strong>New regions:</strong> the model only needs a Landsat mosaic, so it runs wherever one can be built, including countries outside its training area. How well it transfers is an open question worth measuring region by region.</li></ul><h3>Lessons from producing them at scale</h3><p>Most of the work was not the model. It was making the output seamless, comparable across years and honest about its limits.</p><h3>Seams: context beats overlap, and half-measures make it worse</h3><p>The model sees a 256-pixel patch, and the Transformer bottleneck lets every pixel use the whole patch. A pixel near a tile edge therefore sees a different world than its neighbour across the edge, and the junction shows up as a line. We measured the jump at junctions against the natural pixel-to-pixel variation:</p><p>Context read from neighbouring tiles:</p><p>0 px -&gt; 1.6x jump at the junction</p><p>64px -&gt; 25.4x jump at the junction</p><p>128px -&gt; 1x jump at the junction</p><p>A 64-pixel margin was worse than none at all; only a margin of half the patch removed the seam. Inside each tile, overlapping patches are averaged with a Hann window whose weight never reaches zero at the border.</p><h3>One frozen scale for every year</h3><p>Normalizing each file by its own minimum and maximum produced a checkerboard: the same value meant different things in neighbouring tiles. We now measure per-channel percentiles (0.1 and 99.9) once, over the same grids in every year and with equal weight per year, and freeze them. Each GeoTIFF carries a tag identifying the scale it was written with, so mixed scales are caught automatically.</p><h3>Dead channels are real</h3><p>Two of the 32 output channels are constant: their ReLU6 units stopped responding early in training and never recovered. We detect them automatically, per year and per sensor, and drop them. Next time, a normalization layer before that activation should prevent it.</p><h3>Silent failures are the expensive ones</h3><p>When some mosaic tiles had 6 bands and others 7, gdalbuildvrt dropped the odd ones with only a warning, and those tiles came out as empty files counted as successes. We now select bands by name before building the virtual mosaic and turn every dropped file into an error.</p><h3>int8 quantization did not pay off in Vertex AI</h3><p>We expected int8 to make CPU serving cheaper. On an AVX2 CPU with 2 threads, TFLite int8 ran at 48 ms per patch against 46 ms for float32, so there was no gain. It also moved the uint8 embedding by 7 levels on average, while the cosine similarity still read 0.993. Cosine hides changes that a per-channel quantized product makes visible: measure fidelity in the units your users will consume.</p><h3>Serving it on Vertex AI</h3><p>The served model is the same network wrapped in a serving function that does everything the batch pipeline did: decode the input, normalize it, run the overlapping patches, blend them with the Hann window, drop the dead channels and quantize to uint8. We checked it against the batch product: 99.9998% of the uint8 values are identical and the rest differ by one level.</p><p>We export it as a TensorFlow SavedModel with keras.export.ExportArchive and serve it with the official TensorFlow Serving image in a custom container. Vertex AI&#39;s prebuilt TensorFlow containers stop at TF 2.15, and those reach end of availability on 14 January 2027, while our model is Keras 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*bY5kzPFzSNhwV8Ro7AhVcQ.png" /></figure><p>Earth Engine sends one tile per request and gets the embedding back in the same encoding; the container never stores the model, it reads it from the bucket.</p><p>The registration that finally worked reads the model straight from our bucket and exposes only the REST port:</p><pre>gcloud ai models upload --region=us-central1 --display-name=mbx-embeddings \<br>  --container-image-uri=us-central1-docker.pkg.dev/PROJECT/mbx/tf-serving:2.18.0 \<br>  --container-command=/usr/bin/tensorflow_model_server \<br>  --container-args=&quot;--model_name=model,--model_base_path=gs://BUCKET/models/mbx,--rest_api_port=8080&quot; \<br>  --container-ports=8080 \<br>  --container-predict-route=/v1/models/model:predict \<br>  --container-health-route=/v1/models/model</pre><p>Each line of it fixes a problem we hit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJbCJ0dAMQe2zH1vD-Pb-Q.png" /></figure><p>Two bonuses of reading from the bucket: a new model version is published by copying a folder named 2/, 3/ and so on next to the old one, and TF Serving switches to it without a new deployment. Copy to a staging folder first and move it in, so the server never picks up a half-uploaded version.</p><h3>Calling it from Earth Engine</h3><p>ee.Model.fromVertexAi cuts the image into tiles, sends each tile to the endpoint and stitches the answers into an ee.Image. Three details decide whether it works.</p><p><strong>1. The tile geometry.</strong> The overlap is added on each side of the tile. With inputTileSize: [128, 128] and inputOverlapSize: [128, 128], each request carries 384 × 384 pixels: 128 useful plus 128 of context on every side, exactly the margin that removed the seams. We learned this from an error: a payload of 11,469,078 bytes is 640 × 640 pixels × 7 bands × 4 bytes, so our first overlap of 256 had been added twice.</p><p><strong>2. The payload format.</strong> Over HTTP (SERIALIZED_TF_TENSORS), every band of every tile arrives as text: a serialized TensorProto of shape [384, 384, 1], base64-encoded in the web-safe alphabet. The answer has to go back the same way. The serving function decodes and encodes inside the graph:</p><pre>def from_ee(texts, dtype):<br>    # [B] base64 strings -&gt; [B, 384, 384, 1]<br>    one = lambda s: tf.ensure_shape(<br>        tf.io.parse_tensor(tf.io.decode_base64(s), dtype), [384, 384, 1])<br>    return tf.map_fn(one, texts, fn_output_signature=tf.TensorSpec([384, 384, 1], dtype))<br><br>def to_ee(tiles):<br>    # [B, ...] -&gt; [B] base64 strings<br>    return tf.map_fn(lambda t: tf.io.encode_base64(tf.io.serialize_tensor(t)),<br>                     tiles, fn_output_signature=tf.TensorSpec([], tf.string))<br><br>spec = [tf.TensorSpec([None], tf.string, name=b) for b in BANDS]<br><br>@tf.function(input_signature=spec)<br>def serve(green, red, nir, swir1, NDVI, MNDWI, elevation):<br>    bands = [from_ee(v, tf.uint8) for v in (green, red, nir, swir1, NDVI, MNDWI, elevation)]<br>    return {&#39;embedding&#39;: to_ee(embed_tile(bands))}   # embed_tile: normalize, blend, quantize</pre><p><strong>3. The payload size.</strong> Earth Engine refuses maxPayloadBytes above 5 MiB. A 384-pixel tile in float32 is 4.1 MB, which becomes 5.5 MB once base64-encoded. Since the mosaic is already stored as bytes, we send uint8 and let the model convert to float: 1.03 MB per tile, 1.38 MB on the wire, with identical results.</p><p>On the Earth Engine side, the whole thing is one call:</p><pre>var model = ee.Model.fromVertexAi({<br>  endpoint: &#39;projects/PROJECT/locations/us-central1/endpoints/ENDPOINT_ID&#39;,<br>  inputTileSize: [128, 128],<br>  inputOverlapSize: [128, 128],                 // per side: 384-pixel tiles<br>  proj: ee.Projection(&#39;EPSG:4326&#39;).atScale(30),<br>  fixInputProj: true,                           // the model always sees 30 m pixels<br>  outputBands: {embedding: {type: ee.PixelType(&#39;int&#39;, 0, 255), dimensions: 1}},<br>  maxPayloadBytes: 2000000,<br>  payloadFormat: &#39;SERIALIZED_TF_TENSORS&#39;<br>});<br><br>var input = mosaic.select(BANDS).toUint8().addBands(elevation.toUint8());<br>var emb = model.predictImage(input).arrayFlatten([NAMES]);<br>emb = emb.updateMask(emb.select(0).neq(0));</pre><p><strong>Set </strong><strong>proj explicitly.</strong> A mosaic built with .median() has no native projection, and its default is a 1-degree grid: the model would receive pixels about 111 km wide and return flat squares. Anyone who runs the script needs the Vertex AI User role on the project that hosts the endpoint.</p><h3>What it costs, and when not to serve live</h3><p>Vertex AI bills each replica by the hour while the model is deployed, in 30-second increments, whether or not anyone sends a request. At peak, each of our replicas used about 1.5 vCPU and 1.7 GB of RAM, so a small machine with autoscaling is enough.</p><p><strong>1 Replica, deployed 24/7 = U$56</strong></p><p><strong>1 replica, deployed 8 h a day on 22 working days = U$14</strong></p><p><strong>6 replicas, deployed 24/7 = U$338</strong></p><p><strong>The expensive mistake is not the machine type. It is leaving the model deployed while nobody uses it, or zooming out: with the input fixed at 30 m, a continental view asks the model for every 30 m pixel on the screen. Africa alone is about 34 billion such pixels, roughly 2 million tiles, recomputed each time the map moves.</strong></p><p>So we use live inference where it shines (regional views, new mosaics, a quick look at a place nobody has processed yet) and batch processing for everything large. The batch pipeline on a single RTX 4090 handles a 10-megapixel tile in about 12 seconds, which puts a whole continent in the range of 11 GPU hours by our estimate. The result is stored as Cloud-Optimized GeoTIFFs with overviews in Cloud Storage and read by Earth Engine directly, so zooming out costs nothing on the Vertex side.</p><h3>What comes next</h3><p>The model is live and the recipe is stable. The questions we care about now are about the embeddings themselves:</p><ul><li>How much labelling do they save? We want accuracy curves against the number of training samples, task by task.</li><li>How do they compare with the AlphaEarth embeddings on the same tasks, where the two overlap in time?</li><li>How well do they transfer to countries the model never saw during training?</li></ul><p>If you serve your own TensorFlow model to Earth Engine, the short version of this post is: send uint8, decode web-safe base64 inside the graph, remember that the overlap is per side, declare no gRPC port, and read the model straight from your bucket. Questions and comparisons are welcome in the comments.</p><h3>Sources</h3><ul><li><a href="https://developers.google.com/earth-engine/apidocs/ee-model-fromvertexai">ee.Model.fromVertexAi</a> and <a href="https://developers.google.com/earth-engine/guides/ee-vertex-image-predictions">Image predictions</a>, Earth Engine documentation</li><li><a href="https://developers.google.com/earth-engine/guides/ee-vertex-payload-formats">Hosted model payload formats</a>, Earth Engine documentation</li><li><a href="https://developers.google.com/earth-engine/datasets/catalog/GOOGLE_SATELLITE_EMBEDDING_V1_ANNUAL">Satellite Embedding V1 (AlphaEarth Foundations)</a>, Earth Engine Data Catalog</li><li><a href="https://docs.cloud.google.com/vertex-ai/docs/predictions/pre-built-containers">Prebuilt containers for inference</a> and <a href="https://docs.cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements">Custom container requirements</a>, Vertex AI documentation</li><li><a href="https://cloud.google.com/vertex-ai/pricing">Vertex AI pricing</a>, consulted November 2026</li><li>Olofsson, P. et al. (2014). Good practices for estimating area and assessing accuracy of land change. <em>Remote Sensing of Environment</em>, 148, 42–57.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98966705c5f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACT V — The Data Factory: Synthetic Data, Distillation, and Micro-RAG]]></title>
            <link>https://medium.com/@luizcf14/act-v-the-data-factory-synthetic-data-distillation-and-micro-rag-832016613a5d?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/832016613a5d</guid>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 19:04:22 GMT</pubDate>
            <atom:updated>2026-11-20T19:04:22.067Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to turn a small Transformer into a reliable domain-specific agent using synthetic data, teacher-generated examples, and an offline knowledge base.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jE79JERH-vjpYouDAAcM_Q.png" /></figure><p>A 6.59-million-parameter Transformer is an interesting engineering achievement. But architecture alone does not make a useful assistant.</p><p>A model can have an efficient attention mechanism, a carefully optimized memory footprint, and a fast inference engine — and still fail at its actual job.</p><p>It may misunderstand colloquial language, produce invalid commands, confuse a request with a question, or invent information that was never part of its training.</p><p>For an embedded agent, these are not merely language-model problems. They are system reliability problems.</p><p>Imagine an ESP32-S3 controlling a fan, an LED, and a relay. The user says:</p><blockquote>“Tá muito abafado aqui, liga o vento forte.”</blockquote><p>The model must understand the informal request, interpret the current sensor readings, and produce a valid structured action.</p><p>Now consider a different request:</p><blockquote>“Faz um Pix de 100 reais agora.”</blockquote><p>The correct response is not a creative guess. The agent must recognize that the request is outside its capabilities and refuse without activating any hardware.</p><p>This is the central idea of this ACT V: <strong>we do not need a miniature general-purpose chatbot. We need a specialized model that performs a narrow set of tasks reliably.</strong></p><p>To achieve that, the module builds a data factory around three complementary components:</p><ol><li>Synthetic data generation and validation.</li><li>Answer-Only Supervised Fine-Tuning (SFT) combined with Quantization-Aware Training (QAT).</li><li>Micro-RAG: a compact, offline knowledge base stored separately from the model weights.</li></ol><h3>1. The division of labor: model knowledge versus external memory</h3><p>One of the most important design decisions in a small language model is deciding what should live inside its parameters.</p><p>A general-purpose model attempts to encode a broad range of linguistic patterns and factual associations in its weights. That approach is expensive when the available parameter budget is only a few million.</p><p>For a specialized embedded agent, we can divide responsibilities more deliberately.</p><p><strong>What the model learns:</strong></p><ul><li>Understand informal user requests.</li><li>Interpret structured sensor context.</li><li>Recognize the supported actions.</li><li>Generate valid command sequences.</li><li>Produce concise responses.</li><li>Refuse requests outside its domain.</li></ul><p><strong>What external memory provides:</strong></p><ul><li>Emergency procedures.</li><li>Technical reference information.</li><li>Instructions that may need to be updated.</li><li>Facts that are too extensive or specific to encode reliably in a small model.</li></ul><p>This distinction is fundamental.</p><p>The model learns how to interpret and respond. The retrieval system provides information that the model should not be expected to memorize.</p><p>The architecture therefore combines a small neural model with a separate knowledge base stored in Flash.</p><h3>2. Two applications, one specialized model</h3><p>The module organizes the problem around two practical use cases.</p><h3>Track A — The IoT Agent</h3><p>The first application is an autonomous home-automation agent.</p><p>The model receives two inputs:</p><ul><li>A structured representation of the current environment.</li><li>A natural-language request from the user.</li></ul><p>For example:</p><pre>&lt;|bos|&gt;<br>&lt;|ctx|&gt;temp=31C;luz=20%;fan=0;led=off;relay=0<br>&lt;|user|&gt;tá muito abafado aqui, liga o vento forte<br>&lt;|act|&gt;FAN=100<br>&lt;|assistant|&gt;Ventilador ligado em 100% (temperatura em 31°C).<br>&lt;|eos|&gt;</pre><p>Notice that the model does not simply generate a conversational answer.</p><p>It must produce a structured action between &lt;|act|&gt; and &lt;|assistant|&gt;.</p><p>The allowed action vocabulary is deliberately restricted:</p><ul><li>FAN=0, FAN=50, or FAN=100</li><li>LED=OFF, LED=WARM, LED=COOL, or LED=ALERT</li><li>RELAY=0 or RELAY=1</li><li>NONE for requests that should not trigger an action</li></ul><p>Multiple actions can be combined using semicolons.</p><p>This constrained output space makes the task much more manageable than unrestricted text generation.</p><p>It also makes evaluation more objective: we can compare the predicted action with the expected action exactly.</p><h3>Track B — The Offline Emergency Copilot</h3><p>The second application expands the system beyond home automation.</p><p>It introduces a compact knowledge base containing technical information about emergency response and field situations.</p><p>The supplied knowledge base includes topics such as:</p><ul><li>Convulsions and first aid.</li><li>Drowning.</li><li>Snake bites.</li><li>Floods and landslides.</li><li>Post-flood cleaning and leptospirosis.</li><li>Emergency water purification.</li><li>Kitchen oil fires.</li><li>Burns and bleeding.</li><li>Emergency power sources.</li><li>Homemade oral rehydration solution.</li></ul><p>These documents are not embedded in the model’s weights. Instead, they are compiled into a separate binary knowledge base.</p><p>When a user asks a question, the system retrieves a relevant document and injects its content into the model’s context using the &lt;|ctx|&gt; token.</p><p>This is the foundation of Micro-RAG.</p><h3>3. Building a synthetic data factory</h3><p>The first practical component is lab01_gerar_dataset_sintetico.py.</p><p>Its purpose is to generate training examples that cover the language and situations expected from the embedded agent.</p><p>The script produces two datasets:</p><ul><li>dataset_sft.jsonl: training examples.</li><li>dataset_eval.jsonl: examples reserved for evaluation.</li></ul><p>Each record follows a simple JSON structure:</p><pre>{<br>  &quot;ctx&quot;: &quot;temp=31C;luz=20%;fan=0;led=off;relay=0&quot;,<br>  &quot;user&quot;: &quot;tá muito abafado aqui, liga o vento forte&quot;,<br>  &quot;act&quot;: &quot;FAN=100&quot;,<br>  &quot;assistant&quot;: &quot;Ventilador ligado em 100% (31°C).&quot;<br>}</pre><p>The four fields have distinct responsibilities:</p><ul><li>ctx: the current sensor or retrieved-information context.</li><li>user: the natural-language request.</li><li>act: the structured action expected from the model.</li><li>assistant: the natural-language response.</li></ul><p>This separation is important. The model must learn not only what to say, but also which structured action corresponds to the request.</p><h3>Why synthetic data?</h3><p>A small model cannot rely on enormous internet-scale datasets to learn the behavior of a specialized application.</p><p>Instead, we can generate examples around the exact domain we want to support.</p><p>For the IoT agent, that means producing variations of requests involving temperature, lighting, ventilation, and relays.</p><p>The dataset includes informal Brazilian Portuguese expressions such as:</p><ul><li>“vc”</li><li>“tá”</li><li>“mto”</li><li>“aki”</li><li>“bota o vento no médio”</li><li>“corta a ventilação agora”</li></ul><p>The objective is to expose the model to different ways of expressing the same intent.</p><p>The generator also creates examples with different sensor contexts. A request such as “como está o ambiente?” should not always produce the same action. The correct response depends on the temperature and current state.</p><p>This is a small but important step toward context-dependent behavior.</p><h3>Safe refusals are part of the training data</h3><p>A specialized agent must learn when not to act.</p><p>The synthetic data therefore includes requests outside the supported domain, such as financial transactions or questions about bank passwords.</p><p>These examples use:</p><pre>&lt;|act|&gt;NONE</pre><p>The generator’s teacher prompt requests approximately 20% safe refusals.</p><p>This is not just a conversational preference. It is part of the action policy.</p><p>A model that generates plausible language but activates a relay in response to an unrelated request is not a reliable embedded agent.</p><h3>4. Validation before training</h3><p>Synthetic data is only useful if it is valid.</p><p>The module includes automatic validation before the training stage.</p><p>The action validator checks that generated commands follow the supported syntax.</p><p>For example, these are valid:</p><pre>FAN=100<br>LED=WARM<br>LED=WARM;FAN=50<br>RELAY=0<br>NONE</pre><p>An unsupported action or malformed command should not enter the training dataset.</p><p>The generator also checks the tokenized sequence against the configured BPE budget.</p><p>The teacher prompt specifies a maximum of 120 BPE tokens per complete record.</p><p>This connects the data factory directly to the tokenizer developed in Act III and the Transformer architecture introduced in Act IV.</p><p>The dataset must fit the model’s actual input constraints. Generating examples that cannot be processed by the target architecture would only create unnecessary training problems.</p><h3>Keeping evaluation data separate</h3><p>The script defines a separate evaluation set containing 24 examples, including scenarios intended to anticipate the final project in Module 6.</p><p>The training generator checks the evaluation keys before adding examples to the training set.</p><p>It also creates accent-stripped variations of training requests, increasing the diversity of written forms without duplicating the held-out evaluation prompts.</p><p>This separation matters because measuring performance on examples already seen during training would produce an overly optimistic result.</p><p>The evaluation set includes ordinary actions, combined actions, environmental questions, and requests that must be refused.</p><p>It also includes questions that receive retrieved emergency information through the context field.</p><h3>5. Teacher models: using a larger model to teach a smaller one</h3><p>The data factory includes a TEACHER_PROMPT_TEMPLATE.</p><p>It is designed to be used with a larger language model to generate additional examples in the same JSONL format.</p><p>The teacher receives strict instructions about:</p><ul><li>The supported action vocabulary.</li><li>The expected JSON fields.</li><li>Colloquial Portuguese variations.</li><li>The proportion of safe refusals.</li><li>The maximum BPE token budget.</li></ul><p>The larger model acts as a data-generation tool, not as the runtime intelligence of the embedded device.</p><p>This distinction is important.</p><p>The teacher can help produce a broader collection of linguistic variations, but its output still needs to pass the local validation pipeline.</p><p>A teacher model can generate an invalid command, an inconsistent sensor context, or an unsafe response. The data factory must reject those examples rather than blindly trusting generated content.</p><p>The resulting workflow is:</p><pre>Teacher LLM<br>    |<br>    v<br>Synthetic examples<br>    |<br>    v<br>Schema and action validation<br>    |<br>    v<br>BPE token budget validation<br>    |<br>    v<br>Training dataset</pre><p>This is a practical form of knowledge distillation: a larger model helps create examples that teach a smaller model how to behave within a specific domain.</p><p>The goal is not to transfer all the knowledge of the teacher. It is to transfer a carefully selected behavioral capability.</p><h3>6. Answer-Only SFT: teaching the model what to predict</h3><p>Once the dataset is ready, the next step is training.</p><p>The module uses Answer-Only Supervised Fine-Tuning (SFT).</p><p>The training sequence contains the context, user message, action, and assistant response. However, the loss is applied only to the completion portion.</p><p>In other words, the model receives the full prompt as input, but the prompt tokens are masked out of the training objective.</p><p>The implementation uses -100 as the ignored target value in the cross-entropy loss.</p><p>Conceptually:</p><pre>Input:<br>&lt;|ctx|&gt;sensor data<br>&lt;|user|&gt;user request<br>&lt;|act|&gt;FAN=100<br>&lt;|assistant|&gt;Ventilator activated.</pre><pre>Training targets:<br>- Context tokens: ignored<br>- User tokens: ignored<br>- Action tokens: predicted<br>- Assistant response tokens: predicted</pre><p>This is implemented in make_sft_sample().</p><p>The function tokenizes the prompt and completion separately, combines them, and masks the target positions corresponding to the prompt.</p><p>The training loop then calculates cross-entropy using:</p><pre>loss = F.cross_entropy(<br>    logits.view(-1, cfg.vocab_size),<br>    y_t.view(-1),<br>    ignore_index=-100<br>)</pre><p>This makes the optimization focus on the behavior we want the model to generate.</p><p>The model learns to continue the sequence with the correct action and response, conditioned on the sensor context and user request.</p><h3>7. Combining SFT with Quantization-Aware Training</h3><p>The model is not trained only in full precision and quantized afterward.</p><p>The module integrates QAT into the training forward pass.</p><p>The model is called with:</p><pre>logits = model(x_t, qat=True)</pre><p>This simulates the numerical behavior of the quantized representation during training.</p><p>The training script supports two configurations:</p><ul><li>int8 quantization.</li><li>Q4_0 hybrid quantization, enabled with --q4.</li></ul><p>The optimizer is AdamW, with gradient clipping and a learning-rate schedule that includes warmup followed by cosine decay.</p><p>The default training configuration uses:</p><ul><li>35 epochs.</li><li>Batch size of 64.</li><li>Learning rate of 0.0025.</li><li>Weight decay of 0.01.</li><li>Gradient clipping at 1.0.</li></ul><p>The model uses the BPE tokenizer and the TNY3 architecture from the previous modules.</p><p>After training, the script exports the model as:</p><pre>out/tny3_agent.bin</pre><p>This is the artifact intended for the quantized inference pipeline.</p><h3>8. Micro-RAG: a knowledge base without a vector database</h3><p>The second major component of the module is rag_builder.py.</p><p>Traditional Retrieval-Augmented Generation systems often rely on embedding models, vector databases, and similarity search.</p><p>Those components can be useful, but they introduce additional memory, computation, and software dependencies.</p><p>For a small offline system, we can start with something much simpler.</p><p>The Micro-RAG implementation uses lexical retrieval.</p><p>It searches for meaningful terms in the user’s question and compares them with the keywords and content of the available documents.</p><p>The knowledge base is compiled from:</p><pre>data/fichas_emergencia_rag.txt</pre><p>Each line follows a four-field structure:</p><pre>document_id | title | keywords | content</pre><p>For example:</p><pre>afogamento_socorro |<br>Afogamento: primeiros socorros |<br>afogamento afogando piscina rio mar respirar rcp |<br>Retire a vítima sem entrar na correnteza...</pre><p>The builder reads the source file, normalizes the search terms, and stores the title, normalized keywords, and document body in a binary data pool.</p><p>The resulting binary begins with the identifier:</p><pre>RAG1</pre><p>The file contains:</p><ul><li>An 8-byte header.</li><li>A fixed-size entry table.</li><li>A string pool containing titles, keywords, and document bodies.</li></ul><p>Each document entry occupies 20 bytes.</p><p>The string pool is padded to a 4-byte boundary, and the complete binary is also aligned to 4 bytes.</p><p>This is a compact and deterministic format. The embedded system does not need to parse a large JSON document or load a vector database.</p><h3>9. Lexical retrieval with IDF</h3><p>The retrieval function is called search_rag().</p><p>It starts by normalizing the user query:</p><ol><li>Convert text to lowercase.</li><li>Remove accents.</li><li>Replace punctuation with spaces.</li><li>Remove stopwords.</li><li>Ignore terms shorter than three characters.</li></ol><p>The implementation uses a Portuguese stopword list.</p><p>It then scores each document according to the overlap between the query terms and the document’s keywords and body.</p><p>The scoring strategy uses inverse document frequency (IDF).</p><p>In simplified terms, a term that appears in many documents is less informative than a term that appears in only a few.</p><p>The implementation calculates:</p><pre>IDF = log((number_of_documents + 1) / (document_frequency + 0.5)) + 0.5</pre><p>Keyword matches receive a higher score than matches in the document body.</p><p>The scoring weights are:</p><ul><li>Exact keyword match: 4.0 × IDF</li><li>Partial keyword-prefix match: 2.5 × IDF</li><li>Body match: 1.0 × IDF</li></ul><p>The implementation also supports a simple form of follow-up context through last_topic.</p><p>If the current query contains no usable terms, the previous topic can provide the search terms.</p><p>For example:</p><p>First question:</p><blockquote>“Ele engoliu muita água na piscina e está tossindo.”</blockquote><p>Follow-up:</p><blockquote>“E o que não devo fazer?”</blockquote><p>The second question is ambiguous on its own. The previous topic, afogamento, allows the retrieval system to search the relevant document again.</p><p>This is a small mechanism, but it addresses an important property of real conversations: users rarely repeat the entire context in every message.</p><p>A document is returned only when its score reaches the configured threshold of 2.5. Otherwise, the search returns no match.</p><p>This threshold is particularly important for domain restriction. A question such as “Qual a cotação do dólar hoje?” should not retrieve an unrelated emergency document.</p><h3>10. Compiling the knowledge base</h3><p>The RAG builder generates:</p><pre>out/rag_kb.bin</pre><p>This binary is designed to occupy the dedicated 4 MB rag_kb partition introduced in Act IV.</p><p>The compilation process is straightforward:</p><pre>python curso/modulo-05-fabrica-dados-destilacao/rag_builder.py</pre><p>The script builds the binary and executes five retrieval tests:</p><ol><li>A drowning-related question.</li><li>A follow-up question using the previous topic.</li><li>A kitchen oil-fire question.</li><li>An emergency water-purification question.</li><li>An out-of-domain question about the dollar exchange rate.</li></ol><p>The first four should retrieve the expected documents. The final query should produce no match.</p><p>The script also measures retrieval time in microseconds.</p><p>That measurement is useful for understanding the cost of lexical retrieval, although the actual timing depends on the machine running the script. It should not be interpreted as a guaranteed ESP32-S3 benchmark.</p><p>The important architectural property is that the retrieval algorithm does not require a neural embedding model or a vector database.</p><h3>11. Bringing the data factory together</h3><p>The module provides three scripts that form the complete practical workflow.</p><p>Run them from the repository root.</p><p><strong>Step 1 — Generate and validate the datasets</strong></p><pre>python curso/modulo-05-fabrica-dados-destilacao/lab01_gerar_dataset_sintetico.py</pre><p>This generates:</p><pre>out/dataset_sft.jsonl<br>out/dataset_eval.jsonl</pre><p><strong>Step 2 — Compile the Micro-RAG knowledge base</strong></p><pre>python curso/modulo-05-fabrica-dados-destilacao/rag_builder.py</pre><p>This generates:</p><pre>out/rag_kb.bin</pre><p><strong>Step 3 — Train and evaluate the TNY3 specialist</strong></p><pre>python curso/modulo-05-fabrica-dados-destilacao/lab03_treinar_e_avaliar_tny3.py</pre><p>For the hybrid 4-bit configuration:</p><pre>python curso/modulo-05-fabrica-dados-destilacao/lab03_treinar_e_avaliar_tny3.py --q4</pre><p>For the full hardware preset:</p><pre>python curso/modulo-05-fabrica-dados-destilacao/lab03_treinar_e_avaliar_tny3.py --preset full_s3</pre><p>The training script exports tny3_agent.bin and evaluates the quantized model against the held-out prompts.</p><p>The evaluation extracts the generated action and assistant response, then calculates three metrics.</p><p><strong>Action Exact Match</strong></p><p>The percentage of predictions whose structured action exactly matches the expected action.</p><p><strong>Safe Refusal Rate</strong></p><p>The percentage of expected NONE cases where the model correctly refuses to act.</p><p>The script also counts false actuations: cases in which a request that should have been refused produces an action instead.</p><p><strong>Valid Formatting</strong></p><p>The percentage of outputs that follow the expected structure, with &lt;|act|&gt; appearing before &lt;|assistant|&gt; and a syntactically valid action.</p><p>The module defines the following target criteria for the evaluation set:</p><ul><li>Action Exact Match: at least 90%.</li><li>Safe Refusal Rate: at least 95%.</li><li>Valid formatting: 100%.</li></ul><p>These are acceptance targets for the lab, not results that should be assumed without running the experiment.</p><h3>12. The cost of hallucination in physical systems</h3><p>There is a deeper lesson behind this module.</p><p>In a conventional chatbot, a hallucinated answer can mislead a user. In an embedded agent, a hallucinated action can change the physical environment.</p><p>That changes how we should evaluate the model.</p><p>A response can be grammatically correct and still be operationally wrong.</p><p>For example, if the user asks for a financial transaction, the model should not produce a relay command simply because it has learned that requests often lead to actions.</p><p>This is why the module explicitly includes safe refusals and measures false actuations.</p><p>It also suggests an important engineering principle: model output should never be treated as unrestricted hardware authority.</p><p>The action vocabulary should be constrained, the output should be validated, and the device firmware should retain responsibility for deciding whether a command can actually be executed.</p><p>The model is a component in the control system, not the entire safety mechanism.</p><p>Similarly, Micro-RAG should be understood as a retrieval mechanism, not an independent guarantee that retrieved information is correct or safe. The supplied emergency reference documents are compact educational material; critical real-world decisions still require validated procedures and appropriate emergency services.</p><h3>13. What we achieved — and what comes next</h3><p>Module 5 changes the problem from building a small language model to building a specialized embedded intelligence system.</p><p>We now have three complementary pieces:</p><ul><li>A synthetic data factory that generates domain-specific examples and validates their structure.</li><li>A training pipeline that combines Answer-Only SFT with Quantization-Aware Training.</li><li>A compact Micro-RAG knowledge base that stores retrievable information separately from the model parameters.</li></ul><p>The model is no longer expected to memorize every fact or handle every possible request.</p><p>Instead, it learns a limited set of behaviors and uses external context when it needs specific information.</p><p>This separation is especially valuable for embedded systems, where memory, storage, and computational resources are tightly constrained.</p><p>It also creates a more maintainable system. The neural model can remain focused on interpreting requests and producing structured outputs, while the knowledge base can be updated independently.</p><p>But we still have one major challenge.</p><p>A trained model and a binary knowledge base do not automatically make an autonomous physical agent. We need to connect inference, retrieval, hardware interfaces, and execution into one coherent system.</p><p>That is the final step.</p><p>In Act VI, we will bring everything together: SIMD optimization, dual-core execution, the embedded agent, and the transition from language generation to physical interaction.</p><p><strong>The goal is not to fit the entire world into a microcontroller. It is to give a small model exactly the knowledge, tools, and boundaries it needs to act reliably within its world.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832016613a5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACT IV — Modern Transformer Architecture for the ESP32-S3.]]></title>
            <link>https://medium.com/@luizcf14/act-iv-modern-transformer-architecture-for-the-esp32-s3-bc600b14dc75?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc600b14dc75</guid>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 18:57:43 GMT</pubDate>
            <atom:updated>2026-11-20T18:57:43.645Z</atom:updated>
            <content:encoded><![CDATA[<p><em>RoPE, Grouped-Query Attention, SwiGLU, and hybrid quantization: redesigning the Transformer around the memory constraints of a microcontroller.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PcM2UIFZgavQ-9Sv06ouQ.png" /></figure><p>A modern Transformer does not have to be enormous. But making one run on a microcontroller requires more than shrinking its dimensions or quantizing its weights. It requires reconsidering how the architecture uses memory, how information is represented across attention heads, and how model parameters are stored and accessed at inference time.</p><p>In the previous acts, we built the foundations: a neural model, its inference engine, and a tokenizer capable of representing Portuguese text efficiently. Now we can bring those pieces together in a more ambitious architecture.</p><p>This is the goal of <strong>TNY3-S3</strong>: an approximately 6.59-million-parameter Transformer designed around the constraints of the ESP32-S3, with a 16 MB Flash device and hardware configurations ranging from no external PSRAM to 8 MB of PSRAM.</p><p>The architecture combines four important ideas:</p><ul><li>Rotary Positional Embeddings (RoPE)</li><li>Grouped-Query Attention (GQA)</li><li>SwiGLU feed-forward networks</li><li>Hybrid quantization using int8 and Q4_0</li></ul><p>But the architectural changes are only half the story. We will also look at how to place the model in a dedicated Flash partition and map its weights directly into the processor’s address space, without copying the entire model into SRAM.</p><h3>1. The architecture must fit the hardware</h3><p>A conventional Transformer can become expensive on a microcontroller for several reasons.</p><p>The model weights consume Flash or RAM, depending on how they are loaded. The attention mechanism requires a Key-Value cache that grows with the context length. Intermediate activations need working memory. And every operation must be implemented efficiently enough to run on a processor that does not have the resources of a desktop GPU.</p><p>TNY3-S3 addresses these constraints at the architectural level.</p><p>The complete preset uses:</p><ul><li>Vocabulary: 4,096 tokens</li><li>Context length: 256 tokens</li><li>Embedding dimension: 256</li><li>Transformer layers: 8</li><li>Query heads: 8</li><li>Key-Value heads: 2</li><li>SwiGLU hidden dimension: 688</li><li>Positional encoding: RoPE</li><li>Output projection: tied to the token embedding matrix</li></ul><p>This configuration contains <strong>6,590,720 trainable parameters</strong>.</p><p>The central design principle is that memory efficiency should not be treated as a final optimization step. It should influence the architecture from the beginning.</p><h3>2. RoPE: positional information without a learned position table</h3><p>Transformers need a way to represent token positions. Without positional information, attention alone does not tell the model whether a token appeared at the beginning or the end of a sequence.</p><p>A straightforward approach is to add a learned positional embedding to each token representation. This introduces another position-dependent parameter table and ties the representation to the configured context length.</p><p>TNY3-S3 uses <strong>Rotary Positional Embeddings (RoPE)</strong> instead.</p><p>RoPE applies a rotation to pairs of coordinates in the Query and Key vectors. For each pair, the transformation is:</p><p><strong><em>x0_new = x0 * cos(theta) — x1 * sin(theta)</em></strong></p><p><strong><em>x1_new = x0 * sin(theta) + x1 * cos(theta)</em></strong></p><p>The rotation angle depends on the token position and the coordinate pair.</p><p>In the implementation, the frequencies are calculated from the configured context length, head dimension, and rope_theta parameter. The cosine and sine values are prepared in advance and applied to Query and Key tensors.</p><p>There is no learned positional embedding matrix to store.</p><p>This is particularly useful in a constrained environment: <strong>positional information is introduced through a deterministic transformation rather than another set of trainable weights.</strong></p><p>It is important to note that RoPE does not eliminate all positional computation. The rotations still need to be applied during inference. What it removes is the need for a learned position table.</p><h3>3. GQA: reducing the memory cost of attention</h3><p>The next architectural decision concerns attention.</p><p>In standard Multi-Head Attention (MHA), each query head has its own Key and Value head. This means that the KV cache stores a separate Key and Value representation for every attention head and every token in the context.</p><p>For a small device, this can become a significant memory cost.</p><p>TNY3-S3 uses <strong>Grouped-Query Attention (GQA)</strong>.</p><p>Instead of assigning one Key-Value head to every Query head, multiple Query heads share the same Key-Value head.</p><p>The full preset uses:</p><ul><li>8 Query heads</li><li>2 Key-Value heads</li><li>4 Query heads per Key-Value head</li></ul><p>This reduces the number of stored Key and Value representations.</p><p>For the same layer count, context length, and head dimension, the KV cache estimate in the module’s implementation is:</p><p><strong><em>M_KV = L * CTX * 2 * (D_KV + 4)</em></strong></p><p>Here, (L) is the number of layers, (CTX) is the context length, and (D_{KV}) is the combined dimension of the Key-Value heads. The additional four bytes account for the float32 scale associated with each stored vector.</p><p>With the full TNY3-S3 configuration, the difference is substantial.</p><p>At a context length of 256 tokens:</p><ul><li>With 8 Key-Value heads, the estimated cache is approximately 1.04 MB.</li><li>With 2 Key-Value heads, it falls to approximately 272 KB.</li></ul><p>That is roughly a <strong>fourfold reduction</strong>.</p><p>This is one of the most important architectural decisions in the project. It makes a context length of 256 much more realistic for an ESP32-S3 without external PSRAM.</p><p>When PSRAM is available, the system can allocate a larger cache and increase the context length. The hardware demonstration explores this adaptive strategy with contexts of 512 tokens.</p><p>GQA is not simply a compression trick. It changes the relationship between query and memory representations, allowing the model to use fewer stored Key-Value vectors while retaining multiple Query heads.</p><h3>4. SwiGLU: a more expressive feed-forward network</h3><p>After attention, each Transformer block applies a feed-forward network.</p><p>A conventional feed-forward network uses two linear projections with a nonlinear activation between them. TNY3-S3 uses <strong>SwiGLU</strong>, a gated architecture that combines two projections.</p><p>The operation can be expressed as:</p><p><strong><em>SwiGLU(x) = SiLU(x * W_gate) * (x * W_up)</em></strong></p><p>The result is then projected back to the model dimension:</p><p><strong><em>FFN(x) = SwiGLU(x) * W_down</em></strong></p><p>The gate controls which information flows through the feed-forward block. This provides a more expressive transformation than a simple activation between two linear layers.</p><p>The TNY3-S3 preset uses a hidden dimension of 688.</p><p>This value is not arbitrary. The implementation validates that the hidden dimension is a multiple of 16, matching the alignment requirements adopted for the ESP32-S3 vectorized execution path developed in the next module.</p><p>The architecture is therefore designed with both model capacity and future kernel implementation in mind.</p><h3>5. Weight tying: sharing the embedding matrix</h3><p>A language model needs an embedding matrix to convert token IDs into vectors.</p><p>It also needs an output projection to convert the final hidden representation into vocabulary logits.</p><p>A common design uses separate matrices for these two operations. TNY3-S3 uses <strong>weight tying</strong>: the same embedding matrix is shared by the input embedding and the output classification projection.</p><p>For a vocabulary of 4,096 tokens and an embedding dimension of 256, the matrix contains: <strong>4096 * 256 = 1,048,576 parameters</strong></p><p>Sharing this matrix avoids storing a second matrix of the same size.</p><p>There is also a practical reason to preserve this matrix in int8, even when the rest of the model uses 4-bit quantization: it participates in both token lookup and vocabulary projection. The module adopts a hybrid format that keeps embeddings in int8 while allowing the other large weight matrices to use <strong>Q4_0</strong>.</p><p>This is a deliberate trade-off between memory savings and numerical behavior.</p><h3>6. Quantization: int8 versus Q4_0</h3><p>Quantization reduces the number of bits used to represent model weights.</p><p>The TNY3 implementation supports two modes:</p><p><strong>int8, per row</strong></p><p>Each row is represented using signed 8-bit integers and a float32 scale. The scale is calculated from the maximum absolute value in that row:</p><p><strong><em>scale = max(abs(weights)) / 127</em></strong></p><p>The quantized values are obtained by dividing by the scale, rounding, and clipping to the range [-127, 127].</p><p>This representation is straightforward and relatively inexpensive to decode.</p><p><strong>Q4_0, blocks of 32 weights</strong></p><p>The Q4_0 format divides each row into blocks of 32 weights.</p><p>Each block stores:</p><blockquote><strong>4 bytes for a float32 scale + 16 bytes for the packed 4-bit values.</strong></blockquote><p>That means each block occupies 20 bytes.</p><p>The quantized values use a symmetric range from -7 to +7. Each value is shifted by 8 before being packed into a 4-bit nibble.</p><p>The result is a compact representation that reduces the storage required by the large attention and feed-forward matrices.</p><h3>Why not quantize everything to 4 bits?</h3><p>The TNY3 implementation uses a hybrid strategy:</p><ul><li>Embeddings remain int8.</li><li>Attention matrices use the selected quantization mode.</li><li>SwiGLU matrices use the selected quantization mode.</li><li>Normalization gains remain float32.</li></ul><p>This is important because quantization is not free. Reducing precision saves storage, but it also introduces approximation error. The objective is not to use the fewest bits everywhere; it is to find a representation that balances storage requirements and numerical behavior.</p><p>For the complete full_s3 preset, the estimated model sizes are:</p><p><strong>With int8:</strong></p><ul><li>Total parameters: 6,590,720</li><li>Model size: approximately 6.41 MB</li></ul><p><strong>With hybrid Q4_0:</strong></p><ul><li>Total parameters: 6,590,720</li><li>Model size: approximately 4.34 MB</li></ul><p>The embeddings remain int8 in both configurations. The Q4_0 savings come primarily from the attention and SwiGLU matrices.</p><h3>7. Quantization-Aware Training</h3><p>Quantization can be applied after training, but this may introduce a mismatch between the numerical behavior seen during training and the representation used during inference.</p><p>TNY3 includes <strong>Quantization-Aware Training (QAT)</strong> using a Straight-Through Estimator (STE).</p><p>During the forward pass, weights are quantized and dequantized to simulate the lower-precision representation. During backpropagation, the STE allows gradients to pass through the quantization operation as an approximation.</p><p>The implementation provides two paths:</p><ul><li>ste_int8() simulates row-wise int8 quantization.</li><li>ste_q4_0() simulates block-wise 4-bit quantization using blocks of 32 weights.</li></ul><p>The embedding matrix always follows the int8 path.</p><p>The practical lab validates the exported model against a quantized runner. It compares the output logits produced by the PyTorch implementation and the runner for the same prompt.</p><p>The validation checks:</p><ul><li>Cosine similarity between the output logits</li><li>Maximum absolute difference</li><li>Whether both implementations select the same highest-scoring token</li></ul><p>The lab requires cosine similarity above 0.999.</p><p>This is a numerical parity test between implementations. It does not, by itself, demonstrate language quality or prove that a model has learned a useful task. Those questions require training and task-specific evaluation.</p><h3>8. TNY3: a binary format designed for deployment</h3><p>A model that works in PyTorch is not yet a model that can be deployed on a microcontroller.</p><p>The exported representation must describe the architecture, quantization mode, tensor dimensions, and weight data in a deterministic layout that the embedded runtime can read.</p><p>TNY3 uses a binary format with a 32-byte header.</p><p>The header contains:</p><ul><li>Magic identifier: TNY3</li><li>Format version</li><li>Quantization mode</li><li>Vocabulary size</li><li>Context length</li><li>Model dimension</li><li>Number of layers</li><li>Query-head count</li><li>Key-Value-head count</li><li>Hidden dimension</li><li>RoPE theta</li><li>Total binary size</li></ul><p>After the header, the binary stores the embedding matrix, normalization gains, attention matrices, and SwiGLU matrices in a fixed order.</p><p>The format is aligned to 4-byte boundaries. The exporter validates the resulting binary before writing it to disk.</p><p>This explicit layout matters because the embedded runtime does not need to understand Python objects, PyTorch checkpoints, or dynamic tensor metadata. It only needs to interpret the header and read the parameter blocks in the expected order.</p><p>The module’s QuantizedTny3Runner provides a reference implementation for loading this binary and executing autoregressive inference one token at a time.</p><h3>9. From model files to a dedicated Flash partition</h3><p>The next challenge is storage.</p><p>A common embedded deployment approach is to convert model weights into a C header and compile them into the firmware. This is convenient for small models, but it couples the firmware and the model.</p><p>Every model update requires rebuilding and reflashing the application.</p><p>TNY3-S3 takes a different approach.</p><p>The 16 MB Flash is divided into dedicated partitions. The partition table reserves:</p><ul><li>2.5 MB for the application (app0)</li><li>8 MB for the neural model (model_bin)</li><li>4 MB for the retrieval knowledge base (rag_kb)</li><li>Approximately 1.37 MB for SPIFFS</li><li>Additional space for metadata and crash information</li></ul><p>The model partition starts at offset 0x290000 and occupies 0x800000 bytes.</p><p>This separation allows the model to be updated independently of the firmware.</p><p>For example, a model binary can be written directly to the model partition with:</p><pre>esptool.py --chip esp32s3 write_flash 0x290000 your_model_tny3.bin</pre><p>The firmware does not need to be recompiled just because the model weights have changed.</p><p>The partition table is included in the module as partitions_s3_16mb.csv. The validation script checks that partitions do not overlap, that the relevant offsets meet the 64 KB alignment requirement, and that the layout stays within the 16 MB Flash capacity.</p><h3>10. Zero-copy model access with esp_partition_mmap()</h3><p>Separating the model from the firmware solves the update problem. But it does not solve the memory problem if the entire model still needs to be copied into RAM before inference.</p><p>The ESP32-S3 provides a mechanism to map Flash contents into its data address space: esp_partition_mmap().</p><p>Instead of copying the model into a large SRAM buffer, the firmware maps the model_bin partition and receives a pointer to the mapped region.</p><p>The hardware demonstration performs the following steps:</p><ol><li>Finds the model_bin partition using its data subtype.</li><li>Maps the partition using esp_partition_mmap().</li><li>Reads the first 32 bytes as a TNY3 header.</li><li>Checks the magic identifier.</li><li>Prints the model configuration and estimated KV cache requirements.</li><li>Releases the mapping with esp_partition_munmap().</li></ol><p>The important distinction is that mapping Flash does not mean copying the entire model into SRAM.</p><p>The processor accesses the mapped Flash region through its address space. This avoids allocating a second, model-sized RAM buffer.</p><p>It does not mean that the operation has zero system cost: the mapping uses address-space and Flash/MMU resources, and the processor still needs working memory for activations, cache, and other runtime data. But it removes the need to hold a full copy of the weights in internal SRAM.</p><p>This is a major architectural advantage for a device with only a limited amount of internal RAM.</p><h3>11. Adapting the KV cache to the hardware configuration</h3><p>The ESP32-S3 boards used in the project are not all equipped with the same memory configuration.</p><p><strong>The module considers three variants:</strong></p><ul><li><strong>N16: 16 MB Flash, no external PSRAM</strong></li><li><strong>N16R2: 16 MB Flash, 2 MB PSRAM</strong></li><li><strong>N16R8: 16 MB Flash, 8 MB PSRAM</strong></li></ul><p>The firmware checks whether PSRAM is available using psramFound().</p><p>If PSRAM is detected, the demonstration attempts to allocate the KV cache for a context length of 512 tokens using ps_malloc().</p><p>If PSRAM is not available, it attempts to allocate the cache for a context length of 256 tokens using internal malloc().</p><p>This is a simple example of hardware-aware resource allocation.</p><p>The model architecture remains the same, but the runtime can choose a different context configuration depending on the available memory.</p><p>The distinction is important: Flash stores the model weights, while SRAM and PSRAM provide working memory for inference. Mapping the weights from Flash does not eliminate the need for a KV cache.</p><h3>12. Running the practical lab</h3><p>The module includes a Python lab that validates three parts of the deployment pipeline.</p><p>First, it checks the 16 MB partition table:</p><pre>python curso/modulo-04-arquitetura-tny3-s3/lab04_arquitetura_e_particoes.py</pre><p>The default run uses the micro preset for the export and parity tests, while also printing the memory budget for the full architecture.</p><p>To validate the complete 6.59-million-parameter preset:</p><pre>python curso/modulo-04-arquitetura-tny3-s3/lab04_arquitetura_e_particoes.py --preset full_s3</pre><p>The script exports both int8 and Q4_0 binaries, loads them through the quantized runner, and compares their output logits with the PyTorch model.</p><p>The hardware demonstration is located at:</p><pre>esp32s3_mmap_tny3/esp32s3_mmap_tny3.ino</pre><p>To use the custom partition table with the Arduino IDE, copy partitions_s3_16mb.csv into the sketch directory as partitions.csv and configure the board to use that partition scheme.</p><p>The sketch then searches for model_bin and attempts to map it into the ESP32-S3 address space.</p><p>If the partition is empty, it uses a demonstration header stored in program memory to show the expected configuration and prints the command needed to upload a model.</p><h3>13. What we achieved — and what remains</h3><p>TNY3-S3 represents a shift in how we approach language models on microcontrollers.</p><p>Instead of taking a conventional Transformer and simply reducing its dimensions, we designed the architecture around the actual constraints of the target hardware.</p><p>RoPE removes the need for a learned positional embedding table. GQA reduces the memory required by the KV cache. SwiGLU provides a gated feed-forward transformation with dimensions aligned to the intended execution path. Weight tying avoids duplicating the vocabulary projection matrix. Hybrid quantization reduces the storage footprint, and Flash memory mapping makes it possible to access model weights without copying the entire model into SRAM.</p><p>Together, these decisions make a 6.59-million-parameter architecture fit within an 8 MB model partition, with an estimated binary size of approximately 4.34 MB in hybrid Q4_0 or 6.41 MB in int8.</p><p>There is an important distinction, however: fitting the model into Flash is not the same as making inference fast. The architecture and binary format establish the foundation. Efficient matrix-vector operations, activation quantization, and hardware-specific kernels are the next challenge.</p><p>That is where we go next.</p><p>In Act V, we will focus on the data factory: generating domain-specific training examples, building retrieval resources, and preparing the knowledge needed to turn this architecture into a useful specialized model.</p><p><strong>A modern Transformer on a microcontroller is not just a smaller Transformer. It is a Transformer redesigned around the memory hierarchy, numerical constraints, and execution model of the device.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc600b14dc75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACT III — Teaching an ESP32 to Understand Language: Building a BPE Tokenizer.]]></title>
            <link>https://medium.com/@luizcf14/act-iii-teaching-an-esp32-to-understand-language-building-a-bpe-tokenizer-540fdf84b46b?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/540fdf84b46b</guid>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 18:39:29 GMT</pubDate>
            <atom:updated>2026-11-20T18:39:29.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gjtfd-TDTtn13mNH" /></figure><p><em>How to teach a microcontroller to recognize meaningful pieces of Portuguese, preserve UTF-8 accents, and process language more efficiently — without relying on dynamic memory allocation.</em></p><h3>The Problem with Reading One Letter at a Time</h3><p>In the previous acts, we explored how a tiny language model is trained and how its Transformer architecture can be implemented in C. But there is a fundamental limitation in the way our original model reads language.</p><p>It reads one character at a time.</p><p>Our TNY2 model uses a vocabulary of just 97 symbols: essentially ASCII characters, plus a few control tokens. This keeps its embedding table remarkably small. However, it also means that every character consumes one position in the model’s context window.</p><p>Consider this sentence:</p><blockquote><em>A temperatura da sala está 29°C; ligar ventilação?</em></blockquote><p>A character-level model must process more than 50 individual symbols. It does not see <em>temperatura</em> or <em>ventilação</em> as meaningful units. It sees a sequence of letters that must be learned and reconstructed one by one.</p><p>That creates three problems:</p><ol><li><strong>Context waste:</strong> long words consume many positions in the context window.</li><li><strong>Poor linguistic efficiency:</strong> the model must learn spelling patterns instead of representing recurring subword units.</li><li><strong>Encoding limitations:</strong> the original ASCII-oriented pipeline removes Portuguese accents and cannot naturally represent symbols such as °.</li></ol><p>The next step is not simply to make the model larger. It is to give it a better way to represent language.</p><p>That is where Byte-Pair Encoding, or BPE, comes in.</p><h3>1. The Vocabulary Is a Hardware Design Decision</h3><p>Large language models commonly use vocabularies containing tens of thousands of tokens. Some use 32,000, 50,257, or even 128,000 entries.</p><p>On a microcontroller, however, vocabulary size has a direct hardware cost.</p><p>Every token needs an embedding vector. For a model with embedding dimension (D = 256), using int8 weights and one float32 scale per embedding row, the approximate storage cost is:</p><p><strong><em>Embedding memory</em></strong> = <strong>V * (4 + 256)</strong></p><p>Here, (V) is the vocabulary size, 256 bytes store the int8 embedding vector, and 4 bytes store its scale.</p><p>Let’s compare three possible configurations:</p><pre>Vocabulary     | Embedding storage | Approximate size<br>97 tokens      | 25,220 bytes      | 25 KB <br>4,096 tokens   | 1,064,960 bytes   | 1.01 MB<br>128,000 tokens | 33,280,000 bytes  | 31.74 MiB</pre><p>A vocabulary of 128,000 tokens would require more than twice the entire 16 MB Flash capacity of our ESP32-S3 — just for the embedding table.</p><p>At the other extreme, 97 tokens are extremely cheap, but they force the model to spend its context window spelling everything character by character.</p><p>The design target for this module is <strong>4,096 tokens</strong>.</p><p>It is a deliberate compromise: large enough to represent useful Portuguese subwords, but small enough to fit comfortably within the ESP32-S3’s Flash budget.</p><p>This is an important lesson in embedded AI: vocabulary size is not just a language-modeling hyperparameter. It is a memory-allocation decision.</p><h3>2. From Characters to Subwords</h3><p>There are three common approaches to text tokenization.</p><p><strong>Character-level tokenization</strong></p><p>Each character becomes one token.</p><p>For example:</p><p>ventilação → v, e, n, t, i, l, a, ç, ã, o</p><p>It has a small vocabulary and can represent text using a fixed character set, but sequences become long.</p><p><strong>Word-level tokenization</strong></p><p>Each complete word becomes one token.</p><p>ventilação → ventilação</p><p>This produces shorter sequences, but it creates a different problem: every new word or spelling variation may require a new vocabulary entry. Unknown words become difficult to handle.</p><p><strong>Subword tokenization</strong></p><p>BPE finds recurring sequences of bytes or characters and merges them into reusable units.</p><p>A word such as ventilação might become a single token if it occurs frequently enough in the training corpus. Less frequent words can still be represented through smaller pieces.</p><p>The result is a vocabulary that captures recurring patterns without requiring an entry for every possible word.</p><p>For a compact model, this is particularly useful. We want fewer tokens per sentence, but we cannot afford an enormous vocabulary.</p><h3>3. Why Byte-Level BPE?</h3><p>There is another challenge: Portuguese is not ASCII.</p><p>Characters such as ã, ç, é, and ô are represented by multiple bytes in UTF-8. The same is true for symbols such as ° and many other Unicode characters.</p><p>A tokenizer based only on a predefined character list can encounter symbols it does not recognize. This often leads to an unknown-token mechanism, commonly represented as &lt;unk&gt;.</p><p>Our implementation avoids that problem by starting from the complete byte range.</p><p>The vocabulary is organized into three regions:</p><pre>Token IDs |    Quantity   | Purpose |<br><br>0–15      |    16         | Special and reserved tokens |<br><br>16–271    |    256        | Raw byte tokens |<br><br>272–4095  |   Up to 3,824 | Learned BPE merges |</pre><p>The first 16 positions are reserved for control tokens and future expansion.</p><p>The next 256 entries represent every possible byte value, from 0x00 to 0xFF. Each byte is mapped to an ID by adding an offset of 16.</p><p>This gives us a crucial property:</p><p><strong>Any UTF-8 text can be represented at the byte level, even if the tokenizer has never encountered it during training.</strong></p><p>BPE then builds more efficient representations by merging recurring adjacent tokens.</p><p>The tokenizer does not need to memorize every possible word. It only needs a reliable byte-level foundation and a useful collection of learned merges.</p><h3>4. Special Tokens: Language Is More Than Text</h3><p>A tokenizer for an embedded AI system should do more than compress ordinary sentences.</p><p>It must also represent the structure of an interaction.</p><p>Our vocabulary reserves fixed IDs for seven special tokens:</p><pre>ID |      Token    |             Purpose                     |<br>0  | &lt;|pad&gt;        | Padding                                 |<br>1  | &lt;|bos|&gt;       | Beginning of sequence                   |<br>2  | &lt;|eos|&gt;       | End of response                         |<br>3  | &lt;|user|&gt;      | User message                            |<br>4  | &lt;|ctx|&gt;       | Sensor context or retrieved information |<br>5  | &lt;|act|&gt;       | Structured physical action              |<br>6  | &lt;|assistant|&gt; |    Assistant response                   |</pre><p>This distinction matters.</p><p>An embedded agent may receive a sensor reading, process a user request, and produce a command. These are not all the same kind of information.</p><p>For example:</p><pre>&lt;|bos|&gt;&lt;|ctx|&gt;temp=31C;fan=0<br>&lt;|user|&gt;tá quente<br>&lt;|act|&gt;FAN=100<br>&lt;|assistant|&gt;Ventilador ligado!<br>&lt;|eos|&gt;</pre><p>The model can learn that sensor context, user input, physical actions, and natural-language responses have different roles.</p><p>The tokenizer therefore becomes part of the system’s communication protocol, not merely a text-compression utility.</p><h3>5. Training BPE for a Specific Domain</h3><p>A generic tokenizer is not necessarily the best tokenizer for a small, specialized model.</p><p>Our implementation trains its vocabulary using a Portuguese domain corpus containing examples from two main areas:</p><ul><li>IoT automation, including sensors, temperature, ventilation, lighting, and control commands.</li><li>Civil defense, including floods, landslides, emergencies, and safety instructions.</li></ul><p>The training process starts by normalizing text to Unicode NFC and converting it to UTF-8 bytes.</p><p>It then applies deterministic pre-tokenization. This separates individual digits and punctuation while keeping a leading space attached to the following word.</p><p>For example:</p><p><strong>ventilação </strong>remains a unit that can be learned as a recurring pattern.</p><p>But a number such as <strong>29 </strong>is split into individual digits:</p><p>29 → 2, 9</p><p>Why do this?</p><p>In an embedded system, numbers often represent measurements. A temperature sensor may report 24°C today and 29°C tomorrow. We do not want the tokenizer to depend on having seen every possible numerical combination during training.</p><p>After pre-tokenization, the BPE algorithm repeatedly counts adjacent token pairs and merges the most frequent pair into a new token.</p><p>Each merge receives a new ID and a rank. The process continues until the vocabulary reaches its configured size or no eligible pair remains.</p><p>The implementation is available in: <strong>bpe_tokenizer.py</strong></p><p>The training corpus is: <strong>data/corpus_ptbr_dominio.txt</strong></p><p>The script also incorporates the project’s custom question-and-answer data.</p><p>The result is a compact, domain-oriented vocabulary with 4,096 available IDs.</p><h3>6. The Embedded Challenge: Reproducing Python in C</h3><p>Training a tokenizer on a computer is relatively straightforward.</p><p>Running the exact same tokenizer on a microcontroller is a different engineering problem.</p><p>Python can use dictionaries, dynamic lists, and flexible memory allocation. An embedded C implementation should avoid those conveniences when possible, especially when memory is limited and execution must remain predictable.</p><p>Our C implementation is designed around three principles:</p><ul><li>No heavy dynamic allocation during encoding.</li><li>Vocabulary data stored in Flash using PROGMEM.</li><li>Deterministic merge selection shared with the Python implementation.</li></ul><p>The generated vocabulary is exported in two formats:</p><ul><li>tiny_vocab.bin, using the TNYV binary format.</li><li>tiny_vocab.h, containing C-compatible arrays placed in Flash.</li></ul><p>The C header contains three main structures:</p><p><strong>Token byte pool</strong></p><p>TINY_VOCAB_POOL[] stores the byte sequences associated with tokens.</p><p><strong>Token slices</strong></p><p>TINY_VOCAB_SLICES[] stores each token&#39;s offset and length inside the byte pool.</p><p><strong>BPE merge table</strong></p><p>TINY_BPE_MERGES[] stores the left token, right token, resulting token, and merge rank.</p><p>The merge table is sorted by the pair (left, right). This allows the C implementation to use binary search when checking whether an adjacent pair can be merged.</p><p>The encoder starts by converting UTF-8 bytes into their initial token IDs. It then searches for the available adjacent pair with the lowest merge rank, applies that merge, and repeats until no more merges are possible.</p><p>The result is a sequence of uint16_t token IDs.</p><p>No Python runtime, large dictionary, or dynamic object graph is needed on the ESP32.</p><p>The implementation lives in:</p><p>esp32s3_bpe_demo/tiny_tokenizer.h</p><h3>7. UTF-8 Streaming: A Token Is Not Always a Character</h3><p>There is one more detail worth highlighting.</p><p>A token can represent multiple bytes, and a Unicode character can itself require multiple bytes.</p><p>For example, the Portuguese character ã is encoded in UTF-8 using two bytes:</p><p>0xC3 0xA3</p><p>Those bytes may arrive separately during token decoding or streaming.</p><p>If the firmware sends each byte independently to a text interface, it can accidentally split a character in the middle of its UTF-8 representation.</p><p>The module addresses this with TinyUtf8Stream.</p><p>This small stateful buffer accumulates the bytes of a multi-byte UTF-8 sequence and only emits the completed codepoint once all expected bytes have arrived.</p><p>It supports sequences of up to four bytes.</p><p>This is especially useful when generated text is sent incrementally through Server-Sent Events (SSE). The tokenizer can produce tokens one at a time while the streaming layer ensures that the output remains valid UTF-8.</p><p>It is a small component, but it illustrates an important principle: language-model inference does not end when the neural network produces a token. The surrounding software must also handle the representation correctly.</p><h3>8. The Laboratory: Proving Python and C Are Identical</h3><p>The practical lab brings the complete pipeline together.</p><p>From the repository root, run:</p><pre>python curso/modulo-03-tokenizador-bpe-embarcado/lab03_paridade_bpe.py</pre><p>The script performs four main operations:</p><ol><li>Loads the Portuguese domain corpus and custom question-and-answer data.</li><li>Trains the BPE tokenizer with a vocabulary size of 4,096.</li><li>Exports the TNYV binary vocabulary and the C header.</li><li>Validates the generated C representation against the Python implementation.</li></ol><p>The most important part is the parity test.</p><p>The lab checks 55 sentences, including:</p><ul><li>Accented Portuguese words.</li><li>Temperature readings such as 29°C.</li><li>Percentages, voltages, and sensor measurements.</li><li>Punctuation and multiple spaces.</li><li>Special control tokens.</li><li>Newlines and tabs.</li><li>Commands and natural-language questions.</li></ul><p>For every sentence, it verifies that the token IDs generated by Python, the reloaded binary vocabulary, and the C simulation are identical.</p><p>It also verifies that decoding reconstructs the original NFC-normalized text.</p><p>The expected result is:</p><p><strong>55 out of 55 sentences with identical token IDs across Python, TNYV, and the C representation.</strong></p><p>The lab also checks a compression target of at least 3.5 characters per token across its selected natural Portuguese test sentences.</p><p>This is more than a tokenizer demonstration. It is a reproducibility test between the development environment and the embedded implementation.</p><h3>9. Putting It on the ESP32-S3</h3><p>The firmware demonstration is available: esp32s3_bpe_demo/esp32s3_bpe_demo.ino</p><p>Open the sketch in the Arduino IDE, select the ESP32-S3 board configuration, and upload it to the device.</p><p>The demo uses a sample vocabulary header so that the sketch can compile immediately. The full training lab generates out/tiny_vocab.h with the vocabulary learned from the project&#39;s corpus.</p><p>After uploading, open the Serial Monitor at 115200 baud.</p><p>The firmware accepts UTF-8 text and displays:</p><ul><li>The input text and its byte length.</li><li>The generated BPE token IDs.</li><li>The corresponding token pieces.</li><li>The tokenization latency in microseconds.</li><li>The reconstructed text through TinyUtf8Stream.</li></ul><p>Try a sentence such as:</p><pre>A temperatura da sala está 29°C; ligar ventilação?</pre><p>Then compare it with the original character-level representation.</p><p>The difference is not merely visual. The BPE representation can express recurring words and subwords with substantially fewer model steps.</p><p>The module’s example compares approximately 53 character-level tokens with around 11–14 domain-specific BPE tokens for the same sentence.</p><p>That is roughly 3.5 to 4.5 times fewer tokens.</p><p>With a context window of 256 tokens, a compression ratio in this range can represent approximately 950 characters of text, rather than only 256 characters.</p><p>This creates room for longer conversations, sensor context, and structured commands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=540fdf84b46b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACT II — The Transformation: From Random Weights to a Quantized Language Model]]></title>
            <link>https://medium.com/@luizcf14/act-ii-the-transformation-from-random-weights-to-a-quantized-language-model-2ae7b689ce8b?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ae7b689ce8b</guid>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 17:25:38 GMT</pubDate>
            <atom:updated>2026-11-20T17:25:38.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JjIZc_wlEGzsbzLR" /></figure><p><em>How 366,528 parameters learn to predict language — and how that knowledge becomes a 381 KB binary file.</em></p><p>In the first act, we explored how a tiny language model is structured and how its architecture fits within the constraints of an ESP32-S3.</p><p>But an architecture is only a blueprint.</p><p>A Transformer with 366,528 randomly initialized parameters does not understand questions, recognize patterns, or generate meaningful answers. It is a mathematical structure waiting to be trained.</p><p>So, how does that transformation happen?</p><p>How do random numbers become a language model? How does the network learn from examples? And how can we preserve what it has learned in a compact representation that can run on a microcontroller?</p><p>This is the story of that transformation.</p><h3>Before learning, there is only uncertainty</h3><p>Let’s start with a simple experiment.</p><p>Imagine creating a new instance of our TinyTransformer, using the same architecture as TINY:</p><ul><li>97 symbols in the vocabulary</li><li>128 positions of context</li><li>96-dimensional embeddings</li><li>4 Transformer layers</li><li>4 attention heads</li><li>256 neurons in the feed-forward network</li></ul><p>The model contains 366,528 parameters.</p><p>At initialization, its weight matrices contain small random values sampled from a Gaussian distribution. Its normalization gains start at 1.0.</p><p>There is no language knowledge in these numbers.</p><p>When the model receives a question, its output logits are converted into probabilities through Softmax. With no learned preferences, the probabilities are approximately uniform across the 97 possible symbols:</p><p><strong>P(x_t) = 1/97 ~1%</strong></p><p>In other words, the model has roughly a 1% probability of selecting any particular character.</p><p>Ask it a question, and you should expect something closer to random noise than an answer.</p><p>This is our starting point: a complete neural architecture with no useful learned behavior.</p><h3>2. Teaching the model to predict</h3><p>A language model does not learn by memorizing a list of instructions embedded in its architecture. It learns by adjusting its parameters to improve predictions.</p><p>The training objective is autoregressive next-token prediction.</p><p>Given a sequence of characters, the model estimates the probability of the next character based on the preceding context: <strong>P(x_t | x_1, x_2, …, x_{t-1})</strong></p><p>For our character-level model, the sequence is composed of individual characters rather than words or subword tokens.</p><p>Consider this training example: oi | ola!</p><p>The question and answer are converted into token IDs. A separator marks the boundary between them.</p><p>The model receives the question as context and learns to generate the answer one character at a time.</p><p>There is an important detail in our implementation: <strong>the training loss is calculated only over the answer</strong>.</p><p>This is achieved through A<strong>nswer-Only Supervised Fine-Tuning</strong>. The target positions corresponding to the question are masked using <strong>ignore_index=-100</strong>.</p><h3>3. Measuring what the model gets wrong</h3><p>How do we know whether the model is learning?</p><p>We need a way to measure the difference between its predictions and the expected output.</p><p>Our implementation uses Cross-Entropy Loss.</p><p>For a single prediction, the loss is: <strong>Loss = -ln(p_{correct})</strong></p><p>Here, (<strong>p_{correct}</strong>) is the probability assigned by the model to the correct next character.</p><p>At initialization, if all 97 symbols have approximately equal probability: <strong>Loss = -ln(1/97)~ 4.57</strong></p><p>If the model assigns a probability of<strong> 0.95</strong> to the correct character: <strong>Loss = -ln(0.95) ~ 0.05</strong></p><p>A lower loss means the model is assigning more probability to the expected characters.</p><p>The training loop then uses backpropagation to calculate how each parameter contributes to the error.</p><p>In PyTorch, the central operations are familiar:</p><pre>optimizer.zero_grad(set_to_none=True)<br>loss.backward()<br>torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)<br>optimizer.step()</pre><h3>4. The dataset is part of the architecture</h3><p>A small model has very limited capacity compared with modern cloud-scale language models.</p><p>That makes the quality and structure of its training data especially important.</p><p>The original TINY model was trained on a synthetic dataset containing approximately 3,500 facts in English.</p><p>But the dataset was not simply a collection of 3,500 question-and-answer pairs.</p><p>It included variations in how questions were formulated, greetings, capitalization differences, and light typing errors.</p><p>Why does this matter?</p><p>Because a model trained only on:</p><pre>What is the capital of Brazil? | Brasilia.</pre><p>may struggle when asked:</p><pre>Brazil&#39;s capital?</pre><p><strong>The underlying information is the same, but the input sequence is different.</strong></p><p>Dataset engineering exposes the model to different formulations of similar questions. This helps it learn patterns that extend beyond a single exact string.</p><p>The repository documents a significant improvement across TINY versions:<br><strong>TINY v1 -&gt; 6%</strong></p><p><strong>TINY v2.1 — training-style questions -&gt; 90%</strong></p><p><strong>TINY v2.1–780 unseen questions -&gt; 61%</strong></p><p>These results illustrate an important distinction.</p><p>A model can perform very well on examples that resemble its training data and still struggle with questions it has never encountered.</p><p>The dataset is not just material fed into the training loop. It is a fundamental part of how the model acquires its behavior.</p><h3>5. Training under the constraints of INT8</h3><p>There is another challenge.</p><p>Our final model must run with quantized weights on an ESP32-S3.</p><p>A straightforward approach would be to train the model in float32 and convert its weights to int8 after training. This is known as Post-Training Quantization (PTQ).</p><p>However, quantization changes numerical values. In a small network, approximation errors can accumulate across multiple layers and affect the final predictions.</p><p>TINY uses Quantization-Aware Training (QAT) to account for these effects during optimization.</p><p>The function ste_int8() simulates quantization and dequantization during the forward pass.</p><p>Conceptually, the operation is:</p><ol><li>Quantize the value to an integer representation.</li><li>Dequantize it back to a floating-point approximation.</li><li>Use that approximation during the forward computation.</li><li>Allow gradients to flow during backpropagation through a Straight-Through Estimator.</li></ol><p>The implementation uses .detach() to separate the quantized approximation from the gradient path.</p><p>This allows the model to be optimized while experiencing numerical behavior closer to the quantized representation it will use during inference.</p><p>The objective is not merely to make the model smaller after training.</p><p>It is to make the model learn while taking the constraints of its final representation into account.</p><h3>6. Specialization without forgetting: the AMEBA experiment</h3><p>The repository contains a second important training process: adapting TINY to Brazilian Portuguese.</p><p>This is not the same as training a new model from random initialization.</p><p>AMEBA starts from the pretrained TINY weights. It loads the existing model and specializes it using Portuguese question-and-answer examples.</p><p>This process combines several techniques:</p><p><strong>Answer-Only SFT</strong></p><p>The model is trained to generate the expected answers, while the question tokens are excluded from the loss.</p><p><strong>Quantization-Aware Training</strong></p><p>The model continues to experience simulated int8 behavior during training.</p><p><strong>L2-SP</strong></p><p>This technique penalizes excessive deviation from the original pretrained weights. It encourages the specialized model to preserve useful parameters learned during base training.</p><p><strong>Self-distilled replay</strong></p><p>The base model generates 30 anchor answers. These examples are mixed into the fine-tuning process to help preserve some of the original behavior.</p><p>Together, these techniques address a central challenge in specialization: teaching the model new patterns without unnecessarily destroying what it already knows.</p><p>The distinction between the two training processes is important:</p><ul><li>TINY is pretrained from random initialization.</li><li>AMEBA is specialized from the existing TINY weights.</li><li>The four-example experiment is a separate educational exercise that demonstrates learning from scratch.</li></ul><p>They are different experiments, with different purposes.</p><h3>7. From learned parameters to a TNY2 binary</h3><p>After training, the model contains learned parameters, but it is not yet ready for the ESP32.</p><p>The training environment contains structures that are unnecessary for inference: gradients, optimizer state, and training-specific data.</p><p>We need to preserve the information required by the inference engine and discard the rest.</p><p>This is where the TNY2 format comes in.</p><p>The export process quantizes the model’s weight matrices row by row.</p><p>For each row, it calculates a scale: <strong>scale = max(row)/127</strong></p><p>Then each weight is converted into an 8-bit integer:</p><p><strong>w_int8 = round(w/scale)</strong></p><p>The scale is stored alongside the quantized values so the inference engine can reconstruct their approximate magnitude.</p><p>The binary also contains the model header and normalization parameters. The final file has a total size of: <strong>381,808 bytes.</strong></p><p>This is a substantial reduction compared with the 1,466,112 bytes required to store all 366,528 parameters as float32 values alone.</p><p>The export operation is implemented in: <strong>model.export_tny2()</strong></p><p>The resulting file is a compact representation of the trained model. It no longer contains the machinery required to learn. It contains the numerical state required to make predictions.</p><h3>8. The four-example experiment: watching transformation happen</h3><p>The repository includes a small laboratory that makes this process observable.</p><p>Instead of loading TINY.BIN, we instantiate a new TinyTransformer with the same architecture and initialize its weight matrices from scratch.</p><p>Then we train it using only four question-and-answer pairs:</p><pre>pairs = [<br>    (&quot;oi&quot;, &quot;ola! nasci do zero.&quot;),<br>    (&quot;quem e voce?&quot;, &quot;sou uma llm de 367 mil parametros.&quot;),<br>    (&quot;qual sua placa?&quot;, &quot;rodo no esp32-s3 de 16mb.&quot;),<br>    (&quot;quanto e 2 mais 2?&quot;, &quot;2 mais 2 e igual a 4.&quot;),<br>]</pre><p>The model is trained for 180 steps using AdamW, Cross-Entropy Loss, gradient clipping, and QAT.</p><p>Before training, the quantized model produces essentially meaningless output.</p><p>After training, it can reproduce the four answers.</p><p>The experiment is deliberately small, but it demonstrates something fundamental: the same architecture can move from random predictions to learned behavior through parameter optimization.</p><p>It also exposes a limitation.</p><p>Ask an unseen question such as:</p><pre>qual seu nome?</pre><p>The model may fail or combine fragments from the answers it has memorized.</p><p>Four examples are enough to demonstrate the mechanics of learning, but not enough to produce robust generalization.</p><p>This is why the full TINY pretraining process requires thousands of examples and multiple formulations.</p><p>The experiment lets us observe the transformation without hiding it behind a pretrained model.</p><h3>9. What actually changed?</h3><p>At the beginning of this process, we had a neural network with 366,528 randomly initialized parameters.</p><p>After training, those parameters had been adjusted to encode statistical patterns learned from the dataset.</p><p>After quantization and export, the learned state was represented in a 381,808-byte TNY2 file.</p><p>The architecture did not change.</p><p>The number of parameters did not change.</p><p>What changed was the numerical configuration of the network.</p><p>That configuration is what allows the model to assign meaningful probabilities to the next character.</p><p>And that is the transformation: from a mathematical structure with random weights to a compact artifact capable of generating learned sequences.</p><h3>Conclusion: Training creates the model; export makes it portable</h3><p>The journey from random initialization to a deployable language model involves much more than running an optimizer.</p><p>It requires a carefully designed dataset, a suitable prediction objective, an optimization strategy, quantization-aware training, and a binary format that preserves the information needed for inference.</p><p>In this project, these pieces come together in a model with 366,528 parameters and a final footprint of 381,808 bytes.</p><p>The result is not a general-purpose assistant compressed into a microcontroller.</p><p>It is an inspectable language model whose transformation can be followed from individual training examples to the final binary representation.</p><p>In the next act, we will address one of the most important limitations exposed by this implementation: its character-level vocabulary.</p><p>We will explore how a tokenizer changes the way text is represented, why subword units matter, and how a more efficient vocabulary can help a small model make better use of its limited context.</p><p><strong>The weights have learned. Now we need to teach the model how to read more efficiently.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ae7b689ce8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACT I — The Birth]]></title>
            <link>https://medium.com/@luizcf14/hello-neural-silicon-419f21a2a64d?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/419f21a2a64d</guid>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 16:13:11 GMT</pubDate>
            <atom:updated>2026-11-20T17:05:31.640Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How an LLM Is Born: From Random Noise to an ESP32-S3</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*utpN9Tmd0DnGGzVXC5h_Yg.jpeg" /></figure><h3>ACT I — The Birth</h3><p><em>What does it take to turn 366,528 numerical parameters into a language model that fits inside a microcontroller?</em></p><p>We often talk about Large Language Models as if they were mysterious black boxes. We send a prompt, receive an answer, and rarely think about what happens between those two moments.</p><p>But underneath the interface, a language model is a numerical system. Its behavior emerges from matrices of learned weights, a sequence of mathematical operations, and a training process that gradually adjusts millions — or, in our case, just hundreds of thousands — of parameters.</p><p>In this first part of our journey toward running a language model on an ESP32-S3, we are going to open that black box.</p><p>We will follow the model from random initialization to next-character prediction, understand how its parameters are stored in a compact binary file, and finally deploy it on a microcontroller.</p><p>The model we will explore has <strong>366,528 parameters</strong> and occupies just <strong>381,808 bytes</strong> in its quantized binary format.</p><p>That is small enough to make an interesting question possible:</p><p><strong>Can we understand the entire lifecycle of a language model, from its birth to its execution on silicon?</strong></p><h3>AI Doesn’t Have to Live in the Cloud</h3><p>Most introductions to Large Language Models follow a familiar pattern: connect to an API, send a prompt, wait for a response, and display the result.</p><p>But what if we removed the cloud entirely?</p><p>What if the model, its weights, the attention mechanism, and the entire inference pipeline ran inside a microcontroller with only a few hundred kilobytes of internal RAM?</p><p>This is the starting point of our journey: running a real Transformer language model on an ESP32-S3.</p><h3>Meet the Neural Silicon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*ZMPyoL5N0CZhr9-o2oFSRw.png" /><figcaption>Suggested ESP32 Gerber— PCB available in Github</figcaption></figure><p>Our hardware platform is the ESP32-S3-WROOM-1 with 16 MB of Flash memory, an Xtensa LX7 dual-core processor running at up to 240 MHz, and optional external PSRAM.</p><p>Unlike traditional cloud-based inference, the entire computation happens locally.</p><p>The ESP32 handles:</p><ul><li>Neural network inference.</li><li>Token generation.</li><li>Attention and KV Cache management.</li><li>Wi-Fi communication.</li><li>Real-time streaming to a browser interface.</li></ul><p>No external AI API. No GPU. No internet connection required for inference.</p><h3>Understanding the Memory Constraints</h3><p>The first lesson in embedded AI is that memory architecture matters as much as computational power.</p><p>The ESP32-S3 provides three relevant memory regions:</p><p><strong>Flash:</strong> Non-volatile storage for firmware, model weights, and static resources.</p><p><strong>Internal SRAM:</strong> Fast working memory for activations, the KV Cache, network buffers, and runtime variables.</p><p><strong>PSRAM:</strong> Optional external memory that provides additional capacity for longer context windows and larger buffers.</p><p>One important optimization is storing model weights in Flash and accessing them through memory mapping instead of copying the entire model into RAM.</p><p>This allows the processor to access neural weights without consuming precious internal SRAM.</p><h3>he birth of TINY: a model starts with random numbers</h3><p>A trained language model does not contain a collection of predefined answers. It contains numerical weights that have been adjusted during training to make useful predictions.</p><p>At initialization, those weights do not encode a language, facts, or grammar. They are simply numbers.</p><p>In our implementation, the model’s main weight matrices begin with small values sampled from a Gaussian distribution:</p><p><strong>W ~ N(0, 0.02)</strong></p><p>The normalization gain vectors start at 1.0. At this point, the network has no useful linguistic knowledge. Its output is essentially noise.</p><p>The training objective is straightforward: given a sequence of characters, predict the next character.</p><p>This is the central idea behind autoregressive language modeling. The model receives a context and learns to estimate the probability distribution of the next symbol:</p><p><strong>P(x_t | x_1, x_2, …, x_{t-1})</strong></p><p>The same broad principle is used by much larger language models. The difference is the scale of the architecture, the data, and the computational resources.</p><p>Our goal is not to reproduce the capabilities of a cloud-scale model. It is to understand the mechanism at a scale where every parameter and byte can be inspected.</p><h3>2. A Transformer designed around a memory budget</h3><p>The architecture of TINY is deliberately compact.</p><p>Its geometry is:</p><pre>| Configuration        | Value       |<br>|----------------------|------------:|<br>| Vocabulary           | 97 symbols  |<br>| Context window       | 128 characters |<br>| Embedding dimension  | 96          |<br>| Transformer layers   | 4           |<br>| Attention heads      | 4           |<br>| MLP hidden dimension | 256         |<br>| Total parameters     | **366,528** |</pre><p>There is an important historical detail behind this design.</p><p>The original project was developed with MS-DOS constraints in mind. Its README describes a target environment where a program running in Large memory mode had approximately 540 KB of conventional RAM available.</p><p>That constraint shaped the model’s dimensions. The result is a small Transformer whose architecture and binary representation can be examined in detail.</p><h3>Why 97 symbols?</h3><p>Unlike modern language models that use subword tokenizers, TINY uses a character-level vocabulary.</p><p>Its 97 symbols are:</p><ul><li>0: padding.</li><li>1: separator and end-of-sequence marker.</li><li>2–96: printable ASCII characters, from space to ~.</li></ul><p>Each character maps to a numerical ID. For example, the word oi becomes two tokens, followed by a separator token.</p><p>This is simple and easy to implement in C, but it has a cost: every character consumes one position in the context window. We will return to this limitation later.</p><h3>Where do the 366,528 parameters go?</h3><p>The parameter count is not an estimate. It can be calculated directly from the architecture.</p><pre>| Component                   | Parameters |<br>|-----------------------------|-----------:|<br>| Token embeddings            | 9,312      |<br>| Positional embeddings       | 12,288     |<br>| RMSNorm gains across layers | 768        |<br>| Attention projections       | 147,456    |<br>| MLP layers                  | 196,608    |<br>| Final normalization         | 96         |<br>| **Total**                   | **366,528** |</pre><p>The token embedding matrix is also <strong>reused </strong>for the output projection through weight tying, avoiding the need to store another large matrix.</p><p>This is one of the most interesting aspects of a tiny model: architectural decisions that might be minor in a large network become significant when every byte matters.</p><h3>3. From 1.4 MB to 381 KB: quantization</h3><p>If we stored all 366,528 parameters as 32-bit floating-point numbers, the weights alone would occupy: ~That is approximately 1.40 MB.</p><p>For a microcontroller, this is an unnecessary burden.</p><p>TINY uses 8-bit integer weights (int8). Instead of storing each weight as a four-byte floating-point value, it stores one byte and keeps a floating-point scale for each quantized row.</p><p>The quantization process calculates:<strong> scale = max(|row|) / 127</strong></p><p>Then each weight is converted into an integer: <strong>w_int8 = round(w / scale)</strong></p><p>The scale allows the original magnitude of the row to be approximately reconstructed during inference.</p><p>The resulting binary file also contains a small header and the model&#39;s normalization parameters.</p><pre>| Storage item                        | Size          |<br>|-------------------------------------|--------------:|<br>| Quantized weights                   | 366,528 bytes |<br>| 3,169 float32 scales                | 12,676 bytes  |<br>| Normalization parameters and header | 2,604 bytes   |<br>| **TNY2 binary**                     | **381,808 bytes** |</pre><p>The important result is that the complete TNY2 file occupies <strong>381,808 bytes</strong>.</p><p>This is almost four times smaller than storing the weights as float32.</p><p>The binary format uses the TNY2 magic header, followed by the model data. It is the bridge between the Python training environment and the embedded inference engine.</p><h3>4. How does random noise become a language model?</h3><p>The training process can be understood as six connected stages.</p><h3>Stage 1 — Turning text into numbers</h3><p>Neural networks operate on numbers, not directly on text.</p><p>For the character-level tokenizer, each printable ASCII character receives an ID. A training example such as:</p><pre>oi | ola!</pre><p>becomes an input sequence and a target sequence.</p><p>The model receives the question, a separator, and the answer characters. During training, the loss is calculated only on the answer portion.</p><p>This is called <strong>Answer-Only Supervised Fine-Tuning</strong> in our implementation.</p><p>The question provides context. The answer provides the prediction targets.</p><h3>Stage 2 — Initializing the network</h3><p>The model starts with random weights.</p><p>In the zero-from-scratch experiment, the two-dimensional parameter matrices are initialized using:</p><pre>torch.nn.init.normal_(p, mean=0.0, std=0.02)</pre><p>This detail matters in our codebase: the regular TinyTransformer constructor uses torch.empty() because the normal loading path immediately fills those tensors with weights from an existing TNY2 model.</p><p>When creating a genuinely new model, we must initialize them explicitly.</p><p>Before training, the model has no meaningful knowledge. Its output is essentially random character sequences.</p><h3>Stage 3 — Engineering the dataset</h3><p>A small model cannot rely on an enormous and uncontrolled collection of text.</p><p>The original TINY training process used a synthetic dataset covering approximately 3,500 facts in English, with multiple question formulations, greetings, capitalization variations, and light typing errors.</p><p>The repository documents a substantial improvement between its early versions: TINY v1 achieved 6% accuracy, while v2.1 reached 90% on training-style questions and 61% on a set of 780 unseen questions.</p><p>These figures illustrate an important lesson: <strong>dataset construction is part of model engineering</strong>.</p><p>For the Portuguese specialization, the repository includes generate_brazil_dataset.py and txt_to_jsonl.py. They produce question-and-answer examples, variations, and safe refusal responses for AMEBA.</p><h3>Stage 4 — Learning to predict the next character</h3><p>The model processes the training sequence using a causal attention mask.</p><p>During training, the entire sequence can be processed in parallel. The causal mask prevents a position from accessing future characters. This allows the model to calculate predictions for multiple positions in a single forward pass without leaking the answer.</p><p>The error is measured using cross-entropy: <strong>Loss = -ln(p_correct)</strong></p><p>At the beginning, if the model assigns approximately equal probability to all 97 symbols, the expected loss is: <strong>-ln(1/97)</strong> ~<strong>approx 4.57</strong></p><p>As training progresses, the model becomes more confident about the correct next character, and the loss decreases.</p><p>Backpropagation calculates the gradients, and AdamW updates the parameters. The implementation also uses gradient clipping, warmup, and cosine learning-rate decay.</p><p>This is where random numerical values gradually become a model capable of producing meaningful sequences.</p><h3>Stage 5 — Training with 8-bit constraints</h3><p>There is a problem with simply training in float32 and converting everything to int8 at the end.</p><p>Quantization introduces approximation errors. In a small network with multiple layers, those errors can accumulate and noticeably affect the output.</p><p>TINY uses <strong>Quantization-Aware Training (QAT)</strong> to address this.</p><p>During the forward pass, ste_int8() simulates quantization and dequantization of weights and key/value vectors. During backpropagation, a Straight-Through Estimator allows gradients to flow through the rounding operation.</p><p>The AMEBA fine-tuning process adds two more techniques to reduce forgetting:</p><ul><li><strong>L2-SP:</strong> penalizes excessive deviation from the original model weights.</li><li><strong>Self-distilled replay:</strong> uses 30 anchor answers generated by the base model and mixes them into the fine-tuning process.</li></ul><p>The goal is to specialize the model for Brazilian Portuguese while preserving some of the knowledge acquired during base training.</p><h3>Stage 6 — Freezing the model and exporting it</h3><p>Training and inference are very different operations.</p><p>During training, the model needs gradients, an optimizer, and intermediate data structures. During inference, none of those are necessary.</p><p>Once training is complete, the model is exported into the TNY2 binary format. The export process quantizes the weights, stores the corresponding scales, and writes the binary header.</p><p>The repository’s generate_esp32_assets.py tool converts this binary into a C header containing the model data:</p><pre>TINY_BIN_U32[95452] PROGMEM</pre><p>The resulting weights can be included in the ESP32 firmware.</p><p>The model is now frozen. It will not learn on the microcontroller. It will only perform inference: reading the weights, processing the input, and generating the next character.</p><h3>5. Three different experiments: TINY, AMEBA, and learning from scratch</h3><p>Before moving to the hardware, it is important to distinguish three processes in this project.</p><p><strong>TINY base pretraining</strong></p><p>The original base model starts from random initialization and is trained on a synthetic English dataset of approximately 3,500 facts. This is the process that produces TINY.BIN.</p><p><strong>AMEBA Portuguese specialization</strong></p><p>AMEBA starts from the trained TINY weights. It is not a second model trained from random initialization. It loads the base weights and fine-tunes them using Portuguese examples, QAT, replay, and L2-SP.</p><p><strong>The four-example laboratory</strong></p><p>This is a separate educational experiment. We create a new Transformer with the same architecture, initialize it from random values, and train it using only four question-and-answer pairs.</p><p>The four examples are:</p><pre>pairs = [<br>    (&quot;oi&quot;, &quot;ola! nasci do zero.&quot;),<br>    (&quot;quem e voce?&quot;, &quot;sou uma llm de 367 mil parametros.&quot;),<br>    (&quot;qual sua placa?&quot;, &quot;rodo no esp32-s3 de 16mb.&quot;),<br>    (&quot;quanto e 2 mais 2?&quot;, &quot;2 mais 2 e igual a 4.&quot;),<br>]</pre><p>We train for 180 steps using AdamW and QAT, then export the result into the same TNY2 format.</p><p>The experiment is deliberately small. It demonstrates that a network can learn to reproduce a few answers from random initialization.</p><p>But it also reveals the difference between memorization and generalization.</p><p>When we ask an unseen question such as qual seu nome?, the model may fail or combine fragments of the answers it has learned. Four examples are enough to demonstrate the mechanics of training, but not enough to build a useful general-purpose language model.</p><p>That is precisely why the full TINY pretraining process uses thousands of varied examples.</p><h3>Moving from Python to the ESP32-S3</h3><p>Now comes the most satisfying part: taking the trained model out of the PC and running it on a microcontroller.</p><p>Our target hardware is the <strong>ESP32-S3-WROOM-1 with 16 MB of Flash</strong>.</p><p>The key engineering decision is where to store the model weights.</p><p>The ESP32-S3 has several memory regions with different characteristics:</p><pre>torch.nn.init.normal_(p, mean=0.0, std=0.02)</pre><p>The model weights are stored in Flash using PROGMEM.</p><p>On the ESP32-S3, this places the constant data in the DROM region, which is mapped into the CPU address space. The inference engine can read the weights directly without copying the entire model into SRAM.</p><p>This is crucial because internal SRAM is limited and also needed by Wi-Fi and other runtime components.</p><p>In the current implementation, the KV cache occupies approximately 102,400 bytes. The model weights remain in Flash, while the runtime uses SRAM for the data that changes during inference.</p><p>PSRAM can provide additional capacity on modules that include it, but it is not required for the current TNY2 model.</p><p>Once the firmware is flashed, we can interact with the model through the serial monitor or the built-in Wi-Fi access point.</p><p>The firmware exposes a small web interface at: <strong>http://192.168.4.1</strong></p><p>Connect to the AMEBA-1.0 access point and open the interface.</p><p>The Neural Monitor exposes useful runtime information, including layer activity, confidence for the selected character, and generation speed in letters per second.</p><p>This is more than a demonstration. It makes the inference process observable on the actual device.</p><h3>The limitations are part of the lesson</h3><p>Running a language model on an ESP32 is exciting, but the first implementation also exposes the limitations of a character-level architecture.</p><p>There are three particularly important problems.</p><p><strong>1. Context is expensive</strong></p><p>The model has a context window of 128 characters. Since each character consumes one position, a long question and answer can quickly exhaust the available context.</p><p>In the current firmware, the question is limited to 72 characters. Even then, some answers may be truncated before completion.</p><p>There is little room for multi-turn conversations or sensor readings.</p><p><strong>2. The model spends capacity learning spelling</strong></p><p>A character-level model must learn words one character at a time.</p><p>It must learn not only that ventilador is associated with a fan, but also how to generate the sequence of letters that forms the word.</p><p>Synonyms and variations can be difficult. The firmware also normalizes questions by removing accents, which introduces another limitation for Portuguese text.</p><p><strong>3. The firmware needs manual conversation rules</strong></p><p>The repository includes nearly 929 lines of manual rules in tiny_session.cpp, including FOLLOWUP_RULES[] and detect_topic().</p><p>These rules help simulate conversational memory that the model’s short context window cannot provide naturally.</p><p>This is an important observation: making a model run on a microcontroller is not the same as giving it the capabilities of a modern conversational assistant.</p><p>The limitations of this first model will motivate the engineering decisions explored in the next modules.</p><h3>Conclusion: A language model is an engineered artifact</h3><p>We started with random numbers and ended with a binary file that can run on an ESP32-S3.</p><p>Along the way, we examined the architecture, calculated its parameter count, explored the training objective, applied quantization-aware training, and understood how the model is stored in Flash and executed using the microcontroller’s available memory.</p><p>The result is not a miniature version of a cloud-scale assistant. It is something arguably more useful for learning: a complete, inspectable example of the language-model lifecycle.</p><p>We can trace its weights, understand its memory footprint, reproduce its training process, and observe its inference behavior on real hardware.</p><p>And perhaps the most important lesson is this:</p><p><strong>The intelligence of a language model is not hidden in a mysterious file. It is the result of an architecture, a dataset, an optimization process, and a carefully engineered path from training to inference.</strong></p><p>In the next module, we will go deeper into the Transformer itself. We will leave the high-level training story behind and examine how its attention layers, normalization, and feed-forward networks can be implemented in pure C.</p><p>The goal is no longer just to run the model.</p><p>It is to understand every operation that makes it work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=419f21a2a64d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crie seu primeiro próprio Assistente-IA sobre o projeto mapbiomas:]]></title>
            <link>https://medium.com/@luizcf14/crie-seu-primeiro-pr%C3%B3prio-assistente-ia-sobre-o-projeto-mapbiomas-9d97fbbba8c9?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d97fbbba8c9</guid>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mapbiomas]]></category>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 22:19:55 GMT</pubDate>
            <atom:updated>2026-03-26T11:37:11.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crie seu primeiro próprio Assistente-IA sobre o projeto MapBiomas:</h3><p>Por Luiz Cortinhas e Mariana Dias</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qPEVgdQEyD4sGZpgvk4iQ.png" /><figcaption>Generated with Nano Banana 2 - Prompt: ”Crie uma imagem que represente o titulo desse post”</figcaption></figure><h3>Objetivo de Aprendizado</h3><ul><li>Como usar a <a href="https://docs.cloud.google.com/gemini/docs/codeassist/gemini-cli?hl=pt-br">CLI do Gemini</a> para gerar uma configuração completa do <a href="https://docs.cloud.google.com/agent-builder/agent-development-kit/overview?hl=pt-br">agente do ADK</a>;</li><li>Como ajustar a personalidade de um agente aprimorando as instruções;</li><li>Como adicionar “fundamentação”/grounding ao seu agente, atribuindo-lhe um google_search para responder a perguntas sobre eventos recentes;</li><li>Como gerar um avatar personalizado para seu acompanhante usando um <a href="https://docs.cloud.google.com/mcp/overview">servidor MCP</a> com o Imagen;</li></ul><h3>O App</h3><p>Você vai criar um companheiro de IA visual e interativo. É muito mais do que um chatbot padrão de texto. Imagine um personagem vivendo em uma página da Web que consegue interagir em tempo real com o projeto Mapbiomas. <br>Mais do que um simples chat, vamos tentar fazer algo mais criativo: Você digita uma mensagem, e em vez de apenas ver o texto, o personagem olha para você e responde em voz alta, com a boca se movendo em sincronia com as palavras.</p><p>Para isso, quebraremos o código em duas etapas:<br>1 — Interface do fantoche/avatar</p><p>2 — O Cérebro</p><p>Em seguida vamos adicionar progressivamente camadas de inteligência e personalização, transformando esse fantoche simples em um companheiro autêntico e capaz.</p><p>Vamos dar a ele:</p><ul><li>Uma inteligência central usando o ADK(Python) para entender e gerar linguagem.</li><li>Criar uma personalidade única escrevendo as instruções principais que definem o caráter.</li><li>Concedendo superpoderes ao dar a ele ferramentas para acessar informações em tempo real da Internet.</li><li>Criar uma aparência personalizada usando a IA para gerar um avatar exclusivo.</li></ul><p>Se tudo der certo 🤞, ao final, você terá um acompanhante de IA totalmente funcional e personalizado, criado por você.</p><h3>Arquitetura</h3><p>Buscamos simplicidade e eficiencia. Temos um back-end Python que expoe uma API. Esse back-end vai conter nosso agente do ADK, que funciona como o “cérebro”.</p><p>Além disso, vamos explorar um conceito mais avançado iniciando um servidor MCP (Protocolo de Contexto de Modelo) local. Esse servidor funciona como uma ponte de ferramentas especializadas para a geração de imagens. Em seguida, vamos usar a CLI do Gemini para comandar esse servidor MCP, instruindo-o a gerar uma aparência única para nosso acompanhante de IA.</p><p>Sobre a arquitetura:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jq1I-dd8fEfs5mtJ" /></figure><h3>Requisitos</h3><ul><li>Uma conta Google válida</li><li>Uma conta com faturamento ativo na Google Cloud Platform (GCP)</li><li>Possuir o gcloud instalado em seus S.O (<a href="https://docs.cloud.google.com/sdk/docs/install-sdk?hl=pt-br">https://docs.cloud.google.com/sdk/docs/install-sdk?hl=pt-br</a>)</li></ul><h3>E vamos ao código da parte 1:</h3><p>Clone o repositório com o esqueleto desse projeto:</p><pre>git clone https://github.com/luizcf14/companion-python-mb </pre><p>Inicie o projeto configurando as variáveis de ambiente e instalando as dependências</p><pre>cd ~/companion-python<br>./init.sh # para linux-like<br>./init.bat # para windows<br><br>#Configura o projeto google cloud que voce digitou no init.{sh|bat}<br>gcloud config set project $(cat ~/project_id.txt) --quiet <br>#Habilita ou Checa se possui esses dois serviços ligados no seu projeto cloud<br>gcloud services enable  compute.googleapis.com \<br>                        aiplatform.googleapis.com<br>#Criando o Virtual Env para evitar que crie-se conflitos com dependencias previamente instaladas<br>python -m venv env<br>source env/bin/activate # para Linux<br>.\env\Scripts\Activate.ps1 # para Windows<br>pip install -r requirements.txt <br><br># google cloud <br>#./set_env.sh</pre><p>Agora que tudo esta devidamente configurado, vamos experimentar rodar o esqueleto</p><pre>python app.py  # abra a url http://127.0.0.1:5000/ no navegador</pre><p>Se tudo deu certo, o serviço foi iniciado em seu localhost na porta 5000 e no browser voce poderá ver o rascunho dessa aplicação, uma capivara.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2dt93soUSAnxiKiN" /></figure><p>Agora vamos usar do Gemini CLI para nos ajudar a criar esse agente, para isso façamos o seguinte:</p><pre>clear<br>gemini --yolo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*CJguGajvc5FhzJvKJxFI4A.png" /><figcaption>Ao abrir o “gemini — yolo” algo como isso deve aparecer em tela</figcaption></figure><p>Nessa interface CLI vamos colar o seguinte comando:</p><pre>Gere um codigo em Python para o arquivo chamado de character.py<br>O codigo precisa: import `LlmAgent` from `google.adk.agents.llm_agent`. Isso deve tambem importar import `logging` and `os`.<br>Então, crie a instancia de classe `LlmAgent` e assinalea para a variavel `root_agent`<br><br>Quando estiver criando a instancia `LlmAgent`, configure para que esses parametros exatos:<br>  - `model` deve ser uma string que deve conter `&#39;gemini-2.5-flash&#39;`.<br>  - `name` deve ser uma string que deve conter `&#39;companion_agent&#39;`.<br>  - `instruction` deve ser uma string multi linhas que deve conter: &quot;You are a friendly and efficient companion who will interact with user have start a conversation about the Mapbiomas Project, and LULC classes.&quot;.</pre><p>E acabamos de usar de vibe coding! Pedimos para o Gemini gerar uma peça fundamental dessa integração entre o avatar da capivara e a IA por trás disso tudo. Para termos certeza de que a geração não teve nenhuma alucinação, seu código deve ser parecido com isso:</p><pre>import logging<br>import os<br>from google.adk.agents.llm_agent import LlmAgent<br><br>root_agent = LlmAgent(<br>    model=&#39;gemini-2.5-flash&#39;,<br>    name=&#39;companion_agent&#39;,<br>    instruction=&quot;&quot;&quot;<br>          You are a friendly and efficient companion who will interact with user have start a conversation about the Mapbiomas Project, and LULC classes.<br>    &quot;&quot;&quot;,<br>)</pre><p>E vamos rodar novamente o app.py para testar (python app.py)</p><p>👀 Acesse a guia de visualização da Web 👀</p><p>Digite algo como“Olá como vai você?” no campo de texto e clique em enviar. Se tudo deu certo, a capivara vai começar a falar. 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*kjQPmCirnrn9c28rYoMLwA.png" /></figure><h3>Comunicação entre Agentes: Integrando Especialistas via WebSockets e Tool Calling</h3><p>Na arquitetura do nosso Avatar, nos deparamos com um desafio clássico de sistemas multi-agentes: como fazer o agente principal conversacional (o nosso “Companion” | “Fantoche”, instanciado via LlmAgent do <em>Agent Development Kit</em> do Google) se comunicar com um agente remoto ultra-especializado (a <em>MapBiomas Flora</em>)?</p><p>A solução que adotamos foi utilizar o conceito de <strong>Tool Calling</strong> (ou <em>Function Calling</em>) combinado com <strong>WebSockets</strong>. Em vez de sequestrar o fluxo do usuário ou construir complexos orquestradores no backend, nós encapsulamos o agente Flora como se fosse uma “ferramenta” nativa (uma habilidade) disponível para o agente principal.</p><h3>Como a mágica acontece na prática:</h3><p><strong>Intenção e Delegação</strong>: O usuário faz uma pergunta específica sobre o ecossistema brasileiro no front-end. O LLM principal (gemini-2.5-flash), através do seu <em>prompt</em> de instrução, reconhece que aquela informação está fora do seu conhecimento base, mas sabe que possui a ferramenta consult_mapbiomas_flora à sua disposição.</p><p>Codigo da Ferramenta/Tool:</p><pre># No  repositorio ela esta no arquivo flora_tool.py <br># O Comentario de cabeçalho é tambem usado como Guia de uso pelo ADK quando ele lê a tool.<br>async def consult_mapbiomas_flora(message: str, session_id: Optional[str] = None, user_id: Optional[str] = None) -&gt; str:<br>    &quot;&quot;&quot;Consult the Flora remote agent via WebSocket to receive help or interact with the MapBiomas system. Provide the original user message.<br>    <br>    Args:<br>        message: The user&#39;s query or message.<br>        session_id: Optional. A unique session identifier for the user. Leave as None if unknown.<br>        user_id: Optional. A unique user identifier. Leave as None if unknown.<br>        <br>    Returns:<br>        The text response from the Flora remote agent.<br>    &quot;&quot;&quot;<br>    if not session_id:<br>        session_id = f&quot;mapbiomas-{uuid.uuid4().hex[:8]}&quot;<br>    if not user_id:<br>        user_id = f&quot;mapbiomas-{uuid.uuid4().hex[:8]}&quot;<br>    # Endereço do websocket de interação com a IA Mapbiomas<br>    uri = &quot;wss://prd.plataforma.flora2.mapbiomas.org/flora/runs/ws&quot;<br>    payload = {<br>        &quot;message&quot;: message,<br>        &quot;session_id&quot;: session_id,<br>        &quot;user_id&quot;: user_id<br>    }<br>    <br>    responses = []<br>    #Lembrem sempre de tratar erros prefira try-catches a if&#39;s!<br>    try:<br>        async with websockets.connect(uri) as websocket:<br>            await websocket.send(json.dumps(payload))<br>            <br>            while True:<br>                response_text = await websocket.recv()<br>                if response_text == &quot;END&quot;:<br>                    break<br>                    <br>                try:<br>                    data = json.loads(response_text)<br>                    if &quot;content&quot; in data:<br>                        responses.append(data[&quot;content&quot;])<br>                except json.JSONDecodeError:<br>                    pass<br>    except websockets.exceptions.ConnectionClosedOK:<br>        # A conexão foi fechada limpidamente pelo servidor após concluir o envio<br>        pass<br>    except Exception as e:<br>        logging.error(f&quot;Error communicating with Flora agent: {e}&quot;)<br>        return &quot;Desculpe, ocorreu um erro ao se comunicar com o agente remoto do MapBiomas.&quot;<br>        <br>    return &quot;&quot;.join(responses)</pre><p>Pontos chaves sobre a Ferramenta e sua utilização:</p><p><strong>O Acionamento da Tool</strong>: O LLM decide invocar a ferramenta e o <em>runner</em> assíncrono do ADK intercepta esse desejo, executando nossa função Python em tempo real (passando a mensagem do usuário e metadados de sessão).</p><p><strong>A Ponte do WebSocket</strong>: A função Python abre uma conexão WebSocket (wss://) diretamente com o servidor da MapBiomas Flora. Ela envia um payload JSON padronizado (message, session_id e user_id).</p><p><strong>Streaming Bidirecional e Agrupamento</strong>: A Flora processa o pedido e começa a devolver a resposta. Como as respostas de LLMs normalmente vêm em blocos (<em>stream</em>), o nosso código empilha cada pedacinho recebido até que o servidor avise que concluiu (enviando a flag &quot;END&quot; ou fechando a conexão de forma nativa e limpa pelo protocolo padrão com código 1000 OK).</p><p><strong>Síntese Final</strong>: Todo o texto coletado da Flora é devolvido pela ferramenta ao agente principal. O LLM então lê a resposta técnica do especialista e a insere organicamente na conversa com o usuário final, utilizando seu tom de voz amigável.</p><p>E por fim, o trecho de código que adiciona a ferramenta na instância do agente:</p><pre>from google.adk.agents.llm_agent import LlmAgent<br>from flora_tool import consult_mapbiomas_flora<br><br>root_agent = LlmAgent(<br>    model=&quot;gemini-2.5-flash&quot;,<br>    name=&quot;companion_agent&quot;,<br>    instruction=&quot;&quot;&quot;You are a friendly and efficient companion who will interact with user have start a conversation. You have access to a remote agent (Mapbiomas Flora) via a tool, use it whenever the user asks about MapBiomas or if you need external help.&quot;&quot;&quot;,<br>    # Veja que legal!, basta passar a função na lista que vai no argumento de tools<br>    tools=[consult_mapbiomas_flora], <br>    <br>)</pre><h3>Vantagens dessa Arquitetura</h3><p><strong>Desacoplamento</strong>: O agente principal não precisa saber como a IA MapBiomas busca as informações, apenas como chamá-la.</p><ul><li><strong>Velocidade</strong>: Sendo 100% assíncrona (async/await), enquanto o WebSocket aguarda a IA MapBiomas, event loops do Python no servidor ficam livres para atender outros usuários simultâneos.</li><li><strong>Resiliência (Graceful Degradation)</strong>: Se o servidor remoto da IA MapBiomas cair (Ex: um erro HTTP 503 Service Unavailable), o bloco de exceção da ferramenta encapsula o erro e devolve uma mensagem de indisponibilidade programada ao LLM. O nosso Avatar, ao invés de quebrar a aplicação do usuário com uma tela de &quot;Erro 500&quot;, gera uma resposta empática avisando que o colega especialista está temporariamente &quot;indisponível&quot;.</li></ul><h3><strong>Puxa, chegamos ao fim dessa saga!</strong></h3><p>Se você se perdeu ou se nós falhamos em explicar algo, por favor manda uma mensagem. <br>Ahh..se seu tempo estiver corrido e você queira ver logo o código final, basta ir no repositório e baixar a branch “capy_avatar”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*J2Rmr5cGgtWXmFBi1xTTOA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d97fbbba8c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aspectos gerais para quem deseja projetar um sistema multi agente baseado em LLM (LLM-MAS)]]></title>
            <link>https://medium.com/@luizcf14/aspectos-gerais-para-quem-deseja-projetar-um-sistema-multi-agente-baseado-em-llm-llm-mas-f1cda84327b5?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1cda84327b5</guid>
            <category><![CDATA[arquitetura]]></category>
            <category><![CDATA[llm-mas]]></category>
            <category><![CDATA[português]]></category>
            <category><![CDATA[architecture-pattern]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 01:33:04 GMT</pubDate>
            <atom:updated>2025-04-16T01:52:02.355Z</atom:updated>
            <content:encoded><![CDATA[<p>A gente vê por aí como as inteligências artificiais que entendem e escrevem como gente grande (os LLMs) estão revolucionando tudo. Uma das ideias mais fascinantes é juntar várias dessas “mentes” numa equipe, um <a href="https://medium.com/@luizcf14/porque-precisamos-de-llm-multi-agentes-2e10549c2c67">sistema multiagente inteligente</a> (LLM-MAS). Pensa só: um time de “robôs” que conversam e pensam juntos para resolver aqueles problemas que sozinhos seriam impossíveis! Mas calma, não é só juntar um monte de LLM e esperar a mágica acontecer. Para essa “equipe” de agentes de IA funcionar bem e entregar resultados de verdade, precisamos planejar cada detalhe com cuidado. Desde como eles vão se dividir entre as tarefas até a maneira como vão “lembrar” das coisas. Neste artigo, vamos dar uma olhada nos pontos mais importantes para quem quer construir esses sistemas multiagentes com LLMs, um guia inicial para não se perder nessa fascinante jornada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9sYMsFHZWv7jdb_3F8AWQ.jpeg" /><figcaption>AI generated image with <a href="https://labs.google/fx/pt/tools/image-fx">Google FX</a>, prompt: “An sketchy of a happy human professor with robotic arms showing in the black board how LLM agent systems can be organized in many ways , beside the scene you can see a window with a good weather outside. painted illustration”</figcaption></figure><p>Baseado em minhas recentes leituras de artigos cientificos [<a href="https://arxiv.org/pdf/2402.03578">1</a>] [<a href="https://arxiv.org/pdf/2402.01680">2</a>] <a href="https://link.springer.com/article/10.1007/s44336-024-00009-2">[3</a>] [<a href="https://www.mdpi.com/2079-9292/12/12/2722">4</a>][<a href="https://arxiv.org/abs/2503.03686">5</a>] <a href="https://arxiv.org/pdf/2405.15143">[6</a>] que sumarizam os recentes avanços e que tambem pontuam os problemas na area de LLM-MAS, consegui organizar o planejamento da construção de um sistema em 4 itens importantes, e neles teremos alguns sub-itens.</p><h3>1 — Planejamento Global</h3><p>Trata-se de definir a estratégia de alto nível, estabelecendo como o problema complexo será abordado pela coletividade de agentes. Isso envolve a clara identificação e alocação de responsabilidades específicas para cada agente, garantindo que suas capacidades distintas sejam utilizadas de forma eficiente. Além disso, o planejamento global considera a arquitetura geral do sistema, as possíveis interações entre os agentes e a implementação de mecanismos para otimizar o fluxo de trabalho, como a criação de loops de feedback em sub-redes para lidar com tarefas mais simples de maneira ágil. Em essência, o planejamento global traça o mapa estratégico que guiará a colaboração dos agentes em direção ao objetivo final, evitando redundâncias, conflitos e garantindo uma solução coesa e eficaz.</p><p>Ser eficiente na escolha do número de agentes e de suas especificidades em um LLM-MAS é crucial para o desempenho, custo e escalabilidade do seu sistema. Não existe uma fórmula mágica única, pois a resposta depende intrinsecamente da natureza do problema que você busca resolver. Mas pude elencar aqui, algumas diretrizes e perguntas podem te ajudar nesse processo através da tecnica de “<strong>decomposição de problemas por perguntas</strong>”:</p><p><strong>Perguntas Chave para Guiar a Decisão:</strong></p><ul><li>O problema pode ser naturalmente dividido em quantas sub-tarefas distintas?</li><li>Quais habilidades únicas são necessárias para cada sub-tarefa?</li><li>A colaboração entre múltiplos agentes trará um ganho significativo em relação a um único agente mais complexo? (teste)</li><li>Qual o nível de paralelismo que pode ser explorado?</li><li>Quais são as restrições de custo e recursos?</li><li>Como a demanda pelo sistema pode evoluir no futuro?</li></ul><p><strong>Pontos a Considerar:</strong></p><ul><li><strong>Analise a complexidade da tarefa:</strong> O primeiro passo é entender profundamente o problema que o seu LLM-MAS deve solucionar. Quais são as sub-tarefas inerentes a ele? Quão independentes ou interdependentes são essas sub-tarefas?</li><li><strong>Identifique as habilidades necessárias:</strong> Para cada sub-tarefa identificada, quais habilidades ou conhecimentos específicos seriam ideais? Por exemplo, geração de texto criativo, análise de dados, raciocínio lógico, interação com APIs externas, conhecimento de um domínio específico, etc.</li><li><strong>Agentes generalistas vs. especialistas:</strong> Avalie se algumas tarefas podem ser realizadas por agentes mais generalistas, capazes de lidar com uma gama maior de demandas, ou se a especialização trará ganhos significativos em qualidade e eficiência. Tarefas simples e repetitivas podem ser candidatas a agentes mais focados.</li><li><strong>Complexidade e paralelismo:</strong> Problemas mais complexos são aqueles que precisariam de varias consultas a especialistas para que se componha uma resposta, podendo possuir diversas sub-tarefas que podem ser executadas em paralelo, geralmente se beneficiam de um maior número de agentes.</li><li><strong>Escalabilidade futura:</strong> Pense em como as demandas podem crescer no futuro. Um design modular com agentes especializados pode facilitar a adição de novos agentes para lidar com cargas maiores ou novas funcionalidades.</li><li><strong>Custo e recursos:</strong> Mais agentes significam mais computação e potencialmente mais custos (APIs de LLM, infraestrutura, aquecimento global). Encontre um equilíbrio entre o desempenho desejado e os recursos disponíveis. Começar com um número menor e iterar pode ser uma boa estratégia.</li></ul><p>Para completar essa primeira etapa, voce precisa entender muito bem o problema a ser resolvido, entender quais arranjos de agentes são possiveis e principalmente testar. Analogo ao que acontece com os swarms, é provavel que repartir o problema traga mais agilidade para o encontro da solução, mas aqui as instancias podem ser honerosas então tente sempre buscar o melhor custo-beneficio para evitar desperdicios.</p><h3>2 — Planejamento Especifico</h3><p>O Planejamento Específico, em contraste com o Planejamento Global, foca nos detalhes operacionais de como cada agente individual irá executar suas tarefas e como as interações entre eles ocorrerão em um nível mais granular. Enquanto o planejamento global define o “quem faz o quê” em termos amplos, o planejamento específico detalha o “como” cada agente realizará sua parte e “como” essa parte se encaixa no trabalho dos outros.</p><p>Para simplificar tudo isso, vamos as perguntas chaves que voce deve se fazer, elas permitirão um entendimento da necessidade de cada um dos agentes e de como a comunicação deve seguir, são elas:</p><p><strong>Para cada agente individual:</strong></p><ul><li><strong>Qual é o objetivo preciso e mensurável desta tarefa específica para este agente?</strong> (Clareza sobre o resultado esperado)</li><li><strong>Quais são os passos ou o plano de ação detalhado que este agente seguirá para atingir seu objetivo?</strong> (Definição do processo interno)</li><li><strong>Quais são os dados ou informações de entrada que este agente precisa para realizar sua tarefa, e em qual formato?</strong> (Especificação das dependências)</li><li><strong>Qual é o formato exato da saída que este agente deve produzir?</strong> (Garantia de interoperabilidade)</li><li><strong>Quais técnicas de raciocínio (CoT, ToT, etc.) este agente utilizará para processar as informações e gerar a saída?</strong> (Escolha da metodologia de resolução)</li><li><strong>Quais ferramentas ou APIs externas este agente precisa e como ele as utilizará?</strong> (Integração com recursos externos)</li><li><strong>Como este agente gerenciará sua memória de curto prazo durante a execução desta tarefa?</strong> (Contexto operacional)</li><li><strong>Como o desempenho deste agente será avaliado nesta tarefa específica?</strong> (Definição de métricas de sucesso)</li><li><strong>Como este agente deve lidar com erros, informações inválidas ou situações inesperadas durante a execução?</strong> (Mecanismos de tratamento de exceções)</li><li><strong>Quais são as restrições de tempo ou recursos para a conclusão desta tarefa por este agente?</strong> (Considerações práticas)</li></ul><p><strong>Para as interações entre agentes:</strong></p><ul><li><strong>Com quais outros agentes este agente precisa interagir para completar sua tarefa?</strong> (Identificação das dependências inter-agente)</li><li><strong>Qual é o protocolo de comunicação a ser utilizado para essa interação (formato da mensagem, tipo de solicitação/resposta)?</strong> (Padronização da comunicação)</li><li><strong>Quando e em que ordem essa interação deve ocorrer dentro do fluxo de trabalho geral?</strong> (Sequenciamento das ações)</li><li><strong>Quais informações específicas precisam ser trocadas entre esses agentes?</strong> (Conteúdo da comunicação)</li><li><strong>Como os agentes irão coordenar suas ações em cenários mais complexos (por exemplo, tarefas concorrentes ou dependentes)?</strong> (Mecanismos de coordenação)</li><li><strong>Como os conflitos ou inconsistências nas informações trocadas entre agentes serão resolvidos?</strong> (Estratégias de resolução de conflitos)</li><li><strong>Como o sucesso ou a falha de uma interação entre agentes será monitorado e reportado?</strong> (Feedback e diagnóstico)</li></ul><p>Sei que são muitas perguntas, mas pense positivo, voce haveria de perguntar muito mais em uma coleta de requisitos :) .</p><p>Ao responder a essas perguntas de forma detalhada para cada agente pensado na etapa anterior e para suas interações, você estará construindo um planejamento específico robusto que aumentará significativamente as chances de sucesso do seu LLM-MAS. Essa clareza operacional é fundamental para evitar ambiguidades, otimizar o fluxo de trabalho e garantir que todos os componentes do sistema trabalhem juntos de forma coesa.</p><h3>3 — Arquitetura do Sistema</h3><p>É plano estrutural de alto nível que define como os diferentes agentes são organizados, como eles se comunicam e interagem entre si, e como o sistema como um todo é construído para atingir seus objetivos. É o esqueleto que sustenta a inteligência distribuída do sistema.</p><p>Assim como a arquitetura de um prédio define como os cômodos se conectam e como as pessoas se movem dentro dele, a arquitetura de um LLM-MAS define o fluxo de informações, a coordenação das ações e a distribuição das responsabilidades entre os agentes. Uma arquitetura bem projetada é crucial para garantir a eficiência, a escalabilidade, a robustez e a facilidade de manutenção do sistema.</p><p>Na leitura que fiz, pude perceber que existem ao menos três tipos de arquiteturas simples (Que não se modificam de maneira dinamica):</p><ul><li><strong>Arquitetura de Nível Equivalente (Equi-Level):</strong> Nesta arquitetura, todos os agentes operam no mesmo nível hierárquico, sem uma distinção formal de superioridade ou subordinação. Eles se comunicam diretamente entre si, geralmente em um modelo ponto a ponto ou através de um ambiente compartilhado (como um “quadro negro” digital ou uma memória comum), a flexibilidade desse ambiente o torna adaptativo, alguns exemplos legais são os algoritmos que ponderam a resposta pela democracia como o majority-voting.</li><li><strong>Arquitetura Hierárquica: </strong>Nesta arquitetura os agentes são organizados em uma estrutura de árvore ou pirâmide, com diferentes níveis de autoridade e responsabilidade. Agentes de nível superior supervisionam e coordenam as ações dos agentes de nível inferior. Essa arquitetura possui um controle maior da informação e do caminho que ela percorre, ele tende a ser mais fácil de debugar mas pode ser complicado paralelizar.</li><li><strong>Arquitetura Aninhada: </strong>Esta arquitetura envolve a criação de grupos de agentes (sub-sistemas ou “coalizões”) que operam dentro de outros agentes ou grupos maiores. Isso cria uma hierarquia de sistemas dentro de sistemas, permitindo a construção de sistemas complexos com diferentes níveis de abstração e especialização. É um meior termo entre as duas arquiteturas anteriores, se apoia na modulariadade, reusabilidade e encapsulamente para adaptar sua estrutura a necessidade do problema.</li><li><strong>Estrutura Dinâmica: </strong>Nesta arquitetura, a estrutura do sistema pode mudar dinamicamente em resposta às necessidades da tarefa, ao estado do ambiente ou ao desempenho dos próprios agentes. Novos agentes podem ser criados ou desativados, e as conexões entre eles podem evoluir ao longo do tempo.</li></ul><p>A escolha da arquitetura mais adequada dependerá dos requisitos específicos do seu LLM-MAS, incluindo a natureza do problema, a complexidade das tarefas, a necessidade de coordenação, os requisitos de escalabilidade e resiliência, e as restrições de recursos. Muitas vezes, sistemas complexos podem até mesmo combinar elementos de diferentes arquiteturas para aproveitar seus respectivos benefícios.</p><h3>4 — Gerenciamento de Memória</h3><p>Ufa!, estamos chegando ao final, essa ultima etapa refere-se aos mecanismos e estratégias utilizadas para permitir que os agentes armazenem, recuperem e utilizem informações relevantes ao longo do tempo e entre diferentes interações ou tarefas. Assim como nós humanos usam a memória para aprender, recordar experiências passadas e construir conhecimento, os agentes em um LLM-MAS precisam de formas eficazes de “lembrar” informações para tomar decisões mais informadas, manter a coerência nas interações e até memo melhorar seu desempenho ao longo do tempo.</p><p>O gerenciamento de memória em LLM-MAS aborda diferentes horizontes temporais e tipos de informação, reconhecendo que nem toda informação é igualmente importante ou precisa ser armazenada da mesma maneira. Os tipos de memoria (Longo Termo, Curto Termo, Data Storage Externo, Episodic Memory, Consensus Memory) representam diferentes abordagens para lidar com essa necessidade de “lembrança” nos agentes.</p><ul><li><strong>A memória de curto termo:</strong> Também conhecida como memória de trabalho ou contexto, dá a capacidade do agente de reter e processar informações relevantes para a tarefa ou apenas na interação atual. É análoga à nossa memória de trabalho imediata, que nos permite manter informações em mente para realizar uma tarefa específica (como lembrar os passos de uma receita enquanto cozinhamos).</li><li><strong>A memória de longo termo: </strong>É a capacidade do agente de armazenar e recuperar informações relevantes ao longo de múltiplas interações e tarefas, persistindo além da janela de contexto imediata. É análoga à nossa memória de longo prazo, onde armazenamos conhecimentos, fatos e experiências que podemos recordar posteriormente. (como onde voce esta guardando as informações desta singela publicação 🤖)</li><li><strong>Data Storage Externo: </strong>Refere-se ao uso de sistemas de armazenamento de dados que são externos ao próprio agente e à sua memória de curto e longo prazo primária. Isso permite que os agentes acessem grandes volumes de informações, dados estruturados ou recursos específicos que não seriam práticos armazenar diretamente em sua memória. (como o acessos a bancos de dados para consultar preços e disponibilidade de produtos)</li><li><strong>Memória Episódica<em> (Episodic Memory):</em></strong> É<em> </em>a capacidade de um agente de lembrar de experiências específicas ou “episódios” que vivenciou e possuem muito peso para o julgamento da tarefa, incluindo o contexto temporal e sequencial desses eventos. É análoga à nossa memória de eventos autobiográficos (lembrar de um encontro específico, uma conversa ou uma tarefa que realizamos).</li><li><strong>Memória de Consenso<em> (Consensus Memory): </em></strong>A memória de consenso é um mecanismo para que múltiplos agentes em um sistema compartilhem e mantenham um conjunto consistente de informações ou conhecimento. Isso garante que todos os agentes operem com uma visão comum do estado do sistema, do mundo ou de informações relevantes. (por exemplo em um sistema de controle de tráfego aéreo, todos os controladores (agentes) compartilham informações atualizadas sobre a posição das aeronaves.)</li></ul><p>Entender os tipos de memoria e quais eu preciso usar na minha arquitetura LLM-MAS pode evitar muito retrabalho futuro, por isso elaborei esse pequeno (e ultimo, juro!) conjunto de perguntas guias:</p><ul><li><strong>Os agentes precisam reter informações apenas dentro de uma única interação ou tarefa?</strong> (Se sim, a memória de curto termo pode ser suficiente para muitas tarefas.)</li><li><strong>As informações são fatos, conhecimento geral ou dados específicos do domínio que precisam ser acessados repetidamente?</strong> (Memória de longo termo com mecanismos de busca eficientes é necessária.)</li><li><strong>Os agentes precisam lembrar de informações entre diferentes interações com o mesmo usuário ou sobre o mesmo tópico ao longo do tempo?</strong> (Isso aponta para a necessidade de memória de longo termo.)</li><li><strong>Os agentes precisam aprender com suas experiências passadas em tarefas específicas?</strong> (A memória episódica pode ser valiosa aqui.)</li><li><strong>Os agentes precisam acessar grandes volumes de dados estruturados ou informações de fontes externas?</strong> (Armazenamento de dados externo será essencial.)</li><li><strong>É importante que os agentes aprendam com suas experiências e melhorem seu desempenho ao longo do tempo?</strong> (A memória de longo termo e a memória episódica podem facilitar o aprendizado.)</li><li><strong>Os agentes precisam se adaptar a diferentes usuários ou situações com base em interações passadas?</strong> (A memória de longo termo para perfis de usuários e a memória episódica para experiências específicas podem ser relevantes.)</li><li><strong>Os agentes precisam compartilhar informações e manter um entendimento comum do estado do sistema ou do mundo?</strong> (A memória de consenso será importante.)</li><li><strong>As tarefas são simples e isoladas, ou complexas e sequenciais?</strong> (Tarefas complexas podem se beneficiar da capacidade de lembrar passos anteriores e resultados parciais, sugerindo memória de curto e longo termo.)</li><li><strong>Quais são as restrições de recursos computacionais para o armazenamento e a recuperação de informações?</strong> (A escolha do tipo de memória e sua implementação deve considerar a eficiência e o custo.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwYv8UkpJJdr_iJyaPTyOA.jpeg" /><figcaption>AI generated image with <a href="https://labs.google/fx/pt/tools/image-fx">Google FX</a>, prompt: “An sketchy of a happy human professor with robotic arms showing in the black board writing “Fim!”, beside the scene you can see a window with a nigthly good weather outside. painted illustration”</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1cda84327b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Porque precisamos de LLM Multi Agentes?]]></title>
            <link>https://medium.com/@luizcf14/porque-precisamos-de-llm-multi-agentes-2e10549c2c67?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e10549c2c67</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 13:32:41 GMT</pubDate>
            <atom:updated>2025-04-10T13:32:41.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GA2ing2V694msSfJVQwbA.jpeg" /><figcaption>Agente único vs múltiplos agentes, gerado com<a href="https://labs.google/fx/pt/tools/image-fx"> Google Image FX</a>.</figcaption></figure><p><strong>Conceitos e Objetivos</strong></p><p>O campo da inteligência artificial (IA) está testemunhando uma mudança de paradigma significativa com o advento dos Sistemas de Múltiplos Agentes baseados em Modelos de Linguagem Grandes (LLM-MAS).</p><p>Esses sistemas são definidos como conjuntos de múltiplos agentes inteligentes, cada um impulsionado por um agente de LLM distinto (até mesmo combinando modelos de LLM distintas), que interagem e colaboram (ou às vezes competem) para chegar em objetivos complexos que excedem as capacidades de um único agente. <a href="https://doi.org/10.1007/s44336-024-00009-2">[Referência]</a></p><p>No anseio para resolução de problemas complexos a inclusão de LLM`s pode ser necessária, e às vezes nos deparamos com aplicações que tangem os limites de agentes únicos, que inclusive aumentam a probabilidade de alucinações e perdas de contexto. <a href="https://arxiv.org/abs/2406.05720">[Referência]</a></p><p>Para essas situações onde a complexidade é alta e o custo de treino ou refinamento é alto, é que existe um grande ganho no uso de LLM-MAS.</p><p><strong>Motivação</strong></p><p>Ao dividir um problema grande em subtarefas e atribuí-las a agentes com habilidades específicas, os LLM-MAS podem lidar com fluxos de trabalho engenhosos de forma mais eficaz.</p><p>Em segundo lugar, a modularidade e redundância inerente aos sistemas multiagentes contribui para maior robustez e tolerância a falhas; a falha de um único agente não necessariamente paralisa todo o sistema.</p><p>Terceiro, os LLM-MAS figuram maior potencial de adaptabilidade e escalabilidade, permitindo que os sistemas se ajustem dinamicamente a ambientes ou requisitos de tarefas em mudança, adicionando, removendo ou modificando agentes.</p><p><strong>Onde obter mais informações:</strong></p><p>1 — <a href="https://doi.org/10.1007/s44336-024-00009-2">https://doi.org/10.1007/s44336-024-00009-2</a></p><p>2 — <a href="https://www.nature.com/articles/s41746-025-01550-0">https://www.nature.com/articles/s41746-025-01550-0</a></p><p>3- <a href="https://www.nature.com/articles/s41599-024-03611-3">https://www.nature.com/articles/s41599-024-03611-3</a></p><p>4 — <a href="https://arxiv.org/pdf/2402.03578">https://arxiv.org/pdf/2402.03578</a></p><p>5 — <a href="https://arxiv.org/pdf/2402.01680">https://arxiv.org/pdf/2402.01680</a></p><p>6 — <a href="https://arxiv.org/abs/2406.05720">https://arxiv.org/abs/2406.05720</a> (esse é o mais divertido)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e10549c2c67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Ascensão das LLMs: Uma Jornada da Ficção Científica à Realidade]]></title>
            <link>https://medium.com/@luizcf14/a-ascens%C3%A3o-das-llms-uma-jornada-da-fic%C3%A7%C3%A3o-cient%C3%ADfica-%C3%A0-realidade-ff37c675f0d5?source=rss-d9269c051ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff37c675f0d5</guid>
            <category><![CDATA[history-of-technology]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gemma2]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Luiz Neto]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 15:58:35 GMT</pubDate>
            <atom:updated>2024-11-16T16:03:16.887Z</atom:updated>
            <content:encoded><![CDATA[<p>Sumarização, auxilio a escrita, análise de sentimentos, transcrição e criação de conteúdo eram tarefas essencialmente dependente de humanos até pouco tempo atrás. Hoje, você pode ser considerado saudosista se decidir usar apenas a força humana para realizar essas tarefas.</p><p>Esse poder que parece ser a origem do super computador do Guia do Mochileiro das Galáxias, chama-se de LLM, em tradução direta Grande Modelo de Linguagem. As LLM`s estão um sub-campo do aprendizado de máquina chamado de Deep Learning, e estão revolucionando a maneira como interagimos com as máquinas e processamos a linguagem natural.</p><p>O objetivo aqui é entender o passado das redes e por onde passaram até que cheguemos no ponto de hoje.</p><p><strong>1940–1999 — As primeiras redes, o Multi Layer Perceptron, a ELIZA e os N-Grams</strong></p><p>Foi nesse ínterim que o mundo contemplou pela primeira vez os <em>papers </em>que fundamentam a arquitetura bioinspirada de uma rede multi camadas baseada em na compreensão que tínhamos, em 1955, sobre um tipo de neurônio.</p><p>Não posso deixar de comentar que nessa época a computação criava o primeiro software de diálogo, o chatbot ELIZA, que teve sua inspiração <a href="https://pt.wikipedia.org/wiki/ELIZA">na peça de teatro ‘Pigmalião’, Eliza Doolittle, escrita por George Bernard Shaw, em 1913.</a></p><p>Perto do fim dos anos 90, concebemos os N-Grams que apesar de sua simplicidade, servem até hoje como blocos de construção para modelos estatísticos de linguagem, permitindo que os computadores analisassem sequências de palavras e previssem a próxima palavra em uma frase com base na frequência de ocorrência de combinações de palavras anteriores. Essa técnica, embora limitada em sua capacidade de capturar dependências de longo alcance e nuances semânticas, pavimentou o caminho para o desenvolvimento de modelos mais sofisticados.</p><p>E antes dessa era acabar, logo percebemos que os MLP`s eram bons para resolver problemas não lineares, que o chatbot ELIZA e seu parceiro PARRY eram avanços que marcariam uma era, e que os N-Grans nos possibilitavam sintetizar a logística de qualquer linguagem nos permitindo avançar os limites da interação entre a computação e a linguística.</p><p>Mas a humanidade também percebeu que esses modelos, os chatbots e o N-Gram eram pouco democráticos e que só funcionavam de verdade se você tivesse um super computador disponível, e por esse motivo o final dessa era também foi marcado pelo desuso das redes neurais.</p><p>(Acrescentar aqui uma imagem sobre o número de papers)</p><p><strong>2000–2016 — RNN, LSTMs e Word2Vec</strong></p><p>As redes neurais recorrentes dão um grande salto as redes que usavam do mecanismo de<em> feed forward</em>, uma vez que o processo de aprendizado se dá mediante múltiplas passagens conseguimos obter um <em>fitting</em> melhor para processos mais complexos como o reconhecimento de voz e processos dependentes do tempo.</p><p>Em um curto espaço de tempo conhecemos as LSTM`s, que surgiram para solucionar um problema crítico das redes neurais recorrentes (RNNs): a dificuldade de capturar dependências de longo alcance em sequências de dados, como frases longas. Imagine tentar lembrar a primeira palavra de um parágrafo após ler até o final — as RNNs básicas “esqueciam” informações importantes ao longo do caminho.</p><p>Imagine que cada palavra em um idioma seja como uma pessoa com uma personalidade única. Para que um computador “entenda” essa palavra, precisamos descrevê-la de alguma forma que capture sua essência, seus relacionamentos com outras palavras e o contexto em que ela geralmente aparece. Foi em 2013 que o Google apresentou ao mundo o World2Vec que cria um “retrato” matemático vetorial das palavras, representando não só a sua complexidade de sentido como a sua possibilidade de relação semântica.</p><p>Esses parecem ter sido só três pequenos avanços, mas essa era foi marcada por muita velocidade nas publicações cientificas que marcavam o surgimento de um novo e forte campo no Machine Learning, o Deep Learning. Ressalto que aqui já existiam as primeiras GPUs voltadas para processamento massivo de dados o que garantiu um primeiro passo no sentido de democratizar os experimentos científicos e os softwares, uma vez que custavam bem menos que os super computadores.</p><p>Por fim, as CNNs, RNNs e as LSTMs simbolizavam um avanço massivo nas possibilidades de compreensão do mundo real pela computação, em paralelo o World2Vec contribuiu significativamente para a elaboração de modelos de palavras mais modernos como o GLoVe e o FastText, que hoje tem amplo uso na construçao de LLM`s.</p><p><strong>2017 — Hoje — A revolução dos Transformers</strong></p><p><em>Attention is All You Need</em>, é o título do artigo que mais li em toda a minha vida, não só pela audácia dos autores como pela intrigante e revolucionara proposta que fizeram ao mundo. A arquitetura de um <em>transformer</em> estava sendo apresentada ali, que de maneira resumida fugia da ideia do “mecanismo de recorrência” das RNNs (que eu estudei por mais de 10 anos) para apostar no “mecanismo de atenção” especificamente o “<em>Multi-Head attention</em>” que suportado por tokens de memória (ordenação) permitia que as palavras/tokens prestassem atenção umas nas outras e isso definiria a importância individual e o sentido da frase final. Esse paralelismo do mecanismo de atenção e os tokens de memória permitiram a Transformer ser computacionalmente mais econômico e escalável que as redes aqui já citadas.</p><p>Nascem os modelos de linguagem BERT e GPT.</p><p>BERT é “<em>Bidirectional Encoder Representations from Transformers</em>” criado em 2018 é o primeiro modelo do Google que utiliza da tecnica de “Masked Language Modeling” (MLM) para aprender as representações bi-direcionais entre palavras. Diferente dos modelos anteriores que processavam as frases de maneira unidirecional o BERT tinha a ideia de ler a frase em “sentido duplo” o que, de fato, permitiu uma melhor compreensão de trechos de longos de texto.</p><p>GPT é “Generative Pre-trained Transformer” criado pela OpenAI em 2018, é um modelo também baseado em <em>Transformer </em>especialista na geração de textos. Diferente do BERT, o GPT se apoia no uso massivo e paralelo de um elemento da arquitetura Transformer chamado de decodificador, os decodificadores tem a responsabilidade de transformar a informação interna da rede em uma saída coerente e contextualmente relevante. Além disso, os decodificadores presentes no GPT usam de técnica de “decodificação auto regressiva” que basicamente é uma das formas de prever a próxima palavra a ser gerada baseada no contexto já escrito, permitindo uma maior coerência do texto de saída, mesmo em textos longos.</p><p>Esses modelos são os avós dos modelos que temos hoje, eles nem eram considerados “<em>Large”, pois</em> possuíam apenas milhões de parâmetros internos. Modelos como Cloude, GPT4, Gemini 1.5 e Gemma 2 possuem na casa de centenas e bilhoes de parametros internos.</p><p>Esse artigo é de cunho meramente informativo, sobre os passos importantes que tomamos para chegar até os modelos atuais e talvez para entendermos porque chegamos até aqui.</p><p>Modelos multimodais e grandes serão cada vez mais comuns de serem encontrados, de fato ate mesmo iniciativas pequenas podem criar modelos exclusivos do zero, uma pena que pela relação entre a capacidade computacional média e o tamanho de modelos com bilhões ou trilhões e parâmetros estejamos caminhando na contramão da democratização. Criando verdadeiros “Pensadores Profundos” para responder perguntas que poderiam estar sendo feitas na Wikipedia ou nos tradicionais buscadores, consumindo muito menos energia elétrica e ajudando a salvar o planeta.</p><p>Eu pessoalmente, gosto de apostar no uso de modelos menores e mais eficientes como o <a href="https://arxiv.org/abs/2408.00118">Gemma 2</a>, que possui uma arquitetura muito bem documentada em um tamanho razoável, e que me permite fazer fining tunnings e re-treinos usando o hardware local.</p><p>Referencias:</p><ul><li><a href="https://blog.dsacademy.com.br/llms-e-a-evolucao-da-ia-generativa/">LLMs e a Evolução da IA Generativa - Data Science Academy</a></li><li><a href="https://www.guilhermefavaron.com.br/post/os-invernos-da-ia-ciclos-de-ascensao-e-queda-na-historia-da-inteligencia-artificial">Os Invernos da IA: Ciclos de Ascensão e Queda na História da Inteligência Artificial</a></li></ul><p><a href="https://www.assemblyai.com/blog/llm-use-cases/">https://www.assemblyai.com/blog/llm-use-cases/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff37c675f0d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>