<?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 Guaranta Almeida on Medium]]></title>
        <description><![CDATA[Stories by Guaranta Almeida on Medium]]></description>
        <link>https://medium.com/@guaranta?source=rss-a618c5fb18b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*M6mNo4mKZn359jnt</url>
            <title>Stories by Guaranta Almeida on Medium</title>
            <link>https://medium.com/@guaranta?source=rss-a618c5fb18b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 01:24:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guaranta/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[Um MoE ajustado no lugar do LLM denso: 4× mais atendimento na mesma GPU]]></title>
            <link>https://medium.com/@guaranta/um-moe-ajustado-no-lugar-do-llm-denso-4-mais-atendimento-na-mesma-gpu-db8bf433ca63?source=rss-a618c5fb18b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/db8bf433ca63</guid>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[moe]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <dc:creator><![CDATA[Guaranta Almeida]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 17:29:22 GMT</pubDate>
            <atom:updated>2026-11-19T02:12:12.976Z</atom:updated>
            <content:encoded><![CDATA[<h3>Como medimos, ajustamos e trocamos o modelo principal de um assistente de operações — e o que não funcionou no caminho</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzjOzuUYGb92pj_YOZaxIQ.png" /></figure><p>Um assistente de operações responde perguntas sobre uma infraestrutura monitorada: o que está acontecendo no parque agora, por que um link caiu, se um alerta já aconteceu antes. As respostas saem de ferramentas que consultam o monitoramento; o modelo de linguagem só redige. A regra é dura: nenhum número pode ser inventado, e cada frase passa por uma guarda que a confere contra a evidência.</p><p>O modelo era um Qwen3.8–27B denso, em Q4, numa única RTX A5000 de 24 GB. Funcionava, mas não escalava: com dois operadores perguntando ao mesmo tempo, a resposta passava de 15 s; com oito, o primeiro token levava 22 s. A pergunta era se um modelo MoE, que ativa só uma fração dos parâmetros por ficha, poderia assumir sem inventar mais, e o que custaria provar isso.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXNwhJf5pqKFjcX1ko0_Ag.png" /><figcaption>O caso em quatro números: capacidade, espera, qualidade e estabilidade. *Operadores: estimativa a partir da vazão medida.</figcaption></figure><blockquote><strong><em>Na mesma A5000: de ~20–30 para ~80–120 operadores atendidos</em></strong></blockquote><p>≈10 → ≈40 respostas por minuto, para operadores que perguntam a cada 2–3 min. 1º token com 8 simultâneos: 22,3 s → 0,4 s. <em>Estimativa a partir da vazão medida (respostas/min × intervalo entre perguntas); não é teste com operadores reais.</em></p><h3>Onde o modelo fica no sistema</h3><p>O modelo não decide nem calcula. A pergunta passa pela leitura da intenção (léxico + classificador LAYA), por um plano e por ferramentas tipadas que consultam o monitoramento e devolvem agregados, nunca dado cru. O modelo redige a partir do bloco DADOS, e a <strong>guarda</strong> confere cada número e cada nome contra a evidência: remove o que tem precisão comprovada e marca como “não verificada” o resto.</p><p>O modelo é a peça mais cara do sistema e a única que inventa. Tudo o que é decisão tipada ou cálculo fica no código. Trocá-lo mexe num elo só.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACgffzWU4XstOibj8vzfsg.png" /><figcaption>Pergunta, intenção, plano, ferramentas, modelo, guarda, operador. A troca muda um elo só.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*QtkERivAm_uJ9hUd_OyzMA.gif" /><figcaption>A guarda confere frase a frase (exemplo ilustrativo): cada número e nome é conferido contra o bloco DADOS; a guarda apaga só onde a precisão medida da regra é ≥ 80% e marca “não verificada” o resto.</figcaption></figure><h3>Como medimos</h3><p>Trocar o modelo de um sistema que não pode inventar exige uma régua que não dependa de quem escreveu a frase. 96 perguntas pareadas, nenhuma usada em treino. Backend congelado num commit. A verdade de cada frase vem de conferidores cegos, que não sabem qual modelo escreveu nem o que a guarda decidiu. Ao todo, 16.146 frases conferidas no ciclo.</p><p>Duas métricas: <strong>invenção própria</strong> (frases falsas que a evidência desmente ÷ frases julgadas) e <strong>falsas que chegam sem marcação</strong> (o que o operador lê como fato). E toda comparação final é A/B na mesma janela: rodadas em horários diferentes veem estados diferentes do monitoramento.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXWJ6jM8jWbB-CsDndBAmQ.png" /><figcaption>Como medimos.</figcaption></figure><h3>A triagem: três modelos, uma bancada</h3><p>Três candidatos passaram pela mesma bancada. O Qwen3–30B-A3B-Instruct-2507 saiu: inventa 4× mais que o denso (16,1% contra 4,0%). O Qwen3.6–35B-A3B, um MoE com cerca de 3B ativos, é cerca de 4× mais rápido, mas inventa 1,7× mais. Não passava no critério “qualidade não pior” e virou o candidato ao ajuste.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOLklrNjgXhST_3oQE1ZVg.png" /></figure><h3>Ajuste fino de comportamento, não de conhecimento</h3><p>O ajuste não ensina telecom: o dado operacional envelhece, e isso é papel do RAG e das ferramentas. Ensina comportamento: não inventar, escrever “N de TOTAL”, não chamar o agora de período.</p><ul><li><strong>478 perguntas</strong> de desenvolvimento e reais, nenhuma das 96 de medida e nenhuma dos cegos.</li><li><strong>4.396 frases conferidas às cegas</strong>, e cada falsa corrigida pelo conferidor usando só a evidência que o modelo viu.</li><li><strong>Pares sobre o mesmo prompt.</strong> Rejeitada: o texto original. Escolhida: o mesmo texto com só as frases falsas trocadas ou apagadas.</li><li><strong>243 pares DPO</strong> (486 frases corrigidas) e <strong>214 exemplos SFT</strong>, com respostas 100% verdadeiras.</li></ul><p>Por que não usar a resposta de outro modelo como escolhida? Ela traria números que não estão no prompt, e o par ensinaria o modelo a citar o que não viu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YC5-Am7bxPySe1Rgu1rAsg.png" /><figcaption>Pares sobre o mesmo prompt: só a frase falsa muda (exemplo ilustrativo).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*RrHp-2Xt5NmghxtzqxC09g.gif" /><figcaption>Como nasce um par DPO (exemplo ilustrativo): o conferidor cego marca a frase falsa e reescreve só ela; rejeitada e escolhida têm o mesmo prompt. Totais medidos: 4.396 frases, 243 pares DPO, 214 exemplos SFT.</figcaption></figure><p>Anonimização sempre: hosts preservam o papel (hypervisor01-clnt-oper), VM vira VM-&lt;id&gt;, IP vira endereço de documentação, e o conjunto tem 0 ocorrência do cliente. Numa revisão manual de critério, frases que citavam certo o limiar contratual, que estava no prompt, voltaram a verdadeiras (9 de 14).</p><h3>O treino: LoRA, SFT, DPO e uma quantização sob medida</h3><p>LoRA bf16 de rank 16 só na atenção, no DeltaNet e no expert compartilhado; os experts roteados ficaram intactos. SFT por 1 época, DPO por 2 (β 0,1), numa RTX PRO 6000 de 96 GB, em cerca de 25 min. Depois da mescla, uma imatrix com 876 mil fichas do domínio guiou uma quantização mista: Q8_0 nas partes que o LoRA tocou, IQ3_S no gate e no up dos experts, IQ4_XS no down. São 17,49 GB, com KLD de 0,42, contra 0,59 de um IQ4_XS uniforme de 17,64 GB.</p><p>Base e ajustado foram quantizados com a mesma receita, para a comparação medir só o treino.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoDz0DgQkTK-CaiAtiiU2Q.png" /><figcaption>A receita: LoRA só no comportamento, SFT e DPO, imatrix do domínio e quantização mista.</figcaption></figure><h3>O resultado v1, e o laço</h3><p>Com as ferramentas antigas, a invenção própria caiu de 7,2% para 6,1%: −15%, não significativo. Mas 3 a 5 de 84 respostas entravam em laço: a mesma frase repetida até 65 vezes, até bater em 1.400 fichas. O modelo base: zero.</p><p>A causa: o DPO baixou também a probabilidade das respostas escolhidas (recompensa de −1,65 na validação), só menos que a das rejeitadas. É o deslocamento de verossimilhança, uma receita conhecida de degeneração.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNEju_luDHkOAP2-J3ylmg.png" /><figcaption>v1 × v2: o laço do DPO puro e o que o termo de SFT devolveu.</figcaption></figure><h3>O que não funcionou</h3><p>No caminho, quatro tentativas foram medidas e saíram. Oito regras novas no prompt pioraram justamente os erros que descreviam: listar um conceito induz o modelo a usá-lo. O amostrador DRY do llama.cpp reduziu os laços de 3 para 1, mas os nomes de host fora do inventário foram de 12 para 92. Nome errado é pior que laço.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXcxvnyhEOADUtGiBBzcow.png" /><figcaption>Tentamos, medimos, descartamos.</figcaption></figure><h3>O que funcionou</h3><ol><li><strong>Ferramentas e guarda, antes do modelo.</strong> O maior ganho de qualidade do ciclo não veio do modelo. No 27B, as falsas que chegam sem marcação caíram de 8,1% para 3,7% (z = 3,35), e as frases verdadeiras apagadas foram de 29 para 0: a guarda passou a marcar “não verificada” onde sua precisão medida é menor que 80%, e só apaga onde é de 80% ou mais.</li><li><strong>Com as ferramentas novas, o ajuste passou a valer.</strong> MoE ajustado: 4,8% de falsas sem marcação. MoE base: 9,1%.</li><li><strong>Ajuste v2: DPO com um termo de SFT.</strong> RPO, com α = 1: a recompensa das escolhidas foi de −1,65 para −0,90, e os laços longos sumiram. Nos 50 prompts de teste: base 0, v1 3, v2 1 (curto, 72 fichas).</li><li><strong>Uma trava de laço no cliente.</strong> A síntese vem em streaming. Na 3ª repetição da mesma frase, a geração é cortada, a vaga do servidor é solta e a interrupção vira lacuna declarada. A trava não mexe na amostragem, então não deforma nome. Com o v2: 0 laço em 96 perguntas.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*VeHpa04qKecby9ZXzeeuaA.gif" /><figcaption>O laço e a trava (ilustrativo): a mesma frase começa a repetir, e na 3ª repetição a trava corta a geração e solta a vaga.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Z-LUjOvplsBMEn2guhygA.png" /><figcaption>Tabela final: o MoE v2 com trava fica dentro do ruído do 27B (z ≈ −0,9).</figcaption></figure><h3>Capacidade na A5000</h3><p>Prompts reais de síntese, de 1 a 12 operadores simultâneos, em streaming. Com 8 simultâneos, o 1º token do 27B levava 22,3 s; o do MoE v2 com 8 vagas, 0,4 s. Respostas por minuto: 10,3 no 27B, 39,0 no MoE com 8 vagas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6MWEmocCAb_rtL9oQ9IhQ.png" /><figcaption>Resposta p50, 1º token e respostas por minuto: 27B com 4 vagas, MoE v2 com 4 e com 8 vagas.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJoTYEdscrIhlVaEKe7W5Q.png" /><figcaption>Os números medidos de capacidade.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*a97vOm9AkXl4b2xHE8J0og.gif" /><figcaption>Oito operadores ao mesmo tempo: a fila do 27B e o MoE com 8 vagas (tempos individuais ilustrativos, medianas medidas).</figcaption></figure><p>Por que 8 vagas cabem: o MoE híbrido (DeltaNet + atenção) guarda KV só nas camadas de atenção, cerca de 5× menos que o denso. A pilha inteira ficou em 20,3 GB, contra 22,1 GB do 27B, numa placa de 24,5 GB. Com cerca de 40 respostas por minuto, a mesma placa atende algo como 80 a 120 operadores que perguntam a cada 2 a 3 minutos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZdT1k3YGB7godONi_tDUg.png" /><figcaption>VRAM da pilha na A5000: modelo, embeddings, reranker e classificador.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*1_V0kf8dFQaC9GdhsT9yeQ.gif" /><figcaption>Por que 8 vagas cabem: no denso, toda camada guarda KV a cada vaga; no MoE híbrido, só as de atenção (~5× menos). Totais de VRAM medidos; camadas e divisão ilustrativas.</figcaption></figure><p>Quantos operadores isso atende? Com 10,3 respostas por minuto, o 27B atendia algo como 20 a 30 operadores que perguntam a cada 2 a 3 minutos (10,3 × 2 = 20,6; 10,3 × 3 = 30,9). Com cerca de 40 respostas por minuto (39,0 com 8 vagas a 12 simultâneos; 42,3 com 4 vagas), a mesma placa atende algo como 80 a 120 (40 × 2 = 80; 40 × 3 = 120): cerca de 4× mais operadores na mesma GPU. É uma estimativa a partir da vazão medida (respostas/min × intervalo entre perguntas); não é teste com operadores reais.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*So3h8Wl17aRs-oqtmf99VQ.png" /><figcaption>Quantos operadores a mesma A5000 atende: 27B, 10,3 respostas/min → ~20–30; MoE v2, ~40 → ~80–120. Estimativa a partir da vazão medida, não teste com operadores reais.</figcaption></figure><h3>A troca em produção</h3><p>Serviço novo no compose, com a imagem oficial do llama.cpp, publicado no mesmo endereço do modelo antigo: nenhum cliente mudou de configuração. (A imagem compilada localmente calculava IQ3_S errado na GPU, um achado do piloto.) O denso fica no disco, com a unit desabilitada: volta atrás em cerca de 1 min.</p><p>No dia da troca, o servidor teve cerca de 10 reinícios por falta de energia. Antes do deploy: 30+ min estável, journal sem erro de disco, integrity_check do banco = ok, checksum do modelo igual. Depois: health, uma resposta real (0,55 s), VRAM e o SHA do código em produção.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RphLMa0f-UmrlPau8L767g.png" /><figcaption>A troca: mesmo endereço, volta atrás em ~1 min e um portão de estabilidade.</figcaption></figure><h3>Lições do caso</h3><ol><li><strong>Mude a ferramenta antes do modelo.</strong> O maior ganho de qualidade veio de consertar ferramentas e calibrar a guarda.</li><li><strong>Pares sobre o mesmo prompt.</strong> A escolhida é a mesma resposta corrigida, não a de outro modelo. Senão você ensina a citar o que não está no prompt.</li><li><strong>DPO puro degrada.</strong> Sem termo de SFT, a probabilidade das boas respostas cai junto, e o modelo entra em laço.</li><li><strong>Regra no prompt não é de graça.</strong> Listar oito cuidados aumentou os erros que eles descreviam.</li><li><strong>Proteja no código o que o amostrador estraga.</strong> O anti-repetição do amostrador deformou nomes; a trava no cliente não.</li><li><strong>A/B na mesma janela, verdade às cegas.</strong> Com 600 a 900 frases por modelo, 1 a 2 pontos são ruído; comparar com medida antiga engana.</li></ol><p>Trabalhamos com agentes de IA como equipe: duas sessões de engenharia com divisão de arquivos e uma régua de aceite comum, conferidores cegos e um agente de treino. A IA acelerou a execução; as decisões e a responsabilidade pelos números continuaram humanas.</p><p><strong>Qual erro do seu assistente você está tentando corrigir no modelo, quando ele mora na ferramenta?</strong></p><p>Read in English:</p><p><a href="https://medium.com/@guaranta/a-tuned-moe-in-place-of-the-dense-llm-4-more-throughput-on-the-same-gpu-631be763a42d?sharedUserId=guaranta">https://medium.com/@guaranta/a-tuned-moe-in-place-of-the-dense-llm-4-more-throughput-on-the-same-gpu-631be763a42d?sharedUserId=guaranta</a></p><h3>Referências</h3><ol><li><strong>Qwen3.6–35B-A3B</strong> — model card: <a href="https://huggingface.co/Qwen/Qwen3.6-35B-A3B">huggingface.co/Qwen/Qwen3.6–35B-A3B</a></li><li><strong>Qwen3</strong> — Technical Report (arXiv 2505.09388): <a href="https://arxiv.org/abs/2505.09388">arxiv.org/abs/2505.09388</a></li><li><strong>DPO</strong> — Direct Preference Optimization (arXiv 2305.18290): <a href="https://arxiv.org/abs/2305.18290">arxiv.org/abs/2305.18290</a></li><li><strong>RPO</strong> — Iterative Reasoning Preference Optimization, DPO + NLL (arXiv 2404.19733): <a href="https://arxiv.org/abs/2404.19733">arxiv.org/abs/2404.19733</a></li><li><strong>LoRA</strong> — Low-Rank Adaptation of Large Language Models (arXiv 2106.09685): <a href="https://arxiv.org/abs/2106.09685">arxiv.org/abs/2106.09685</a></li><li><strong>TRL</strong> — DPOTrainer e loss_type: <a href="https://huggingface.co/docs/trl/dpo_trainer">huggingface.co/docs/trl/dpo_trainer</a></li><li><strong>llama.cpp</strong> — servidor, imatrix e quantização: <a href="https://github.com/ggml-org/llama.cpp">github.com/ggml-org/llama.cpp</a></li><li><strong>DRY sampler</strong> — proposta original: <a href="https://github.com/oobabooga/text-generation-webui/pull/5677">github.com/oobabooga/text-generation-webui/pull/5677</a></li><li><strong>LAYA</strong> — classificador de decisões tipadas usado na leitura: <a href="https://github.com/NandhaKishorM/laya">github.com/NandhaKishorM/laya</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db8bf433ca63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A tuned MoE in place of the dense LLM: 4× more answers on the same GPU]]></title>
            <link>https://medium.com/@guaranta/a-tuned-moe-in-place-of-the-dense-llm-4-more-throughput-on-the-same-gpu-631be763a42d?source=rss-a618c5fb18b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/631be763a42d</guid>
            <category><![CDATA[moe]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[Guaranta Almeida]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 02:07:27 GMT</pubDate>
            <atom:updated>2026-11-19T02:15:27.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>How we measured, fine-tuned and swapped the main model of an operations assistant — and what didn’t work along the way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXi57vR5ZKgVZ_8nDrJ6dQ.png" /></figure><p>An operations assistant answers questions about a monitored infrastructure: what is happening across the estate right now, why a link went down, whether an alert has fired before. The answers come from tools that query the monitoring system; the language model only writes them up. The rule is strict: no number may be invented, and every sentence goes through a guard that checks it against the evidence.</p><p>The model was a dense Qwen3.8–27B, in Q4, on a single 24 GB RTX A5000. It worked, but it didn’t scale: with two operators asking at the same time, an answer took more than 15 s; with eight, the first token took 22 s. The question was whether an MoE model, which activates only a fraction of its parameters per token, could take over without inventing more, and what it would take to prove it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXNwhJf5pqKFjcX1ko0_Ag.png" /><figcaption>The case in four numbers: capacity, wait, quality and stability. *Operators: estimate from measured throughput.</figcaption></figure><blockquote><strong><em>On the same A5000: from ~20–30 to ~80–120 operators served</em></strong></blockquote><p>≈10 → ≈40 answers per minute, for operators who ask every 2–3 min. TTFT with 8 concurrent: 22.3 s → 0.4 s. <em>Measured throughput (answers/min × time between questions); Teste with real operators.</em></p><h3>Where the model sits in the system</h3><p>The model neither decides nor calculates. The question goes through intent reading (lexicon + LAYA classifier), a plan and typed tools that query the monitoring system and return aggregates, never raw data. The model writes from the DATA block, and the <strong>guard</strong> checks every number and every name against the evidence: where its precision is proven, it removes what fails; the rest it flags as “unverified”.</p><p>The model is the most expensive part of the system and the only one that invents. Everything that is a typed decision or a calculation stays in code. Swapping it touches a single link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhlVi9CA1G2lTLPqjdgKvQ.png" /><figcaption>Question, intent, plan, tools, model, guard, operator. The swap changes a single link.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*MW8BcFS9_bzi0O2j8DT2Tw.gif" /><figcaption>The guard checks sentence by sentence (illustrative example): every number and name is checked against the DATA block; the guard deletes only where the rule’s measured precision is ≥ 80% and flags the rest “unverified”.</figcaption></figure><h3>How we measured</h3><p>Swapping the model of a system that must not invent requires a yardstick that doesn’t depend on who wrote the sentence. 96 paired questions, none used in training. Backend frozen at a commit. The truth of each sentence comes from blind checkers, who don’t know which model wrote it or what the guard decided. In total, 16,146 sentences checked in the cycle.</p><p>Two metrics: the <strong>own-invention rate</strong> (false sentences contradicted by the evidence ÷ sentences judged) and <strong>false sentences reaching the operator unflagged</strong> (what the operator reads as fact). And every final comparison is A/B in the same window: runs at different times see different states of the monitoring system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCYHJ27vnycZsG1BJThCgA.png" /><figcaption>How we measured.</figcaption></figure><h3>Triage: three models, one bench</h3><p>Three candidates went through the same bench. Qwen3–30B-A3B-Instruct-2507 was out: it invents 4× more than the dense model (16.1% vs 4.0%). Qwen3.6–35B-A3B, an MoE with about 3B active parameters, is about 4× faster, but invents 1.7× more. It failed the “quality no worse” criterion and became the fine-tuning candidate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yoqhWm_JFuefw-UJUkAL7Q.png" /><figcaption>Triage scoreboard. p50 latency of the 27B on the A5000; of the MoEs, on the RTX PRO 6000 (Blackwell).</figcaption></figure><p>The errors were behavioral, and the same in all three: concluding “there are no incidents” because there are no tickets; taking the slice for the whole (“8 most severe” becomes “most”); calling the snapshot of now “yesterday”; confusing node with VM; mislabeling severity.</p><h3>Fine-tuning behavior, not knowledge</h3><p>The fine-tuning doesn’t teach telecom: operational data goes stale, and that is the job of RAG and the tools. It teaches behavior: don’t invent, write “N of TOTAL”, don’t call now a period.</p><ul><li><strong>478 questions</strong>, development and real, none of the 96 used for measurement and none from the blind sets.</li><li><strong>4,396 sentences blind-checked</strong>, and each false one corrected by the checker using only the evidence the model saw.</li><li><strong>Same-prompt pairs.</strong> Rejected: the original text. Chosen: the same text with only the false sentences replaced or deleted.</li><li><strong>243 DPO pairs</strong> (486 corrected sentences) and <strong>214 SFT examples</strong>, with 100% true answers.</li></ul><p>Why not use another model’s answer as the chosen one? It would bring numbers that aren’t in the prompt, and the pair would teach the model to cite what it hasn’t seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tr67Ruj5EZwsxJd328Hew.png" /><figcaption>Same-prompt pairs: only the false sentence changes (illustrative example).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*nEXH45DBSKxYU4t9_gaEWA.gif" /><figcaption>How a DPO pair is born (illustrative example): the blind checker flags the false sentence and rewrites only that one; rejected and chosen share the same prompt. Measured totals: 4,396 sentences, 243 DPO pairs, 214 SFT examples.</figcaption></figure><p>Anonymization always: hosts keep their role (hypervisor01-clnt-oper), VM becomes VM-&lt;id&gt;, IP becomes a documentation address, and the set has 0 occurrences of the client. In a manual review of criteria, sentences that correctly cited the contractual threshold, which was in the prompt, were set back to true (9 of 14).</p><h3>Training: LoRA, SFT, DPO and a tailored quantization</h3><p>LoRA bf16 with rank 16 only on attention, DeltaNet and the shared expert; the routed experts were left intact. SFT for 1 epoch, DPO for 2 (β 0.1), on a 96 GB RTX PRO 6000, in about 25 min. After the merge, an imatrix built from 876 thousand domain tokens guided a mixed quantization: Q8_0 on the parts the LoRA touched, IQ3_S on the experts’ gate and up, IQ4_XS on down. That’s 17.49 GB, with a KLD of 0.42, vs 0.59 for a uniform IQ4_XS of 17.64 GB.</p><p>Base and tuned were quantized with the same recipe, so the comparison measures only the training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QrzBwhSkf0esRckT5igyA.png" /><figcaption>The recipe: LoRA on behavior only, SFT and DPO, a domain imatrix and mixed quantization.</figcaption></figure><h3>The v1 result, and the loop</h3><p>With the old tools, the own-invention rate fell from 7.2% to 6.1%: −15%, not significant. But 3 to 5 of 84 answers fell into a loop: the same sentence repeated up to 65 times, until hitting 1,400 tokens. The base model: zero.</p><p>The cause: DPO also lowered the probability of the chosen answers (reward of −1.65 on validation), just less than that of the rejected ones. This is likelihood displacement, a known recipe for degeneration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OHjZdqeFMUIBMuHqyPsRg.png" /><figcaption>v1 vs v2: the pure-DPO loop and what the SFT term gave back.</figcaption></figure><h3>What didn’t work</h3><p>Along the way, four attempts were measured and dropped. Eight new rules in the prompt worsened precisely the errors they described: listing a concept nudges the model to use it. The llama.cpp DRY sampler cut loops from 3 to 1, but host names outside the inventory went from 12 to 92. A wrong name is worse than a loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIO2G94YmJVCI98FWB9TsQ.png" /><figcaption>We tried, measured, discarded.</figcaption></figure><h3>What worked</h3><ol><li><strong>Tools and guard, before the model.</strong> The biggest quality gain of the cycle didn’t come from the model. On the 27B, false sentences reaching the operator unflagged fell from 8.1% to 3.7% (z = 3.35), and true sentences deleted went from 29 to 0: the guard now flags “unverified” where its measured precision is below 80%, and only deletes where it is 80% or higher.</li><li><strong>With the new tools, the fine-tuning started to pay off.</strong> Tuned MoE: 4.8% unflagged false sentences. Base MoE: 9.1%.</li><li><strong>Fine-tune v2: DPO with an SFT term.</strong> RPO, with α = 1: the reward of the chosen answers went from −1.65 to −0.90, and the long loops disappeared. On the 50 test prompts: base 0, v1 3, v2 1 (short, 72 tokens).</li><li><strong>A client-side loop breaker.</strong> The synthesis is streamed. On the 3rd repetition of the same sentence, generation is cut, the server slot is released and the interruption becomes a declared gap. The breaker doesn’t touch sampling, so it doesn’t mangle names. With v2: 0 loops in 96 questions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Pa2sdxkc3XZVJ1hmp5Csgg.gif" /><figcaption>The loop and the breaker (illustrative): the same sentence starts repeating, and on the 3rd repetition the breaker cuts generation and releases the slot.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoKLW8GWM_Pl3w-qZ70Vmw.png" /><figcaption>Final table: the MoE v2 with breaker is within the noise of the 27B (z ≈ −0.9).</figcaption></figure><h3>Capacity on the A5000</h3><p>Real synthesis prompts, from 1 to 12 concurrent operators, streamed. With 8 concurrent, the 27B’s time to first token (TTFT) was 22.3 s; the MoE v2 with 8 slots, 0.4 s. Answers per minute: 10.3 on the 27B, 39.0 on the MoE with 8 slots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXGr1YKglon9Dx9EyCPqnw.png" /><figcaption>p50 answer time, TTFT and answers per minute: 27B with 4 slots, MoE v2 with 4 and with 8 slots.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRS5VjsLt3vYoQytPZlgbQ.png" /><figcaption>The measured capacity numbers.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*ycmijBVYOTD2rJwV8OWqYQ.gif" /><figcaption>Eight operators at once: the 27B queue and the MoE with 8 slots (individual times illustrative, medians measured).</figcaption></figure><p>Why 8 slots fit: the hybrid MoE (DeltaNet + attention) keeps KV only in the attention layers, about 5× less than the dense model. The whole stack came to 20.3 GB, vs 22.1 GB for the 27B, on a 24.5 GB card. At about 40 answers per minute, the same card serves something like 80 to 120 operators who ask every 2 to 3 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56291eBVcGl20gQ9sAOGXQ.png" /><figcaption>Stack VRAM on the A5000: model, embeddings, reranker and classifier.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*IpMJK7gxX5oL3IgxFmN_Mg.gif" /><figcaption>Why 8 slots fit: in the dense model every layer keeps KV for each slot; in the hybrid MoE only the attention layers do (~5× less). VRAM totals measured; layers and split illustrative.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JhvyiTxNZ6rF9ywhuNtaQ.png" /><figcaption>How many operators the same A5000 serves: 27B, 10.3 answers/min → ~20–30; MoE v2, ~40 → ~80–120. Estimate from measured throughput, not a test with real operators.</figcaption></figure><h3>The swap in production</h3><p>A new service in the compose file, with the official llama.cpp image, published at the same address as the old model: no client changed its configuration. (The locally built image computed IQ3_S wrong on the GPU, a finding from the pilot.) The dense model stays on disk, with its unit disabled: rollback in about 1 min.</p><p>On swap day, the server had about 10 restarts due to power outages. Before the deploy: 30+ min stable, journal with no disk errors, database integrity_check = ok, model checksum matching. After: health, one real answer (0.55 s), VRAM and the SHA of the code in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xvKVma1fTiT-JKT2EYq7w.png" /><figcaption>The swap: same address, rollback in ~1 min and a stability gate.</figcaption></figure><h3>Lessons from the case</h3><ol><li><strong>Fix the tool before the model.</strong> The biggest quality gain came from fixing tools and calibrating the guard.</li><li><strong>Same-prompt pairs.</strong> The chosen answer is the same answer, corrected, not another model’s. Otherwise you teach it to cite what isn’t in the prompt.</li><li><strong>Pure DPO degrades.</strong> Without an SFT term, the probability of good answers drops too, and the model falls into loops.</li><li><strong>Prompt rules aren’t free.</strong> Listing eight cautions increased the very errors they described.</li><li><strong>Protect in code what the sampler breaks.</strong> The sampler’s anti-repetition mangled names; the client-side breaker didn’t.</li><li><strong>A/B in the same window, blind truth.</strong> With 600 to 900 sentences per model, 1 to 2 points are noise; comparing against an old measurement misleads.</li></ol><p>We worked with AI agents as a team: two engineering sessions with a split of files and a shared acceptance yardstick, blind checkers and a training agent. AI sped up execution; the decisions and the responsibility for the numbers remained human.</p><p><strong>Which of your assistant’s errors are you trying to fix in the model, when it lives in the tool?</strong></p><p>Leia em português: <a href="https://medium.com/@guaranta/um-moe-ajustado-no-lugar-do-llm-denso-4-mais-atendimento-na-mesma-gpu-db8bf433ca63?sharedUserId=guaranta">https://medium.com/@guaranta/um-moe-ajustado-no-lugar-do-llm-denso-4-mais-atendimento-na-mesma-gpu-db8bf433ca63?sharedUserId=guaranta</a></p><h3>References</h3><ol><li><strong>Qwen3.6–35B-A3B</strong> — model card: <a href="https://huggingface.co/Qwen/Qwen3.6-35B-A3B">huggingface.co/Qwen/Qwen3.6–35B-A3B</a></li><li><strong>Qwen3</strong> — Technical Report (arXiv 2505.09388): <a href="https://arxiv.org/abs/2505.09388">arxiv.org/abs/2505.09388</a></li><li><strong>DPO</strong> — Direct Preference Optimization (arXiv 2305.18290): <a href="https://arxiv.org/abs/2305.18290">arxiv.org/abs/2305.18290</a></li><li><strong>RPO</strong> — Iterative Reasoning Preference Optimization, DPO + NLL (arXiv 2404.19733): <a href="https://arxiv.org/abs/2404.19733">arxiv.org/abs/2404.19733</a></li><li><strong>LoRA</strong> — Low-Rank Adaptation of Large Language Models (arXiv 2106.09685): <a href="https://arxiv.org/abs/2106.09685">arxiv.org/abs/2106.09685</a></li><li><strong>TRL</strong> — DPOTrainer and loss_type: <a href="https://huggingface.co/docs/trl/dpo_trainer">huggingface.co/docs/trl/dpo_trainer</a></li><li><strong>llama.cpp</strong> — server, imatrix and quantization: <a href="https://github.com/ggml-org/llama.cpp">github.com/ggml-org/llama.cpp</a></li><li><strong>DRY sampler</strong> — original proposal: <a href="https://github.com/oobabooga/text-generation-webui/pull/5677">github.com/oobabooga/text-generation-webui/pull/5677</a></li><li><strong>LAYA</strong> — typed-decision classifier used for intent reading: <a href="https://github.com/NandhaKishorM/laya">github.com/NandhaKishorM/laya</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631be763a42d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System One + System Two: um RAG que se encaixa no hardware]]></title>
            <link>https://medium.com/@guaranta/system-one-system-two-um-rag-que-se-encaixa-no-hardware-6a997eee285c?source=rss-a618c5fb18b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a997eee285c</guid>
            <category><![CDATA[laya]]></category>
            <category><![CDATA[system-one-model]]></category>
            <category><![CDATA[inteligencia-artificial]]></category>
            <dc:creator><![CDATA[Guaranta Almeida]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 02:15:39 GMT</pubDate>
            <atom:updated>2026-10-06T02:15:39.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Como o LAYA se mostrou a estratégia mais eficiente — um caso real de comparativo entre estratégias de roteamento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYBiAD9uay2QtPxmtarOMg.png" /></figure><p>Modelos System One estão no centro da conversa: decisores pequenos, rápidos e calibrados, que tomam a decisão tipada antes de qualquer geração de texto. O nome vem de Kahneman: System One é o pensamento rápido; System Two, o deliberado.</p><p>A pergunta que nos interessava não era se eles funcionam numa demo, mas se aguentam produção: hardware que você não escolheu, perguntas que você não previu e componentes que falham. Para responder, construímos um copiloto de catálogo de produtos que não pode inventar preço, estoque ou especificação, e colocamos nove configurações de roteamento na mesma bancada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPw72A4oo-GQaVy5s5Ltqw.png" /><figcaption>O caso em quatro números, do problema à produção.</figcaption></figure><p>Quem entrou na disputa, do mais barato ao mais caro. LAYA e CLM rodaram sem ajuste e ajustados; o LAYA, também com o LLM de reserva. São as nove configurações.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53h-YiqbLqKEvQ-0CZ2bQg.png" /><figcaption>As seis estratégias comparadas.</figcaption></figure><h3>O problema: uma decisão antes da busca</h3><p>Para buscar certo, o copiloto precisa primeiro entender o que o cliente pediu, em duas dimensões:</p><ul><li><strong>O ato:</strong> é uma pergunta de fato, uma comparação, uma dúvida de compatibilidade, um pedido de sugestão, algo fora de escopo?</li><li><strong>O extremo:</strong> o cliente quer o mais barato, o mais silencioso, o mais estreito? Ou nenhum?</li></ul><p>Errar aqui faz a busca certa responder à pergunta errada. “Compare os dois no ruído” não é “qual o mais silencioso”, embora as palavras sejam parecidas. O ponto de partida era um léxico escrito à mão: 0,96 de acerto nas perguntas para as quais foi escrito e 0,31 em perguntas novas. <strong>Overfitting</strong> com outro nome.</p><h3>Onde a decisão fica: System One + System Two</h3><p>Cada pergunta passa por três naturezas de componente. O <strong>System One</strong> (LAYA) lê a intenção e devolve uma decisão tipada com confiança calibrada, sem gerar texto. O <strong>System Two</strong> (Qwen3) planeja a busca e redige a resposta. O <strong>código determinístico</strong> busca, confere e cacheia: o LLM não escreve SQL, a busca é híbrida (full-text + pgvector, RRF e rerank) e um GroundingGuard confere cada preço e ID antes de a frase sair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkmSFiGmxBBnFdvMspG9xQ.png" /><figcaption>Arquitetura: o System 1 decide, o System 2 pensa, o código garante.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*681wXu_zju3VJcp4ki0J3w.png" /><figcaption>O caminho de uma pergunta, mensagem a mensagem.</figcaption></figure><h3>O comparativo: uma bancada para todos</h3><p>A regra do projeto era simples: nada entra ou sai sem medição. Todas as estratégias passaram pelo mesmo script, nos três servidores, com as mesmas perguntas: 456 âncoras para treino, 472 de teste em categorias disjuntas e 24 escritas à mão. A métrica exige acertar o ato e o extremo juntos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvlZCa5R9rBXW_sh0IfuPQ.png" /><figcaption>Como medimos.</figcaption></figure><h3>O resultado: por que o LAYA venceu</h3><p>O LAYA ajustado chegou a 0,943. Nenhuma outra estratégia passou de 0,87, e a mais próxima precisava do LLM em 38% das perguntas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*MLeLVLQRuQWpKsGGjnghvA.gif" /><figcaption>A corrida: o mesmo fluxo de perguntas nas quatro estratégias, com o placar convergindo para o valor medido.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwEOe0BCIrdwg5hE-37NUQ.png" /><figcaption>Placar das nove configurações (472 perguntas de teste, servidor de 96 GB).</figcaption></figure><ul><li><strong>Zero-shot não basta.</strong> Sem ajuste, nenhum roteador especializado (LAYA, CLM, Arch-Router) passou de 0,56.</li><li><strong>Tamanho não decide.</strong> O 32B, 75 vezes maior que o LAYA, ficou em 0,73, a 536 ms por decisão contra 38 ms.</li><li><strong>O concorrente mais próximo cobra caro.</strong> O bge kNN com o 32B de reserva chegou a 0,87, mas chamava o LLM em 38% das perguntas. O LAYA fica em dúvida em 3%.</li></ul><h3>O que é o RLCD, o ajuste que mudou o veredito</h3><p>RLCD significa <em>Reinforcement Learning for Calibrated Decisions</em>: aprendizado por reforço para decisões calibradas. É a receita publicada com o próprio LAYA. Treinar só com cross-entropy ensina o modelo a acertar, mas não a saber quando está em dúvida. No RLCD, a recompensa é uma <strong>regra de pontuação estritamente própria</strong>, que só é máxima quando a probabilidade declarada é a verdadeira: ser confiante e errado custa mais do que ser cauteloso e errado.</p><p>A cada lote, o modelo sorteia quatro versões ruidosas da sua distribuição, pontua cada uma contra o gabarito (regras esférica e RPS) e reforça as que ficaram acima da média do grupo, no estilo GRPO. Depois do treino, uma temperatura por tipo de decisão é ajustada num pedaço dos dados que o treino nunca viu. É essa calibração que torna confiável o gate de 0,9. Resultado: de 0,371 sem ajuste para 0,943.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*wteaYi6IUQmXuCJTLCk1ug.gif" /><figcaption>O RLCD treinando (ilustrativo): amostras ruidosas, notas pela regra esférica, ruído caindo a cada época e a calibração no fim.</figcaption></figure><p>Dois cuidados para ler o número com honestidade. Treino e teste vieram do mesmo gerador; nas 24 perguntas escritas à mão, o LAYA fez 0,79 sozinho e 0,875 com o LLM de reserva, e esse é o piso que citamos. E uma sonda de paridade achou um bug nosso que custava 7 pontos ao CLM; corrigimos antes de comparar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r-Pmrsr-XXYSmTz1-onyg.png" /></figure><h3>A política servida: o System One tem limites</h3><p>Em produção, a leitura literal da pergunta tem prioridade, e o LAYA só preenche um extremo quando as palavras não dizem nenhum, ele está confiante e nenhum produto foi nomeado. No extremo, essa política fez 0,97 contra 0,80 da regra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJx22Ty_CCn62PgCJ98tGg.png" /><figcaption>Os três caminhos da política servida (exemplos ilustrativos).</figcaption></figure><h3>Um checkpoint, cinco dispositivos</h3><p>O mesmo checkpoint de 421M foi medido em cinco dispositivos, e a acurácia não mudou além da terceira casa. Só a latência muda, de 26 ms numa A5000 a 1,7 s numa VM de 2 vCPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEcH7QawPCUSdqdVc2WfJQ.png" /><figcaption>Latência p50 e acerto do mesmo checkpoint em cinco dispositivos.</figcaption></figure><h3>Hardware-aware placement: cada sistema onde cabe</h3><p>Ninguém edita configuração ao trocar de máquina. Uma sonda em container lê o hardware, e o planner escreve a topologia: o System 2 pela VRAM (32B a partir de 80 GB, 8B abaixo de 40 GB, 1.7B só com CPU, com standby numa segunda GPU) e o System 1 pelo que sobra. Na A5000 de 24 GB, ao lado do 8B, o LAYA estourou a memória da GPU, e o planner o pôs na CPU, a 249 ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*A_C0uYz48Lk-9WQKGvD6IQ.gif" /><figcaption>O placement acontecendo nas três máquinas.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Syl-2t2CUPbeWSr4F-2AdA.png" /><figcaption>A topologia que o planner escreveu em cada máquina.</figcaption></figure><h3>O ciclo de LLMOps do System 1</h3><p>Um System 1 treinado uma vez envelhece no primeiro catálogo novo. Por isso o ciclo inteiro virou um comando do build: o cliente sobe o catálogo dele, e a camada de decisão é refeita, aprovada e posicionada sem intervenção manual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X3TFkuRHeQVWYNnfWE48A.png" /><figcaption>Ciclo de vida do System 1, do catálogo à observação.</figcaption></figure><h3>O que é o ONNX, e por que ele entra no passo 4</h3><p>ONNX (<em>Open Neural Network Exchange</em>) é um formato aberto que representa um modelo como um grafo de operadores padronizados, com os pesos no mesmo arquivo. O ONNX Runtime executa esse grafo em CPU ou GPU, sem o PyTorch, e o quantiza sem retreinar. No nosso ciclo, o ONNX FP32 reproduz o PyTorch com o mesmo acerto, e o INT8 corta a memória de 2,9 para 1,3 GB num notebook.</p><p>O risco também é concreto: o mesmo arquivo INT8 que funciona num Apple M2 colapsa num EPYC sem instruções VNNI. Por isso o build gera duas variantes, e um canário no host repete 48 respostas de referência antes de servir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDWWb6QDbhfFa4_xNY9XyQ.png" /><figcaption>O que é um arquivo ONNX, o pipeline de export e o mesmo arquivo em duas CPUs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*7y1iXhmGf8yjzNkkhLFoDg.gif" /><figcaption>O canário no EPYC Zen 2: faixa completa recusada (0,021), faixa reduzida servida (0,896).</figcaption></figure><h3>Observabilidade: como cada número é provado</h3><p>Em LLMOps, um número sem rastro é opinião. Cada requisição deixa um rastro com o mesmo request_id, e cada medição deixa um arquivo bruto com o git SHA do código.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*-puA1RYcY4V7-2WqtpapLw.gif" /><figcaption>Operação ao vivo (ilustrativo): o primary cai, o circuito abre e o standby assume sem perder pedido.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xz71EByfU_o2myc1PrOW8A.png" /><figcaption>Os sinais e o que cada um mostra.</figcaption></figure><h3>O que sustenta o System 2: fallback e inferência</h3><p>Derrubando o modelo principal sob carga, 1.218 de 1.218 pedidos foram atendidos, com o standby assumindo em 2 s (p50). E trocar BF16 por AWQ no 32B multiplicou o throughput por 6,9 com a mesma acurácia; depois disso, só max_num_seqs e o prefix cache mudaram o resultado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ib6tfEnNnaVISfAZaUFAbw.png" /><figcaption>Fallback em camadas do System 2.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwHD7z5DJSgU9DKTzmSvWQ.png" /><figcaption>Precisão do Qwen3 32B: throughput e TTFT p95 a 32 usuários.</figcaption></figure><h3>Radar: o que avaliamos do estado da arte</h3><p>Estar atualizado não é adotar tudo o que sai; é medir rápido e decidir com evidência.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgBAhw_-nLPkBo4W4FPyuQ.png" /><figcaption>O que passou pela bancada e o veredito de cada um.</figcaption></figure><h3>Lições do caso</h3><ol><li><strong>Um System 1 ajustado vence um LLM grande na decisão estreita.</strong> 421M contra 32B: 0,94 contra 0,73.</li><li><strong>Zero-shot é a hipótese, não o veredito.</strong> O LAYA sem ajuste fez 0,37.</li><li><strong>Confiança calibrada é o contrato entre os dois sistemas.</strong> Sem calibração, um gate de 0,9 é só um número.</li><li><strong>O hardware faz parte da arquitetura.</strong> O mesmo modelo foi de 26 ms a 1,7 s, e um INT8 funcionou num processador e devolveu lixo em outro.</li><li><strong>Rastreie antes de culpar o modelo.</strong> Quando o 32B acertava 7 de 12, o trace mostrou cinco bugs de código.</li><li><strong>Número só vale com procedimento.</strong> Arquivo bruto com git SHA, decision log e um auditor independente.</li></ol><p>Trabalhamos com agentes de IA como equipe, com papéis separados. A IA acelerou a execução; as decisões e a responsabilidade pelos números continuaram humanas.</p><p><strong>Que decisão você ainda pede ao LLM e poderia passar para um System 1?</strong></p><h3>Referências</h3><ol><li><strong>System One models</strong> — o que é um modelo System 1 (systemonemodels.org): <a href="https://systemonemodels.org/guides/what-is-a-system-one-model/">systemonemodels.org/guides/what-is-a-system-one-model</a></li><li><strong>LAYA</strong> — repositório, checkpoints e receita RLCD (Convai Innovations, Apache-2.0): <a href="https://github.com/NandhaKishorM/laya">github.com/NandhaKishorM/laya</a> · <a href="https://huggingface.co/convaiinnovations/laya-typed-decisions">huggingface.co/convaiinnovations/laya-typed-decisions</a></li><li><strong>CLM-8B</strong> — Contrastive Language Model v0.1: <a href="https://huggingface.co/Contrastive-LM/CLM-v0.1-8B">huggingface.co/Contrastive-LM/CLM-v0.1–8B</a></li><li><strong>Arch-Router</strong> — Aligning LLM Routing with Human Preferences (arXiv 2506.16655): <a href="https://arxiv.org/abs/2506.16655">arxiv.org/abs/2506.16655</a> · <a href="https://huggingface.co/katanemo/Arch-Router-1.5B">huggingface.co/katanemo/Arch-Router-1.5B</a></li><li><strong>GRPO</strong> — Group Relative Policy Optimization, introduzido no DeepSeekMath (arXiv 2402.03300): <a href="https://arxiv.org/abs/2402.03300">arxiv.org/abs/2402.03300</a></li><li><strong>ModernBERT</strong> — o encoder por trás do LAYA (arXiv 2412.13663): <a href="https://arxiv.org/abs/2412.13663">arxiv.org/abs/2412.13663</a></li><li><strong>ONNX</strong> — formato aberto para modelos de ML: <a href="https://onnx.ai/">onnx.ai</a></li><li><strong>ONNX Runtime</strong> — quantização, faixa reduzida e CPUs sem VNNI: <a href="https://onnxruntime.ai/docs/performance/model-optimizations/quantization.html">onnxruntime.ai/docs/performance/model-optimizations/quantization.html</a></li><li><strong>Qwen3</strong> — Technical Report (arXiv 2505.09388): <a href="https://arxiv.org/abs/2505.09388">arxiv.org/abs/2505.09388</a></li><li><strong>AWQ</strong> — Activation-aware Weight Quantization (arXiv 2306.00978): <a href="https://arxiv.org/abs/2306.00978">arxiv.org/abs/2306.00978</a></li><li><strong>Redis vector sets</strong> — base do cache semântico: <a href="https://redis.io/docs/latest/develop/data-types/vector-sets/">redis.io/docs/latest/develop/data-types/vector-sets</a></li></ol><h3>LInk</h3><ol><li><strong>Versão em inglês</strong> — <a href="https://medium.com/@guaranta/system-one-system-two-a-rag-that-fits-the-hardware-bfaa325d516">https://medium.com/@guaranta/system-one-system-two-a-rag-that-fits-the-hardware-bfaa325d516</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a997eee285c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System One + System Two: a RAG that fits the hardware]]></title>
            <link>https://medium.com/@guaranta/system-one-system-two-a-rag-that-fits-the-hardware-bfaa325d5161?source=rss-a618c5fb18b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfaa325d5161</guid>
            <category><![CDATA[system-one-model]]></category>
            <category><![CDATA[laya]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Guaranta Almeida]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 01:59:40 GMT</pubDate>
            <atom:updated>2026-10-06T02:16:23.500Z</atom:updated>
            <content:encoded><![CDATA[<p>How LAYA proved to be the most efficient strategy — a real-world comparison of routing strategies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmiiF0U24lhinUC8aylOFQ.png" /></figure><p>System One models are at the center of the conversation: small, fast, calibrated deciders that make the typed decision before any text is generated. The name comes from Kahneman: System One is fast thinking; System Two, deliberate thinking.</p><p>The question we cared about was not whether they work in a demo, but whether they hold up in production: hardware you didn’t choose, questions you didn’t foresee and components that fail. To answer it, we built a product-catalog copilot that cannot make up a price, stock level or spec, and put nine routing configurations on the same bench.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Gbv9GCO-7oIE8cCr0yAQA.png" /><figcaption>The case in four numbers, from the problem to production.</figcaption></figure><p>Who entered the race, from cheapest to most expensive. LAYA and CLM ran zero-shot and fine-tuned; LAYA also ran with the LLM as backup. That makes nine configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jeox0aSHdQKqqhHP8DbAKQ.png" /><figcaption>The six strategies compared.</figcaption></figure><h3>The problem: a decision before the search</h3><p>To search correctly, the copilot first has to understand what the customer asked for, along two dimensions:</p><ul><li><strong>The act:</strong> is it a factual question, a comparison, a compatibility question, a request for a suggestion, something out of scope?</li><li><strong>The extreme:</strong> does the customer want the cheapest, the quietest, the slimmest? Or none?</li></ul><p>Getting this wrong makes the right search answer the wrong question. “Compare the two on noise” is not “which one is quietest”, even though the words are similar. The starting point was a handwritten lexicon: 0.96 accuracy on the questions it was written for and 0.31 on new questions. Overfitting by another name.</p><h3>Where the decision lives: System One + System Two</h3><p>Every question goes through three kinds of component. <strong>System One</strong> (LAYA) reads the intent and returns a typed decision with calibrated confidence, without generating text. <strong>System Two</strong> (Qwen3) plans the search and writes the answer. <strong>Deterministic code</strong> searches, checks and caches: the LLM doesn’t write SQL, search is hybrid (full-text + pgvector, RRF and rerank) and a GroundingGuard checks every price and ID before the sentence goes out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GG8TKxQQyGSBkLzDshd59w.png" /><figcaption>Architecture: System One decides, System Two thinks, code guarantees.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WABqT0Zn29-0TQ3I__zYxQ.png" /><figcaption>The path of a question, message by message.</figcaption></figure><h3>The benchmark: one bench for everyone</h3><p>The project rule was simple: nothing goes in or out without measurement. Every strategy went through the same script, on all three servers, with the same questions: 456 anchors for training, 472 test questions in disjoint categories and 24 written by hand. The metric requires getting the act and the extreme right together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkGof1xoqxITctsQWUoNtA.png" /><figcaption>How we measured.</figcaption></figure><h3>The result: why LAYA won</h3><p>Fine-tuned LAYA reached 0.943. No other strategy went above 0.87, and the closest one needed the LLM on 38% of the questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*xScn16HX9w8j91yzxSqVCA.gif" /><figcaption>The race: the same question stream through the four strategies, with the score converging to the measured value.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSpHCF0YcGaskElXItx6-g.png" /><figcaption>Scoreboard of the nine configurations (472 test questions, 96 GB server).</figcaption></figure><ul><li><strong>Zero-shot isn’t enough.</strong> Without fine-tuning, no specialized router (LAYA, CLM, Arch-Router) went above 0.56.</li><li><strong>Size doesn’t decide.</strong> The 32B, 75 times larger than LAYA, stayed at 0.73, at 536 ms per decision against 38 ms.</li><li><strong>The closest competitor charges a lot.</strong> bge kNN with the 32B as backup reached 0.87, but called the LLM on 38% of the questions. LAYA is unsure on 3%.</li></ul><h3>What RLCD is: the fine-tuning that changed the verdict</h3><p>RLCD stands for <em>Reinforcement Learning for Calibrated Decisions</em>. It is the recipe published with LAYA itself. Training with cross-entropy alone teaches the model to be right, but not to know when it is unsure. In RLCD, the reward is a <strong>strictly proper scoring rule</strong>, which is only maximal when the stated probability is the true one: being confident and wrong costs more than being cautious and wrong.</p><p>On each batch, the model samples four noisy versions of its distribution, scores each one against the label (spherical and RPS rules) and reinforces the ones above the group mean, GRPO style. After training, one temperature per decision type is fitted on a slice of data training never saw. That calibration is what makes the 0.9 gate trustworthy. Result: from 0.371 zero-shot to 0.943.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*yawVv5jkGH7N1GtP-SKJjQ.gif" /><figcaption>RLCD training (illustrative): noisy samples, spherical-rule scores, noise dropping each epoch and calibration at the end.</figcaption></figure><p>Two caveats for reading the number honestly. Training and test came from the same generator; on the 24 handwritten questions, LAYA scored 0.79 alone and 0.875 with the LLM as backup, and that is the floor we quote. And a parity probe found a bug of ours that cost CLM 7 points; we fixed it before comparing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpOtAbb_8OoURcZgpGOOqA.png" /></figure><h3>The served policy: System One has limits</h3><p>In production, the literal reading of the question takes priority, and LAYA only fills in an extreme when the words don’t state one, it is confident and no product was named. On the extreme, this policy scored 0.97, against 0.80 for the rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJx22Ty_CCn62PgCJ98tGg.png" /><figcaption>The three paths of the served policy (illustrative examples).</figcaption></figure><h3>One checkpoint, five devices</h3><p>The same 421M checkpoint was measured on five devices, and accuracy didn’t change beyond the third decimal place. Only latency changes, from 26 ms on an A5000 to 1.7 s on a 2-vCPU VM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRbCP9PXRdc3KUTGe-vxQA.png" /><figcaption>p50 latency and accuracy of the same checkpoint on five devices.</figcaption></figure><h3>Hardware-aware placement: each system where it fits</h3><p>Nobody edits configuration when switching machines. A probe in a container reads the hardware, and the planner writes the topology: System Two by VRAM (32B from 80 GB up, 8B below 40 GB, 1.7B on CPU only, with a standby on a second GPU) and System One by whatever is left. On the 24 GB A5000, next to the 8B, LAYA ran out of GPU memory, and the planner moved it to the CPU, at 249 ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*XGDwUtwuw0ZaaY8A-lHU_A.gif" /><figcaption>Placement in action on the three machines.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDeXaKKB8Fuak1a6bmyt_Q.png" /><figcaption>The topology the planner wrote on each machine.</figcaption></figure><h3>The System One LLMOps cycle</h3><p>A System One trained once goes stale at the first new catalog. That’s why the whole cycle became a single build command: the customer uploads their catalog, and the decision layer is rebuilt, approved and placed with no manual intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gp4_q-WP6uBJrNhOi64aTA.png" /><figcaption>System One lifecycle, from catalog to observation.</figcaption></figure><h3>What ONNX is, and why it comes in at step 4</h3><p>ONNX (<em>Open Neural Network Exchange</em>) is an open format that represents a model as a graph of standardized operators, with the weights in the same file. ONNX Runtime executes that graph on CPU or GPU, without PyTorch, and quantizes it without retraining. In our cycle, ONNX FP32 reproduces PyTorch with the same accuracy, and INT8 cuts memory from 2.9 to 1.3 GB on a laptop.</p><p>The risk is just as concrete: the same INT8 file that works on an Apple M2 collapses on an EPYC without VNNI instructions. That’s why the build generates two variants, and a canary on the host replays 48 reference answers before serving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjWUAhj0qnuVVf12OVUMEg.png" /><figcaption>What an ONNX file is, the export pipeline and the same file on two CPUs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*KB8gDRpS-_yMnZYa-4jSXw.gif" /><figcaption>The canary on the EPYC Zen 2: full range refused (0.021), reduced range served (0.896).</figcaption></figure><h3>Observability: how every number is proven</h3><p>In LLMOps, a number without a trail is an opinion. Every request leaves a trail with the same request_id, and every measurement leaves a raw file with the git SHA of the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*zaqTbIijc7PfwMzPeTThOw.gif" /><figcaption>Live operation (illustrative): the primary goes down, the circuit opens and the standby takes over without losing a request.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kc4Nqf2pMNmZQOyqmrHThw.png" /><figcaption>The signals and what each one shows.</figcaption></figure><h3>What keeps System Two standing: fallback and inference</h3><p>With the main model taken down under load, 1,218 of 1,218 requests were served, with the standby taking over in 2 s (p50). And switching from BF16 to AWQ on the 32B multiplied throughput by 6.9 with the same accuracy; after that, only max_num_seqs and the prefix cache changed the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0NpwGZCoyLuiKIMk5qjOg.png" /><figcaption>Layered System Two fallback.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TjJYV4T7gF9PR1bdybPbg.png" /><figcaption>Qwen3 32B precision: throughput and TTFT p95 at 32 users.</figcaption></figure><h3>Radar: what we evaluated from the state of the art</h3><p>Staying current isn’t adopting everything that comes out; it’s measuring fast and deciding on evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPxI5ZZWRNi7jTg-OiUABQ.png" /><figcaption>What went through the bench and the verdict on each.</figcaption></figure><h3>Lessons from the case</h3><ol><li><strong>A fine-tuned System One beats a large LLM on the narrow decision.</strong> 421M against 32B: 0.94 against 0.73.</li><li><strong>Zero-shot is the hypothesis, not the verdict.</strong> LAYA without fine-tuning scored 0.37.</li><li><strong>Calibrated confidence is the contract between the two systems.</strong> Without calibration, a 0.9 gate is just a number.</li><li><strong>Hardware is part of the architecture.</strong> The same model went from 26 ms to 1.7 s, and an INT8 file worked on one processor and returned garbage on another.</li><li><strong>Trace before blaming the model.</strong> When the 32B got 7 of 12 right, the trace showed five code bugs.</li><li><strong>A number is only worth something with a procedure.</strong> Raw file with git SHA, decision log and an independent auditor.</li></ol><p>We worked with AI agents as a team, with separate roles. AI sped up execution; the decisions and the responsibility for the numbers stayed human.</p><p><strong>Which decision are you still asking the LLM to make that could move to a System One?</strong></p><h3>References</h3><ol><li><strong>System One models</strong> — what a System One model is (systemonemodels.org): <a href="https://systemonemodels.org/guides/what-is-a-system-one-model/">systemonemodels.org/guides/what-is-a-system-one-model</a></li><li><strong>LAYA</strong> — repository, checkpoints and RLCD recipe (Convai Innovations, Apache-2.0): <a href="https://github.com/NandhaKishorM/laya">github.com/NandhaKishorM/laya</a> · <a href="https://huggingface.co/convaiinnovations/laya-typed-decisions">huggingface.co/convaiinnovations/laya-typed-decisions</a></li><li><strong>CLM-8B</strong> — Contrastive Language Model v0.1: <a href="https://huggingface.co/Contrastive-LM/CLM-v0.1-8B">huggingface.co/Contrastive-LM/CLM-v0.1–8B</a></li><li><strong>Arch-Router</strong> — Aligning LLM Routing with Human Preferences (arXiv 2506.16655): <a href="https://arxiv.org/abs/2506.16655">arxiv.org/abs/2506.16655</a> · <a href="https://huggingface.co/katanemo/Arch-Router-1.5B">huggingface.co/katanemo/Arch-Router-1.5B</a></li><li><strong>GRPO</strong> — Group Relative Policy Optimization, introduced in DeepSeekMath (arXiv 2402.03300): <a href="https://arxiv.org/abs/2402.03300">arxiv.org/abs/2402.03300</a></li><li><strong>ModernBERT</strong> — the encoder behind LAYA (arXiv 2412.13663): <a href="https://arxiv.org/abs/2412.13663">arxiv.org/abs/2412.13663</a></li><li><strong>ONNX</strong> — open format for ML models: <a href="https://onnx.ai/">onnx.ai</a></li><li><strong>ONNX Runtime</strong> — quantization, reduced range and CPUs without VNNI: <a href="https://onnxruntime.ai/docs/performance/model-optimizations/quantization.html">onnxruntime.ai/docs/performance/model-optimizations/quantization.html</a></li><li><strong>Qwen3</strong> — Technical Report (arXiv 2505.09388): <a href="https://arxiv.org/abs/2505.09388">arxiv.org/abs/2505.09388</a></li><li><strong>AWQ</strong> — Activation-aware Weight Quantization (arXiv 2306.00978): <a href="https://arxiv.org/abs/2306.00978">arxiv.org/abs/2306.00978</a></li><li><strong>Redis vector sets</strong> — the basis of the semantic cache: <a href="https://redis.io/docs/latest/develop/data-types/vector-sets/">redis.io/docs/latest/develop/data-types/vector-sets</a></li></ol><h3>Link</h3><ol><li><strong>Pt-Br Version </strong>— <a href="https://medium.com/@guaranta/system-one-system-two-um-rag-que-se-encaixa-no-hardware-6a997eee285c">https://medium.com/@guaranta/system-one-system-two-um-rag-que-se-encaixa-no-hardware-6a997eee285c</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfaa325d5161" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seu agente corporativo não precisa de mais RAG. Precisa de memória]]></title>
            <link>https://medium.com/@guaranta/seu-agente-corporativo-n%C3%A3o-precisa-de-mais-rag-precisa-de-mem%C3%B3ria-e7e0d1ef4cfd?source=rss-a618c5fb18b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7e0d1ef4cfd</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[enterprise-ai-strategy]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[enterprise-ai-solutions]]></category>
            <dc:creator><![CDATA[Guaranta Almeida]]></dc:creator>
            <pubDate>Sun, 31 May 2026 16:30:50 GMT</pubDate>
            <atom:updated>2026-06-03T22:33:01.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHvl2FmE-Lz8i1ye2ljoCg.png" /></figure><h4><strong>0,12% de parâmetros mudam como agentes de IA lembram, investigam e trabalham.</strong></h4><p>E esse número diz mais sobre IA corporativa do que parece.</p><p>Por muito tempo, a resposta para agentes que “esquecem” foi sempre a mesma: aumentar a janela de contexto, empilhar RAG, subir mais um banco vetorial.</p><p>Existe um ponto em que isso deixa de ser arquitetura e vira remendo.</p><p>RAG é essencial. Recupera normas, contratos, logs, políticas, evidência auditável.</p><p>Mas agente corporativo não precisa só recuperar trechos. Precisa <strong>manter estado</strong>: acompanhar uma investigação longa, lembrar hipóteses descartadas, preservar decisões intermediárias, cruzar sinais fracos — sem reprocessar tudo a cada passo.</p><p>Por isso o <strong><em>δ-mem</em></strong> chama atenção.</p><p>Ele adiciona memória online a um modelo congelado, com 0,12% de overhead de parâmetros — contra 76,40% de uma alternativa líder — e ainda supera essa alternativa em benchmarks de memória. Em vez de jogar o histórico de novo no prompt, comprime interações passadas numa memória associativa dinâmica que influencia a inferência.</p><p>O ponto central: <strong>memória não é “mais texto”. Memória é arquitetura.</strong></p><p>E tem uma segunda peça. O paper sobre Direct Corpus Interaction mostra que o próprio retrieval tradicional vira gargalo em tarefas agentic: quando todo o acesso ao conhecimento é comprimido num top-k, pistas fracas e evidências que só aparecem em múltiplas iterações somem do caminho.</p><p>Num NOC, num SRE, em segurança ou análise documental, isso é crítico. O agente investiga, testa hipótese, volta atrás, cruza logs e tickets. Não é pergunta-e-resposta.</p><p><strong>Por isso a arquitetura madura não é LLM + RAG. É uma jornada de camadas — e a maioria das empresas para no meio dela sem perceber.</strong></p><h3>O que o mercado chama de avançado</h3><p>Antes de falar em maturidade, vale olhar o que hoje se vende como “agente de IA avançado”. Na prática, costuma ser uma pilha de quatro camadas: um modelo de linguagem genérico consumido via API, uma memória de trabalho para manter contexto, RAG para fundamentar respostas, e ferramentas via MCP para disparar ações.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0_hVo1EIKc8kqitDWJajw.png" /><figcaption><em>A arquitetura padrão de mercado — quatro camadas sobre modelos de terceiros</em></figcaption></figure><p>Essa arquitetura funciona e entrega valor — não é à toa que é vendida como avançada. Mas, olhada de perto, ela é pouco acima de um projeto de entrada: o modelo é de terceiros, os dados saem de casa a cada chamada, não há investigação profunda quando o RAG não basta, e não existe nenhuma camada de soberania. É o teto do que o mercado oferece. E é exatamente aqui que vale perguntar: até onde uma arquitetura pode ir?</p><h3>A Escala &lt;neuro&gt;BIT-7: onde sua empresa está nessa jornada</h3><p>É para responder isso que estruturamos a Escala BIT-7, um modelo de maturidade agêntica em sete níveis acumulativos. Repare que a stack “avançada” do mercado mal chega à metade dela. Cada nível adiciona uma capacidade real — mas, e esse é o ponto que quase ninguém enxerga, a exposição de dados (e o risco de LGPD) aparece logo no início e só desaparece no topo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUXH1tZhDEKoT74kpvSY9A.png" /><figcaption><em>Escala BIT-7 de Maturidade Agêntica — OMTX / Quantum Lab</em></figcaption></figure><p>Vale ler a tabela por faixas, porque é assim que o retorno se comporta de verdade.</p><p><strong>Faixa de experimentação (Níveis 1–2): o ROI ilusório. </strong>Começa com API pura de grandes modelos e evolui para a submissão de documentos no prompt. A capacidade sobe rápido e barato — mas é aqui que mora a primeira armadilha. No Nível 2, documentos inteiros saem da empresa para uma API de terceiro: a exposição de dados vai ao pico, e a soberania, a zero. E o retorno aparente engana: apenas 33% das iniciativas corporativas de IA atingem suas metas de ROI, segundo a Salesforce — e a acurácia é parte da razão. A maioria das empresas brasileiras está parada exatamente nessa faixa, confundindo “funciona na demo” com “gera retorno”.</p><p><strong>Faixa de capacidade com exposição (Níveis 3–5): o ganho real começa, o risco também. </strong>RAG tradicional, interação direta com corpus e, por fim, tool calling com MCP. Aqui o agente deixa de só responder e começa a investigar e agir — o retorno passa a ser concreto, na forma de redução de custo por interação. A diferença econômica é grande: cada interação de IA custa entre US$ 0,25 e US$ 0,50, contra US$ 3 a US$ 6 de uma interação humana. O problema é que, nesta faixa, o modelo e a infraestrutura ainda costumam ser de terceiros — então a capacidade cresce com os dados ainda trafegando para fora. E a própria Gartner observa que a acurácia dos LLMs genéricos cai em tarefas que exigem contexto de negócio específico: a capacidade desta faixa tem teto.</p><p><strong>Faixa de maturidade soberana (Níveis 6–7): o retorno que se sustenta. </strong>Stack agêntica real (skills e subagents encadeados) e, no topo, o SLM próprio especializado rodando em infraestrutura proprietária. É só aqui que capacidade e soberania convergem: o agente é autônomo e confiável, e os dados nunca saem de casa. E é a faixa com a evidência de ROI mais robusta. A Gartner prevê que, até 2027, empresas implantarão SLMs específicos três vezes mais que LLMs de propósito geral, justamente pelo menor custo de computação, inferência mais rápida e maior acurácia de domínio. Em ambientes regulados, o ganho é mensurável: em benchmarks financeiros, modelos pequenos evitaram o model drift e atingiram 100% de consistência de saída. E o custo operacional cai de forma direta — num caso documentado, a troca de um LLM genérico por um SLM ajustado reduziu a latência em 47% e cortou os custos de inferência em mais de 50%.</p><p><strong>A leitura honesta dos números. </strong>Esses percentuais são indicadores agregados de mercado (Gartner, Salesforce, IBM) e estudos de caso. O que eles mostram com segurança é a direção: o retorno mais consistente e defensável está na faixa de maturidade soberana, não na de experimentação onde a maioria está parada.</p><h3>A viabilidade já é realidade</h3><p>Aqui é onde costumam dizer que a faixa soberana é “bonita no papel, cara na prática”. Não é mais. Nos últimos meses, a tecnologia que torna o Nível 7 viável deixou de ser cara ou experimental — três números do mercado de infraestrutura comprovam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxFFmtdeLZ5ZM5kCPTF2qA.png" /><figcaption><em>A tecnologia já virou a chave — fontes de mercado, maio de 2026</em></figcaption></figure><p><strong>E é aqui que mora a distinção que muda tudo: </strong>a tecnologia virou a chave, mas quem implementa, na maioria, ainda não. O custo de inferência caiu, os pesos abertos amadureceram, os SLMs especializados provaram seu valor — e mesmo assim o que se vende como “agente avançado” continua sendo a stack rasa de quatro camadas. O atraso deixou de ser técnico ou de custo. Virou um atraso de arquitetura — e de quem a constrói.</p><p>E há uma evidência técnica que fecha o raciocínio da camada de memória (Nível 3). O mecanismo δ-mem mostra que o ganho de memória não exige inflar o modelo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMFxMXS9769Up5Vooak7bQ.png" /><figcaption><em>Ganho do δ-mem por intensidade de memória — Lei et al., 2026 (arXiv:2605.12357)</em></figcaption></figure><p>Com um estado de memória online de apenas 8×8, o δ-mem melhora o score médio para 1,10× o do modelo congelado, chegando a 1,20× no LoCoMo e 1,31× no MemoryAgentBench — preservando as capacidades gerais. Em outras palavras: quanto mais a tarefa depende de memória, maior a vantagem — e isso se obtém com 0,12% de overhead de parâmetros, viável dentro da própria infraestrutura.</p><p><strong>É o primeiro indício de algo maior: capacidade e independência não são um trade-off. Dá para ganhar memória sem pedir nada a ninguém. E isso muda a pergunta certa a se fazer.</strong></p><h3>A soberania não é o topo. É a fundação.</h3><p>Medimos parâmetros, contexto, latência. Raramente medimos dependência — que é o que quebra primeiro. A Escala BIT-7 parecia ser uma escada de capacidade, com a soberania esperando lá no sétimo degrau. Mas a coluna de exposição de dados conta outra história: a dependência aparece logo no Nível 1 e atravessa quase toda a jornada. O que parecia ser o topo, na verdade, precisava estar na base o tempo todo.</p><p>Porque, em engenharia, você só controla o que projeta. E a soberania de uma arquitetura de IA não se instala no fim — ela começa na fundação do projeto: hardware, dados e treinamento. É a inversão da pirâmide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyG-WQbPuQBVIKvMhPrn9Q.png" /><figcaption><em>A resposta soberana: os 7 níveis assentados sobre a Fundação 0 — OMTX / Quantum Lab</em></figcaption></figure><p><strong>Hardware (o silício). </strong>Inferência e treino rodam em máquina projetada, não alugada de terceiros. O controle físico é o primeiro elo da cadeia — e o único que, se faltar, nenhum software recupera.</p><p><strong>Dados (LGPD na raiz). </strong>O dado nunca sai de casa. Conformidade deixa de ser uma etapa final de checklist e passa a ser propriedade de origem da arquitetura. É a diferença entre evitar a multa e nunca ter exposto o dado.</p><p><strong>Treinamento (controlado). </strong>Um SLM especializado no seu domínio supera o modelo genérico — algo demonstrado em múltiplos estudos independentes, de tool calling a benchmarks regulados. A fundação “dados + treino” não é ideologia: é desempenho medido. E sem pedir licença a ninguém.</p><p>Cada elo terceirizado dessa cadeia é uma decisão que outra pessoa toma por você — sobre custo, sobre disponibilidade, sobre o que pode ou não rodar. E isso deixou de ser só uma escolha técnica.</p><p><strong>A regulação já escreveu a palavra. </strong>A Portaria <strong>MGI nº 3.485/2026 </strong>institui a Política de Governança de IA da administração pública federal e lista, entre seus princípios obrigatórios, a soberania digital — ao lado de privacidade, segurança e supervisão humana, com base na LGPD. E o projeto de lei do Sistema Nacional de IA, enviado ao Congresso em dezembro de 2025, declara explicitamente o objetivo de evitar a dependência de padrões regulatórios estrangeiros. Quando o decreto exige soberania digital, ele está exigindo algo que não se compra como API.</p><p>Na OMTX / Quantum Lab, essa discussão é prática — porque somos engenheiros da cadeia inteira, do projeto físico ao token gerado. É o que torna a Fundação 0 real, e não um slide: hardware, dados e treinamento sob o mesmo controle.</p><p>A próxima geração de agentes não será definida por modelos maiores. Será definida por sistemas que sabem o que manter, o que buscar, o que esquecer, o que auditar — e o que nunca executar sozinhos.</p><p><strong>Um sistema é soberano quando ninguém, fora dele, precisa dizer sim.</strong></p><p>GPU e benchmark — é a base para modelos rodarem dentro da empresa, com memória operacional, ferramentas reais e soberania sobre dado sensível.</p><p>A próxima geração de agentes não será definida por modelos maiores. Será definida por sistemas que sabem o que manter, o que buscar, o que esquecer, o que auditar — e o que nunca executar sozinhos.</p><p>Na OMTX / Quantum Lab, essa discussão é prática. Infra de IA não é só</p><p><strong>Memória é arquitetura. E arquitetura de IA começa na fundação.</strong></p><h3>Links de referência</h3><p>1. <strong>δ-mem — Lei et al., 2026 (arXiv) — </strong><a href="https://arxiv.org/abs/2605.12357">https://arxiv.org/abs/2605.12357</a></p><p>2. <strong>Direct Corpus Interaction (arXiv) — </strong><a href="https://arxiv.org/abs/2605.05242">https://arxiv.org/abs/2605.05242</a></p><p>3. <strong>SLM Tool Calling — Jhandi et al., AWS (arXiv) — </strong><a href="https://arxiv.org/abs/2512.15943">https://arxiv.org/abs/2512.15943</a></p><p>4. <strong>SLMs especializados — estudo 300+ modelos (arXiv) — </strong><a href="https://arxiv.org/abs/2510.21970">https://arxiv.org/abs/2510.21970</a></p><p>5. <strong>Portaria MGI nº 3.485/2026 (DOU / gov.br) — </strong><a href="https://www.gov.br/gestao/pt-br/assuntos/noticias/2026/abril/mgi-institui-politica-de-governanca-de-inteligencia-artificial-no-ambito-do-ministerio">https://www.gov.br/gestao/pt-br/assuntos/noticias/2026/abril/mgi-institui-politica-de-governanca-de-inteligencia-artificial-no-ambito-do-ministerio</a></p><p>6. <strong>Model Context Protocol (Anthropic) — </strong><a href="https://www.anthropic.com/news/model-context-protocol">https://www.anthropic.com/news/model-context-protocol</a></p><p>7. <strong>OWASP Top 10 para LLM Applications — </strong><a href="https://owasp.org/www-project-top-10-for-large-language-model-applications/">https://owasp.org/www-project-top-10-for-large-language-model-applications/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7e0d1ef4cfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Transformer Models: Optimizations Inspired by the PD-General Framework and Event Horizon…]]></title>
            <link>https://medium.com/@guaranta/enhancing-transformer-models-optimizations-inspired-by-the-pd-general-framework-and-event-horizon-878d752186af?source=rss-a618c5fb18b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/878d752186af</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[optmization]]></category>
            <dc:creator><![CDATA[Guaranta Almeida]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 17:50:10 GMT</pubDate>
            <atom:updated>2025-02-24T17:50:10.445Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing Transformer Models: Optimizations Inspired by the PD-General Framework and Event Horizon Strategies</h3><p><strong>Abstract</strong></p><p>The <strong>PD-General Framework</strong> was developed to optimize peridynamics simulations by redesigning calculations and implementing advanced memory management, leveraging the massively parallel computing power of GPUs (using CUDA). This article presents a comparative analysis between the optimization principles of <strong>PD-General</strong> and the computational challenges of <strong>Transformer models</strong>, with a particular focus on self-attention calculations. We establish a <strong>mathematical comparison</strong> between both scenarios, highlighting how structural and parallelization techniques can be adapted to enhance Transformer efficiency. Additionally, we explore the implementation of an <strong>approximate softmax</strong>, discussing the trade-offs between reducing computational costs and maintaining training stability. Finally, we present a speculative perspective on potential performance improvements, suggesting that the <strong>Event Horizon</strong> approach could be a promising path toward model <strong>super-specialization</strong>, paving the way for future experimental research.</p><p><strong>Introduction</strong></p><p>Transformer models have revolutionized natural language processing (NLP) and other <strong>machine learning</strong> domains by employing <strong>self-attention mechanisms</strong> to capture contextual dependencies in parallel. However, the computations involved — particularly matrix multiplications and softmax normalization — pose significant challenges regarding <strong>performance and memory consumption</strong>, especially when processing large datasets and deep architectures.</p><p>Similarly, <strong>peridynamics simulations</strong>, which model fractures and material damage using nonlocal interactions, face comparable computational challenges, as they require evaluating interactions among millions of particles with <strong>high processing costs</strong>.</p><p>Recently, the <strong>PD-General Framework</strong>, published in the <em>Chinese Journal of Computational Mechanics</em> (January 8, 2025, DOI: 10.1016/j.enganabound.2025.106133), demonstrated that with <strong>advanced parallelization techniques and CUDA-based memory management</strong>, it is possible to accelerate <strong>peridynamics simulations up to 800×</strong> compared to sequential implementations.</p><p>This article explores the hypothesis that <strong>key optimization concepts</strong> used in the <strong>PD-General</strong> framework can be adapted to <strong>enhance Transformer efficiency</strong>, particularly through a reformulation of self-attention calculations that <strong>reorganizes loops, optimizes memory access, and explores parallel computing strategies</strong>.</p><p><strong>The PD-General Framework: Fundamentals and Optimizations</strong></p><p>In <strong>peridynamics</strong>, calculations often involve evaluating an <strong>integral that represents the resultant force</strong> at each point, considering all interactions within a defined “horizon”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/0*Sd-HL8a9QCK12Zgq.png" /><figcaption>equação do Horizonte e sua integral</figcaption></figure><p>where <strong><em>T</em></strong>(<strong><em>x</em></strong>,<strong><em>x′</em></strong>) represents the force between points <strong><em>x</em></strong> and <strong><em>x′ </em></strong>(or their bond). In a non-optimized implementation, this <strong>computational cost</strong> scales as <strong>O(N²)</strong> for <strong>N</strong> particles.</p><p><strong>Key Optimizations in PD-General</strong></p><p>The <strong>PD-General Framework</strong> proposes:</p><p>✔ <strong>Extreme Parallelization</strong> — Restructuring calculations to distribute operations across thousands of <strong>GPU cores</strong>, allowing multiple iterations to run simultaneously. Some simulations with <strong>millions of particles</strong> completed <strong>4,000 iterations in just 5 minutes</strong>.</p><p>✔ <strong>Optimized Memory Management</strong> — <strong>Reorganizing data</strong> to minimize global memory accesses on the GPU, leveraging <strong>caches, shared memory, and registers</strong> to eliminate bottlenecks and improve computational efficiency.</p><p>✔ <strong>Significant Performance Gains</strong> — Achieving <strong>up to 800× speedup</strong> compared to sequential methods and <strong>100× improvement</strong> over traditional parallel implementations (e.g., OpenMP-based).</p><p>The <strong>framework’s mathematical analysis</strong> demonstrates how algorithmic and structural optimizations can significantly reduce <strong>computational costs</strong>, primarily by <strong>loop reordering, optimized matrix operations, and reduced memory access overhead</strong>.</p><p><strong>Mathematical Parallels with Transformer Models</strong></p><p><strong>Transformer Self-Attention: Core Computations</strong></p><p>At their core, <strong>Transformers</strong> rely heavily on <strong>matrix operations</strong>, particularly in self-attention layers, where the following equation plays a central role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siaCtlEzyaOFQgNfsyeDhA.png" /></figure><p>This operation involves:</p><p>• <strong>Large matrix multiplications</strong></p><p>• <strong>Softmax normalization</strong></p><p>• <strong>Heavy memory access and data movement</strong></p><p>Since both <strong>peridynamics and self-attention calculations</strong> involve <strong>iterative loops and extensive matrix operations</strong>, <strong>parallelization and memory optimizations</strong> from <strong>PD-General</strong> could potentially enhance <strong>Transformer efficiency</strong>.</p><h4>Mathematical Comparison: Parallels Between PD-General and Self-Attention</h4><p>Although the domains are distinct — <strong>peridynamics versus language processing</strong> — both cases can be expressed in terms of <strong>matrix operations and iterative loops</strong> that benefit from parallelism. In the <strong>PD-General Framework</strong>, performance improvements are achieved through a <strong>restructuring of computations</strong>, which mathematically translates into a <strong>reduction of the computational cost from O(N²)</strong>.</p><p>For <strong>Transformers</strong>, the computational cost of <strong>self-attention</strong> is <strong>O(n²⋅d)</strong> for a sequence of length <strong>n</strong> and dimension <strong>d</strong>. By applying <strong>parallelization techniques inspired by PD-General</strong>, it is possible to <strong>restructure the QK^T multiplication and the softmax operation</strong>, better distributing computations and reducing <strong>memory access overheads</strong>. This leads to an <strong>effective reduction in execution time</strong> without changing the theoretical complexity.</p><p><strong>Event Horizon Concept vs. Self-Attention in Transformers</strong></p><p><strong>Event Horizon in Peridynamics</strong></p><p>In <strong>bond-based peridynamics</strong>, the force at a point x is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFn4FTbWcIATJsna5VGgTA.png" /></figure><p>where <strong>each particle interacts with multiple neighbors</strong>, leading to <strong>O(N²) complexity</strong>.</p><p><strong>Self-Attention in Transformers</strong></p><p>The <strong>self-attention</strong> mechanism in <strong>Transformers</strong> follows the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bib3Z8R_bQNlEB8fO0S1JQ.png" /></figure><p><strong>Potential Optimizations</strong></p><p>✔ <strong>Loop Restructuring</strong> — Redesigning self-attention computations to <strong>minimize redundant operations</strong>.</p><p>✔ <strong>Shared Memory Utilization</strong> — Storing <strong>Q, K, and V tensors</strong> in <strong>high-speed cache memory</strong> on the GPU.</p><p>✔ <strong>Mixed Precision Computing</strong> — Using <strong>low-precision calculations</strong> selectively to optimize processing speed.</p><p>By <strong>borrowing optimization principles from peridynamics</strong>, the <strong>Event Horizon</strong> approach could <strong>restructure self-attention computations</strong> to make them more <strong>efficient</strong> while maintaining accuracy.</p><h4>Simplified Simulation of Cost Reduction in PD-General</h4><pre>import numpy as np<br>import time<br><br># Number of particles<br>N = 1000<br># Simulation: random positions in 2D space<br>positions = np.random.rand(N, 2)<br><br># Bond force: simple function that depends on distance<br>def bond_force(x, y):<br>    # Avoids division by zero and simulates an inversely proportional force to distance<br>    dist = np.linalg.norm(x - y) + 1e-6<br>    return (x - y) / (dist**3)<br><br># Naive implementation: double loops<br>def compute_forces_naive(positions):<br>    N = positions.shape[0]<br>    forces = np.zeros_like(positions)<br>    for i in range(N):<br>        for j in range(N):<br>            if i != j:<br>                forces[i] += bond_force(positions[i], positions[j])<br>    return forces<br><br># Optimized implementation: using vectorized operations<br>def compute_forces_vectorized(positions):<br>    N = positions.shape[0]<br>    forces = np.zeros_like(positions)<br>    # Expand to compute differences between all particles<br>    pos_expanded = positions[:, np.newaxis, :]  # shape (N,1,2)<br>    diff = pos_expanded - positions  # shape (N,N,2)<br>    dist = np.linalg.norm(diff, axis=2, keepdims=True) + 1e-6  # shape (N,N,1)<br>    forces = np.sum(diff / (dist**3), axis=1)<br>    return forces<br><br># Testing implementations<br>start = time.time()<br>forces_naive = compute_forces_naive(positions)<br>time_naive = time.time() - start<br><br>start = time.time()<br>forces_vect = compute_forces_vectorized(positions)<br>time_vect = time.time() - start<br><br>print(f&quot;Naive time: {time_naive:.4f} s&quot;)<br>print(f&quot;Vectorized time: {time_vect:.4f} s&quot;)</pre><p>Naive time: <strong>4.4490 s</strong><br>Vetorized time: <strong>0.0652 s</strong></p><p><strong>PD Simulation — Naive vs. Optimized</strong></p><p>This example simulates <strong>execution time as a function of the number of particles</strong>. In a <strong>naive implementation</strong> (using double loops), the time complexity grows approximately as <strong>O(N²)</strong>. In contrast, in the <strong>vectorized version</strong>, we assume a <strong>100× reduction in computational cost</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*hfOEtyIRLPQcoIvlr7w1Dw.png" /></figure><p><strong>Self-Attention Simulation — Naive vs. Optimized</strong></p><p>In this example, we simulate the <strong>computational cost of the self-attention mechanism</strong> for different sequence lengths. We assume the cost is proportional to <strong>O(n²⋅d)</strong> (with <strong>d</strong> constant, e.g., 64) and that the optimization reduces overhead by <strong>40%</strong>, meaning the new cost is <strong>60% of the original value</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*OMdgo3l3QamqOEOl5156KQ.png" /></figure><p><strong>Simulation: Impact of Overhead Factor on the Computational Cost of Self-Attention</strong></p><p>Here, we simulate how the <strong>computational cost of self-attention</strong> varies with the <strong>overhead factor</strong>. We use the simulated formula:</p><p>\text{Cost} = n² \cdot d \cdot \text{overhead}</p><p>for a Transformer model with <strong>n = 1024</strong> and <strong>d = 64</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*rh6AOsavulMz0slU0y34Ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GeidrecoMHZeUMRY.png" /><figcaption>Paper Section Snippets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sp3gHz3C4HzYG-aMLW1Ixg.png" /><figcaption>Tabela de Novas Formulções BBPD</figcaption></figure><p>This new formulation:</p><p>• Introduces an <strong>interaction horizon</strong> <strong>Hδ</strong> in self-attention calculations, similar to the <strong>neighborhood concept</strong> in <strong>BBPD</strong>.</p><p>• Restricts <strong>matrix multiplications</strong> within this horizon, reducing computational cost.</p><p>• Proposes <strong>memory hierarchy optimization</strong>, inspired by <strong>interaction optimizations</strong> in peridynamics.</p><h4>Implementation Example:</h4><p><strong>Parallelized Computation of <em>QK </em>ˆ<em>T</em></strong></p><p>• <strong>Divide</strong> <strong><em>Q</em></strong> and <strong><em>K</em></strong> into smaller blocks.</p><p>• Each <strong>thread computes the dot product</strong> between a row of <strong><em>Q</em></strong> and a column of <strong>K</strong>.</p><p>• <strong>Store intermediate results in registers</strong> for fast access.</p><p><strong>Approximate Softmax:</strong></p><p>• Compute <strong>only the top-k values</strong> of <strong><em>QK </em>ˆ<em>T</em></strong>.</p><p>• Apply <strong>softmax only to these values</strong>, ignoring the others.</p><p><strong>Multiplication <em>A</em></strong>softmax<strong><em>V</em></strong> <strong>with Shared Memory:</strong></p><p>• <strong>Load <em>A</em></strong>softmax​ <strong>and </strong>V <strong>into shared memory</strong> for efficient reuse.</p><p>Currently, <strong>standard Transformer models</strong> do not have an <strong>explicit control</strong> over an “<strong>attention horizon</strong>” as seen in <strong>Peridynamics</strong> (where interactions are limited to a <strong>local neighborhood</strong> defined by a radius \delta ). However, <strong>sparse and local attention mechanisms</strong> have been proposed to <strong>reduce the computational complexity</strong> of self-attention, indirectly <strong>approximating</strong> the concept of an <strong>attention horizon</strong>. Below, I detail the <strong>similarities and differences</strong>:</p><h4>Standard (Global) Self-Attention</h4><p>In the original <strong>Transformer formulation</strong> (Vaswani et al., 2017):</p><p>• <strong>Attention is global</strong>: Each token interacts with <strong>all</strong> other tokens in the sequence.</p><p>• <strong>Computational complexity</strong>: <strong><em>O(N²)</em></strong> , which is prohibitive for <strong>long sequences</strong>.</p><ul><li><strong>No fixed horizon</strong>: There is no <strong>spatial or neighborhood constraint</strong>.</li></ul><h4>Mechanisms That Resemble an “Attention Horizon”</h4><p>Several <strong>self-attention adaptations</strong> have introduced <strong>restrictions inspired by “horizons”</strong> or <strong>local neighborhoods</strong>:</p><p><strong>a) Local Attention (Sliding Window Attention)</strong></p><p>• <strong>Description</strong>: Each token interacts <strong>only with tokens within a fixed window</strong> around it.</p><p>• <strong>Examples</strong>:</p><p>• <strong>Longformer</strong> (Beltagy et al., 2020): Uses a <strong>fixed window size</strong> (e.g., 512 tokens).</p><p>• <strong>Image Transformer</strong> (Parmar et al., 2018): Applies <strong>local attention in 2D grids for images</strong>.</p><p>• <strong>Similarity to Horizon</strong>: Defines a <strong>“neighborhood”</strong> of interaction, reducing complexity to O(n \cdot w) , where w is the window size.</p><p><strong>b) Blockwise Attention</strong></p><p>• <strong>Description</strong>: <strong>Divides the sequence into blocks</strong> and restricts attention to <strong>tokens within the same block</strong> or adjacent blocks.</p><p>• <strong>Example</strong>:</p><p>• <strong>BigBird</strong> (Zaheer et al., 2020) combines <strong>local (windowed), global (specific tokens), and random attention</strong>.</p><ul><li><strong>Similarity to Horizon</strong>: <strong>Blocks act as discrete “horizons”</strong>.</li></ul><p><strong>c) Dynamic Sparse Attention</strong></p><p>• <strong>Description</strong>: Dynamically selects a <strong>subset of tokens</strong> for interaction, based on <strong>learned criteria</strong>.</p><p>• <strong>Example</strong>:</p><p>• <strong>Routing Transformer</strong> (Roy et al., 2021).</p><ul><li><strong>Difference</strong>: The <strong>“horizon” is adaptive and learned</strong>, not fixed.</li></ul><p><strong>d) Dilated Attention</strong></p><p>• <strong>Description</strong>: Uses a <strong>window with “gaps” (dilation)</strong> to <strong>capture broader contexts with fewer computations</strong>.</p><p>• <strong>Example</strong>:</p><p>• <strong>Sparse Transformer</strong> (Child et al., 2019).</p><p>• <strong>Similarity</strong>: Defines a <strong>non-contiguous neighborhood</strong>, but still <strong>limited</strong>.</p><h4>Comparison with the Peridynamics Horizon</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inLzfjdCb3aMXF2Cruz3WA.png" /></figure><h4>Limitations and Trade-offs</h4><p><strong>Transformers with Local Attention:</strong></p><ul><li><strong>Advantage:</strong> Reduce complexity and allow longer sequences.</li><li><strong>Disadvantage:</strong> Lose global context information unless combined with other mechanisms (e.g., sparse global attention).</li></ul><h4>Peridynamics:</h4><ul><li>The “horizon” is an inherent <strong>physical restriction</strong> of the model, whereas in <strong>Transformers, it is an engineering choice for efficiency</strong>.</li></ul><h4>Practical Example: Longformer</h4><p>The <strong>Longformer</strong> uses a <strong>local attention window</strong> (e.g., 512 tokens) + some <strong>global tokens</strong> (e.g., [CLS]). This corresponds to a <strong>hybrid horizon</strong>:</p><ul><li><strong>Local interactions:</strong> Within the defined window.</li><li><strong>Global interactions:</strong> Selected tokens (such as [CLS]).</li></ul><p>Although original Transformers <strong>do not have an explicit “attention horizon”</strong> like in <strong>Peridynamics</strong>, <strong>sparse or local attention mechanisms</strong> play a similar role by limiting interactions to a <strong>defined neighborhood</strong>. These adaptations are essential for enabling the processing of <strong>long sequences</strong> (e.g., texts, genomes, videos) and can be seen as a <strong>generalization of the “horizon” concept</strong> for non-physical domains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUxYXiEA3vNDAbXWxl6gxg.png" /></figure><h4>Detailed Comparison:</h4><p><strong>1. PD-General Horizon</strong></p><p><strong>Advantages:</strong></p><p>· <strong>Computational Efficiency:</strong> Guaranteed reduction to , where . (<strong>+90%</strong>)</p><p>· <strong>Memory:</strong> Optimized storage of fixed neighborhoods. (<strong>+85%</strong>)</p><p>· <strong>Precision:</strong> Suitable for physical domains (e.g., fractures). (<strong>+95%</strong>)</p><p><strong>Disadvantages:</strong></p><p>· <strong>Flexibility:</strong> Restricted to problems with a fixed spatial structure. (<strong>-50%</strong>)</p><p>· <strong>Scalability:</strong> Limited by hardware (e.g., GPUs). (<strong>Neutral</strong>)</p><p><strong>Similarities:</strong> Defines an <strong>“interaction horizon”</strong>, similar to <strong>fixed windows in Transformers</strong>.</p><p><strong>2. Sliding Window Attention</strong></p><p><strong>Advantages:</strong></p><p>· <strong>Efficiency:</strong> Reduction to , where . (<strong>+80%</strong>)</p><p>· <strong>Scalability:</strong> Works well with long sequences. (<strong>+70%</strong>)</p><p><strong>Disadvantages:</strong></p><p>· <strong>Precision:</strong> Loss of global context. (<strong>-10%</strong>)</p><p>· <strong>Memory:</strong> Redundant storage of windows. (<strong>-20%</strong>)</p><p><strong>Similarity to PD:</strong> Uses a <strong>fixed window</strong> (equivalent to a <strong>non-physical “horizon”</strong>).</p><p><strong>3. Blockwise Attention</strong></p><p><strong>Advantages:</strong></p><p>· <strong>Efficiency:</strong> Easy parallelization in blocks. (<strong>+75%</strong>)</p><p>· <strong>Memory:</strong> Reduced overhead per block. (<strong>+60%</strong>)</p><p><strong>Disadvantages:</strong></p><p>· <strong>Precision:</strong> Artificial separation of blocks. (<strong>-15%</strong>)</p><p>· <strong>Flexibility:</strong> Fixed block size. (<strong>-30%</strong>)</p><p><strong>Similarity to PD:</strong> Division of the domain into <strong>sub-regions</strong> (similar to <strong>discrete horizons</strong>).</p><p><strong>4. Dilated Attention</strong></p><p><strong>Advantages:</strong></p><p>· <strong>Broad Context:</strong> Captures distant interactions at a low cost. (<strong>+65%</strong>)</p><p>· <strong>Efficiency:</strong> Fewer operations than global attention. (<strong>+70%</strong>)</p><p><strong>Disadvantages:</strong></p><p>· <strong>Precision:</strong> May lose local details. (<strong>-20%</strong>)</p><p>· <strong>Complexity:</strong> More difficult implementation. (<strong>-25%</strong>)</p><p><strong>Similarity to PD:</strong> No direct similarity (focus on <strong>non-contiguous patterns</strong>).</p><p><strong>5. Dynamic Sparse Attention</strong></p><p><strong>Advantages:</strong></p><p>· <strong>Precision:</strong> Maintains critical interactions via learning. (<strong>+50%</strong>)</p><p>· <strong>Flexibility:</strong> Adapts to the context. (<strong>+60%</strong>)</p><p><strong>Disadvantages:</strong></p><p>· <strong>Efficiency:</strong> Overhead from dynamic selection. (<strong>-40%</strong>)</p><p>· <strong>Memory:</strong> Storage of sparse masks. (<strong>-30%</strong>)</p><p><strong>Similarity to PD:</strong> No direct similarity (<strong>learning-based vs. physical rules</strong>).</p><p><strong>6. Hybrid Attention</strong></p><p><strong>Advantages:</strong></p><p>· <strong>Precision:</strong> Combines local + global context. (<strong>+85%</strong>)</p><p>· <strong>Scalability:</strong> Works with very long sequences. (<strong>+90%</strong>)</p><p><strong>Disadvantages:</strong></p><p>· <strong>Efficiency:</strong> Additional cost from global attention. (<strong>-20%</strong>)</p><p>· <strong>Complexity:</strong> Hybrid implementation complexity. (<strong>-25%</strong>)</p><p><strong>Similarity to PD:</strong> No direct similarity (<strong>combines multiple strategies</strong>).</p><h4>Performance Improvement Ranking (Relative to PD-General Horizon):</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZoPXI6n_hYbJHegnjHtFQ.png" /></figure><h3>Observations:</h3><p>· <strong>PD-General Horizon</strong> leads in <strong>efficiency and precision</strong> for physical domains but is <strong>less flexible</strong>.</p><p>· <strong>Hybrid Attention</strong> (e.g., Longformer) balances <strong>efficiency and precision</strong>, making it the most <strong>versatile</strong> for <strong>NLP applications</strong>.</p><p>· <strong>Dynamic Sparse Attention</strong> has the <strong>lowest efficiency</strong> due to dynamic overhead but <strong>high flexibility</strong>.</p><p>· <strong>Sliding Window Attention</strong> is the closest to the <strong>PD “horizon”</strong>, but it suffers in terms of <strong>flexibility and global context</strong>.</p><h3>Conclusion</h3><p>This article has demonstrated that the optimization concepts of the <strong>PD-General Framework</strong> can offer <strong>valuable insights </strong>for improving the efficiency of <strong>Transformers</strong>, particularly by introducing an <strong>attention horizon</strong>. We highlighted that the use of an <strong>approximate softmax</strong> presents important trade-offs: while it reduces computational costs, it may impact <strong>training stability and model precision</strong>, requiring a careful balance.</p><p>The performance ranking presented was strictly <strong>illustrative</strong>, serving to highlight potential improvements without claiming to be a <strong>definitive measure</strong>. This reflects the <strong>dynamic nature</strong> of the Transformer field, where <strong>design choices</strong> are constantly evolving and <strong>new approaches</strong> continue to be explored.</p><p>In the next article, we will conduct a <strong>detailed experimental implementation</strong> to compare different interventions. Our goal is to demonstrate, through <strong>code and benchmarks</strong>, how the <strong>Event Horizon approach</strong> could be a promising path for <strong>training and inference of highly specialized models</strong>, integrating <strong>structural optimizations</strong> and <strong>efficient parallelization</strong>.</p><p><em>This article is also available in Portuguese: </em><a href="https://medium.com/p/759bf177fd1a">https://medium.com/p/759bf177fd1a</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878d752186af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aprimoramento de Modelos Transformer: Otimizações Inspiradas no PD‑General e Estratégias de…]]></title>
            <link>https://medium.com/@guaranta/aprimoramento-de-modelos-transformer-otimiza%C3%A7%C3%B5es-inspiradas-no-pd-general-e-estrat%C3%A9gias-de-759bf177fd1a?source=rss-a618c5fb18b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/759bf177fd1a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Guaranta Almeida]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 15:18:15 GMT</pubDate>
            <atom:updated>2025-02-24T19:09:06.829Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Aprimoramento de Modelos Transformer: Otimizações Inspiradas no PD‑General e Estratégias de Superespecialização através do Horizonte de Eventos</strong></h3><p><strong>Resumo</strong></p><p>O PD‑General Framework foi desenvolvido para otimizar simulações de peridodinâmica por meio do redesenho dos cálculos e do gerenciamento avançado de memória, aproveitando o potencial da computação massivamente paralela via GPUs (usando CUDA). Este artigo propõe uma análise comparativa entre os princípios de otimização do PD‑General e os desafios computacionais dos modelos Transformer, com ênfase especial nos cálculos de self‑attention. Realizamos um confronto matemático entre os dois cenários para demonstrar como técnicas de paralelização e reorganização algorítmica podem ser adaptadas para melhorar a eficiência, para fins específicos, dos Transformers.</p><p>Além disso, exploramos a implementação de um softmax aproximado, discutindo os trade-offs entre a redução dos custos computacionais e a manutenção da estabilidade do treinamento. Por fim, apresentamos uma perspectiva especulativa, indicando que a adoção de um “Horizonte de Eventos” pode ser uma estratégia promissora para alcançar a superespecialização dos modelos, abrindo caminho para futuras investigações experimentais.</p><p><strong>Introdução</strong></p><p>Os modelos Transformer revolucionaram o campo do processamento de linguagem natural e outras áreas de machine learning ao utilizarem mecanismos de self‑attention para capturar dependências contextuais de forma paralela. Contudo, os cálculos envolvidos — em especial, as operações de multiplicação de matrizes e a normalização via softmax — impõem grandes desafios em termos de desempenho e consumo de memória, especialmente quando se lida com grandes volumes de dados e arquiteturas profundas.</p><p>De modo similar, a simulação de peridodinâmica (PD) — uma abordagem não local para modelar fraturas e danos em materiais — apresenta desafios similares, pois envolve a avaliação de interações entre milhões de partículas, com custo computacional elevado.</p><p>Recentemente, o PD‑General framework, apresentado no <em>Chinese Journal of Computational Mechanics</em> (8 de janeiro de 2025 DOI: <a href="https://doi.org/10.1016/j.enganabound.2025.106133">10.1016/j.enganabound.2025.106133</a>), demonstrou que, com técnicas avançadas de paralelização e gestão de memória baseadas em CUDA, é possível acelerar simulações complexas de peridodinâmica em até 800× em relação a implementações sequenciais. Este artigo investiga a hipótese de que os conceitos fundamentais utilizados para otimizar os cálculos no PD‑General framework possam ser adaptados para melhorar a eficiência dos Transformers.</p><p><strong>O PD‑General Framework: Fundamentos e Otimizações</strong></p><p>No contexto da peridodinâmica, os cálculos geralmente envolvem a avaliação de uma integral que representa a força resultante em cada ponto, considerando todas as interações dentro de um “horizonte”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*DPzk6-yEIK1m3w5WpTN_0A.png" /><figcaption>equação do Horizonte e sua integral</figcaption></figure><p>onde <strong><em>T</em></strong>(<strong><em>x</em></strong>,<strong><em>x′</em></strong>) representa a força entre os pontos <strong><em>x</em></strong> e <strong><em>x′</em></strong> (ou o vínculo entre eles). Em uma implementação não otimizada, esse cálculo tem custo da ordem de <strong><em>O</em></strong>(<strong><em>N</em></strong>²), para <strong><em>N</em></strong> partículas.</p><p>o PD‑General framework propõe:</p><ul><li><strong>Paralelização Extrema:</strong> A reestruturação dos cálculos para distribuir as operações em milhares de núcleos de uma GPU, permitindo a execução simultânea de múltiplas iterações. Por exemplo, simulações com milhões de partículas foram capazes de completar 4.000 iterações em apenas 5 minutos.</li><li><strong>Gestão Otimizada da Memória:</strong> A reorganização dos dados para minimizar acessos à memória global da GPU, aproveitando caches, memória compartilhada e registradores, de forma a evitar gargalos e aumentar a eficiência computacional.</li><li><strong>Resultados Expressivos:</strong> Ganhos de desempenho de até 800× comparado a métodos sequenciais e 100× em relação a implementações paralelas tradicionais (ex.: baseadas em OpenMP).</li></ul><p>O framework apresenta, inclusive, um confronto matemático que ilustra a redução do tempo de cálculo por meio de otimizações algorítmicas e estruturais. Os detalhes matemáticos completos estão contidos no artigo original, mas posso destacar os pontos-chave que se resumem à reordenação dos loops de iteração, uso intensivo de operações matriciais otimizadas e minimização dos custos de acesso à memória.</p><p><strong>Analogias com os Modelos Transformer</strong></p><p>Os Transformers, em sua essência, dependem fortemente de operações de matriz — principalmente nas subcamadas de self‑attention, onde a operação abaixo é central.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPom8dIs7VYX4fgxiIa-pg.png" /><figcaption><strong>imagem 1 — Atenção escalada por dot-product (Scaled Dot-Product Attention)</strong>,</figcaption></figure><p>Essa operação envolve:</p><ul><li>Multiplicações de matrizes grandes;</li><li>Operações de normalização (softmax);</li><li>Acesso e movimentação intensiva de dados na memória.</li></ul><h3>Comparação Matemática:</h3><h4>Paralelos entre PD‑General e Self‑Attention</h4><p>Embora os domínios sejam distintos — peridodinâmica versus processamento de linguagem — ambos os casos podem ser expressos em termos de operações matriciais e loops iterativos que se beneficiam do paralelismo. No PD‑General framework, a melhoria de desempenho é alcançada pela reestruturação dos cálculos que, matematicamente, pode ser descrita como uma redução do custo computacional do algoritmo de <strong><em>O</em>(<em>N²</em>) </strong>.</p><p>Para os Transformers, o cálculo de self‑attention tem custo <strong><em>O</em>(<em>n²⋅d</em>)</strong> para uma sequência de comprimento <strong><em>n</em></strong> e dimensão <strong><em>d</em></strong>. Ao aplicar técnicas de paralelização inspiradas no PD‑General, pode-se reestruturar a multiplicação QK^T e o softmax para distribuir melhor as operações e reduzir overheads de acesso à memória, levando a uma redução efetiva do tempo de execução sem alterar a complexidade teórica.</p><h4>PD‑Teoria Baseada em Vínculos vs. Self‑Attention dos Transformers</h4><p><strong><em>PD‑Teoria Baseada em Vínculos:</em></strong></p><p>Na abordagem bond‑based (baseada em vínculos) da peridodinâmica, a força em um ponto <strong><em>x</em></strong> é calculada como:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Es_GVna9YhShjJO-g-vkzA.png" /></figure><p>Este cálculo é intensivo, pois cada ponto interage com muitos outros, resultando em complexidade <strong><em>O</em>(<em>N²</em>)</strong>.</p><p><strong>Self‑Attention dos Transformers:</strong></p><p>No Transformer, o mecanismo de self‑attention é definido por:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWeIuvUsky2Io7vQD_aEtA.png" /></figure><h4>Potencial de Otimização</h4><p>Assim como no PD‑General framework, onde a reordenação dos cálculos e a otimização dos acessos à memória reduzem significativamente os custos, podemos propor:</p><ul><li><strong>Reestruturação de Loops:</strong> No cálculo de self‑attention, reorganizar os laços para minimizar operações redundantes.</li><li><strong>Uso de Memória Compartilhada:</strong> Armazenar blocos dos tensores <strong><em>Q</em></strong>, <strong><em>K</em></strong> e <strong><em>V</em></strong> em memória de alta velocidade (como caches ou memória compartilhada da GPU).</li><li><strong>Precisão Mista:</strong> Aplicar técnicas de mixed precision para aproveitar melhor os recursos do hardware, reduzindo o tempo de cálculo sem comprometer a acurácia.</li></ul><p>A analogia matemática mostra que, se em PD os custos de <strong><em>O</em>(<em>N²</em>)</strong> são otimizados via paralelismo intensivo, os cálculos de self‑attention — também de ordem <strong><em>O</em>(<em>n²⋅d</em>)</strong> — podem ser beneficiados por técnicas similares.</p><p><strong>Simulação Simplificada da Redução de Custo no PD‑General</strong></p><pre>import numpy as np<br>import time<br><br># Número de partículas<br>N = 1000<br># Simulação: posições aleatórias no espaço 2D<br>positions = np.random.rand(N, 2)<br># Força de vínculo: função simples que depende da distância<br>def bond_force(x, y):<br>    # Evita divisão por zero e simula uma força inversamente proporcional à distância<br>    dist = np.linalg.norm(x - y) + 1e-6<br>    return (x - y) / (dist**3)<br><br># Implementação ingênua: loops duplos<br>def compute_forces_naive(positions):<br>    N = positions.shape[0]<br>    forces = np.zeros_like(positions)<br>    for i in range(N):<br>        for j in range(N):<br>            if i != j:<br>                forces[i] += bond_force(positions[i], positions[j])<br>    return forces<br><br># Implementação otimizada: usando operações vetorizadas<br>def compute_forces_vectorized(positions):<br>    N = positions.shape[0]<br>    forces = np.zeros_like(positions)<br>    # Expandir para calcular diferenças entre todas as partículas<br>    pos_expanded = positions[:, np.newaxis, :]  # shape (N,1,2)<br>    diff = pos_expanded - positions  # shape (N,N,2)<br>    dist = np.linalg.norm(diff, axis=2, keepdims=True) + 1e-6  # shape (N,N,1)<br>    forces = np.sum(diff / (dist**3), axis=1)<br>    return forces<br><br># Testando as implementações<br>start = time.time()<br>forces_naive = compute_forces_naive(positions)<br>time_naive = time.time() - start<br><br>start = time.time()<br>forces_vect = compute_forces_vectorized(positions)<br>time_vect = time.time() - start<br><br>print(f&quot;Tempo ingênuo: {time_naive:.4f} s&quot;)<br>print(f&quot;Tempo vetorizado: {time_vect:.4f} s&quot;)</pre><p>Tempo ingênuo: <strong>4.4490 s</strong><br>Tempo vetorizado: <strong>0.0652 s</strong></p><h4>Simulação de PD — Naive vs. Otimizado</h4><p>Este exemplo simula o tempo de execução em função do número de partículas. Em uma implementação ingênua (laços duplos), o tempo cresce aproximadamente com <strong><em>O</em>(<em>N²</em>)</strong>; já na versão vetorizada, assumimos uma redução de 100× no custo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*TqaV681deIzlftbLDiI1uQ.png" /></figure><h4>Simulação de Self‑Attention — Naive vs. Otimizado</h4><p>Neste exemplo, simulamos o custo computacional do mecanismo de self‑attention para diferentes comprimentos de sequência. Consideramos que o custo é proporcional a <strong><em>O</em>(<em>n²⋅d</em>)</strong> (com <strong><em>d</em></strong> constante, por exemplo, 64) e que a otimização reduz o overhead em 40% (ou seja, o custo passa a ser 60% do valor original).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*cuOPFmCGfoPOGlD_j3tOVw.png" /></figure><h4>Simulação Impacto do Fator de Overhead no Custo Computacional do Self‑Attention</h4><p>Aqui, simulamos como o custo computacional do self‑attention varia com o fator de overhead. Utilizamos a fórmula simulada:</p><p><strong><em>Custo</em></strong> = <strong><em>n²</em></strong>⋅ <strong><em>d</em></strong> ⋅ <strong>overhead</strong></p><p>para um modelo Transformer com n = 1024 e d = 64 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*YIXboa32PBadxKtesSJ0-Q.png" /></figure><figure><img alt="Paper Section snippets" src="https://cdn-images-1.medium.com/max/1024/1*tZ8qyIcCgOtBejvsHaIHAA.png" /><figcaption>Paper Section Snippets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iR7MsCmi_YFvGk_HnOHCRw.png" /><figcaption>Tabela de Novas Formulções BBPD</figcaption></figure><p>Essa nova formulação:</p><p>· <strong>Introduz um horizonte de interação Hδ</strong> nos cálculos de self-attention, similar ao conceito de vizinhança em <strong><em>BBPD</em></strong>.</p><p>· <strong>Redefine as multiplicações matriciais</strong> para serem restringidas dentro desse horizonte, reduzindo o custo computacional.</p><p>· <strong>Propõe uma hierarquização da memória</strong>, inspirada na otimização de interações em PD.</p><h4>Exemplo de Implementação:</h4><p><strong>Cálculo de <em>QK </em>ˆ<em>T</em> com Paralelização</strong>:</p><p>· Dividir <strong><em>Q</em></strong> e <strong><em>K</em></strong> em blocos menores.</p><p>· Cada thread calcula o produto escalar entre uma linha de <strong><em>Q</em></strong> e uma coluna de <strong><em>K</em></strong>.</p><p>· Armazenar resultados intermediários em registradores.</p><p><strong>Softmax Aproximado:</strong></p><p>· Calcular apenas os top-k valores de <strong><em>QK </em>ˆ<em>T</em></strong>.</p><p>· Aplicar softmax apenas nesses valores, ignorando os demais.</p><p><strong>Multiplicação <em>A</em></strong>softmax<strong><em>V</em> com Memória Compartilhada:</strong></p><p>· Carregar <strong><em>A</em></strong>softmax​ e <strong><em>V</em></strong> em memória compartilhada.</p><p>Atualmente, os modelos <strong>transformers</strong> padrão <strong>não possuem um controle explícito de “horizonte de atenção”</strong> como na Peridinâmica (onde interações são limitadas a uma vizinhança local definida por um raio <em>δ</em>). No entanto, <strong>mecanismos de atenção esparsa</strong> ou <strong>atenção local</strong> foram propostos para reduzir a complexidade computacional do self-attention, aproximando-se indiretamente do conceito de “horizonte”. Abaixo detalho as semelhanças e diferenças:</p><h4>Self-Attention Padrão (Global)</h4><p>Na formulação original do transformer (<a href="https://arxiv.org/abs/1706.03762">Vaswani et al., 2017</a>):</p><p><strong>Atenção é global</strong>: Cada token interage com todos os outros tokens da sequência.</p><p><strong>Complexidade</strong>: <strong><em>O</em>(<em>N²</em>) </strong>, o que é proibitivo para sequências longas.</p><p><strong>Sem horizonte fixo</strong>: Não há restrição espacial ou de vizinhança.</p><h4>Mecanismos que se Assemelham a um “Horizonte de Atenção”</h4><p>Várias adaptações do self-attention introduziram restrições inspiradas em “horizontes” ou vizinhanças locais:</p><p><strong>a) Atenção Local (Sliding Window Attention)</strong></p><p><strong>Descrição</strong>: Cada token só interage com tokens dentro de uma <strong>janela fixa</strong> ao seu redor.</p><p><strong>Exemplos</strong>:</p><p>o <strong>Longformer</strong> (<a href="https://arxiv.org/abs/2004.05150">Beltagy et al., 2020</a>): Usa uma janela de tamanho fixo (ex: 512 tokens).</p><p>o <strong>Image Transformer</strong> (<a href="https://arxiv.org/abs/1802.05751">Parmar et al., 2018</a>): Atenção local em grades 2D para imagens.</p><p><strong>Semelhança com Horizonte</strong>: Define uma “vizinhança” de interação, reduzindo a complexidade para <strong><em>O</em></strong>(<strong><em>n⋅w</em></strong>), onde w<em>w</em> é o tamanho da janela.</p><p><strong>b) Atenção por Blocos (Blockwise Attention)</strong></p><p><strong>Descrição</strong>: Divide a sequência em blocos e restringe a atenção a tokens dentro do mesmo bloco ou blocos adjacentes.</p><p><strong>Exemplo</strong>: <strong>BigBird</strong> (<a href="https://arxiv.org/abs/2007.14062">Zaheer et al., 2020</a>) combina atenção local (janela), global (tokens específicos) e aleatória.</p><p><strong>Semelhança com Horizonte</strong>: Blocos funcionam como “horizontes discretos”.</p><p><strong>c) Atenção Dinâmica Esparsa</strong></p><p><strong>Descrição</strong>: Seleciona dinamicamente um subconjunto de tokens para interagir, baseado em critérios aprendidos.</p><p><strong>Exemplo</strong>: <strong>Routing Transformer</strong> (<a href="https://arxiv.org/abs/2003.05997">Roy et al., 2021</a>).</p><p><strong>Diferença</strong>: O “horizonte” é adaptativo e aprendido, não fixo.</p><p><strong>d) Atenção com Dilatação (Dilated Attention)</strong></p><p><strong>Descrição</strong>: Usa uma janela com “saltos” (dilatação) para capturar contextos mais amplos com menos cálculos.</p><p><strong>Exemplo</strong>: <strong>Sparse Transformer</strong> (<a href="https://arxiv.org/abs/1904.10509">Child et al., 2019</a>).</p><p><strong>Semelhança</strong>: Define uma vizinhança não contígua, mas ainda limitada.</p><h4>Comparação com o Horizonte da Peridinâmica</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*ZdZTkHw6JXFp9owiU6Y8AA.png" /></figure><h4>Limitações e Trade-offs</h4><p><strong>Transformers com Atenção Local</strong>:</p><p>o <strong>Vantagem</strong>: Reduzem a complexidade e permitem sequências mais longas.</p><p>o <strong>Desvantagem</strong>: Perdem informações de contexto global, a menos que combinadas com outros mecanismos (ex: atenção global esparsa).</p><p><strong>Peridinâmica</strong>:</p><p>O “horizonte” é uma restrição física inerente ao modelo, enquanto em transformers é uma escolha de engenharia para eficiência.</p><h4>Exemplo Prático: Longformer</h4><p>O <strong>Longformer</strong> usa uma janela de atenção local (ex: 512 tokens) + alguns tokens globais (ex: [CLS]). Isso equivale a um “horizonte híbrido”:</p><p><strong>Interações locais</strong>: Dentro da janela.</p><p><strong>Interações globais</strong>: Tokens selecionados (como o [CLS]).</p><p>Embora os transformers originais não tenham um “horizonte de atenção” explícito como na Peridinâmica, <strong>mecanismos de atenção esparsa ou local</strong> desempenham um papel semelhante ao limitar interações a uma vizinhança definida. Essas adaptações são essenciais para viabilizar o processamento de sequências longas (ex: textos, genomas, vídeos) e podem ser vistas como uma generalização do conceito de “horizonte” para domínios não físicos.</p><p>Abaixo está uma comparação entre os mecanismos de <strong>atenção local em transformers</strong> e o <strong>“Horizonte de Atenção” do PD-General Framework</strong>, incluindo vantagens, desvantagens, semelhanças e um ranking hipotético de melhora de performance (baseado em ganhos típicos observados na literatura). Os percentuais são ilustrativos e refletem trade-offs entre <strong>eficiência computacional</strong>, <strong>precisão</strong> e <strong>escalabilidade</strong>.</p><h3>Critérios de Comparação:</h3><ol><li><strong>Eficiência Computacional</strong>: Redução do tempo de execução.</li><li><strong>Uso de Memória</strong>: Redução do consumo de memória.</li><li><strong>Precisão</strong>: Manutenção da qualidade do modelo.</li><li><strong>Escalabilidade</strong>: Capacidade de lidar com sequências longas.</li><li><strong>Flexibilidade</strong>: Adaptação a diferentes contextos.</li></ol><h3>Mecanismos Comparados:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSq7RV6fWr5L6lkd61qLtQ.png" /></figure><p><strong>Comparação Detalhada:</strong></p><p><strong>1. PD-General Horizon</strong></p><ul><li><strong>Vantagens</strong>:</li><li><strong>Eficiência Computacional</strong>: Redução garantida para <strong><em>O(n⋅k)</em></strong>, onde <strong><em>k≪nk≪n</em></strong>. <strong>(+90%)</strong></li><li><strong>Memória</strong>: Armazenamento otimizado de vizinhanças fixas. <strong><em>(+85%)</em></strong></li><li><strong>Precisão</strong>: Adequado para domínios físicos (ex: fraturas). <strong><em>(+95%)</em></strong></li><li><strong>Desvantagens</strong>:</li><li><strong>Flexibilidade</strong>: Restrito a problemas com estrutura espacial fixa. <strong><em>(-50%)</em></strong></li><li><strong>Escalabilidade</strong>: Limitado por hardware (ex: GPUs). <strong>(Neutro)</strong></li><li><strong>Semelhanças</strong>: Define um “horizonte” de interação, similar a janelas fixas em transformers.</li></ul><p><strong>2. Sliding Window Attention</strong></p><ul><li><strong>Vantagens</strong>:</li><li><strong>Eficiência</strong>: Redução para<strong><em> O(n⋅w), w≪nw≪n</em></strong>. <strong>(+80%)</strong></li><li><strong>Escalabilidade</strong>: Funciona bem com sequências longas. <strong>(+70%)</strong></li><li><strong>Desvantagens</strong>:</li><li><strong>Precisão</strong>: Perda de contexto global. <strong>(-10%)</strong></li><li><strong>Memória</strong>: Armazenamento redundante de janelas. <strong>(-20%)</strong></li><li><strong>Semelhança com PD</strong>: Uso de uma janela fixa (equivalente a um “horizonte” não físico).</li></ul><p><strong>3. Blockwise Attention</strong></p><ul><li><strong>Vantagens</strong>:</li><li><strong>Eficiência</strong>: Paralelização fácil em blocos. <strong>(+75%)</strong></li><li><strong>Memória</strong>: Redução de sobrecarga por bloco. <strong>(+60%)</strong></li><li><strong>Desvantagens</strong>:</li><li><strong>Precisão</strong>: Separação artificial de blocos. <strong>(-15%)</strong></li><li><strong>Flexibilidade</strong>: Tamanho de bloco fixo. <strong>(-30%)</strong></li><li><strong>Semelhança com PD</strong>: Divisão do domínio em sub-regiões (como “horizontes discretos”).</li></ul><p><strong>4. Dilated Attention</strong></p><ul><li><strong>Vantagens</strong>:</li><li><strong>Contexto Amplo</strong>: Captura interações distantes com baixo custo. <strong>(+65%)</strong></li><li><strong>Eficiência</strong>: Menos operações que atenção global. <strong>(+70%)</strong></li><li><strong>Desvantagens</strong>:</li><li><strong>Precisão</strong>: Pode perder detalhes locais. <strong>(-20%)</strong></li><li><strong>Complexidade</strong>: Implementação mais difícil. <strong>(-25%)</strong></li><li><strong>Semelhança com PD</strong>: Nenhuma direta (foco em padrões não contíguos).</li></ul><p><strong>5. Dynamic Sparse Attention</strong></p><ul><li><strong>Vantagens</strong>:</li><li><strong>Precisão</strong>: Mantém interações críticas via aprendizado. <strong>(+50%)</strong></li><li><strong>Flexibilidade</strong>: Adapta-se ao contexto. <strong>(+60%)</strong></li><li><strong>Desvantagens</strong>:</li><li><strong>Eficiência</strong>: Overhead de seleção dinâmica. <strong>(-40%)</strong></li><li><strong>Memória</strong>: Armazenamento de máscaras esparsas. <strong>(-30%)</strong></li><li><strong>Semelhança com PD</strong>: Nenhuma direta (aprendizado vs. regras físicas).</li></ul><p><strong>6. Hybrid Attention</strong></p><ul><li><strong>Vantagens</strong>:</li><li><strong>Precisão</strong>: Combina contexto local + global. <strong>(+85%)</strong></li><li><strong>Escalabilidade</strong>: Funciona com sequências muito longas. <strong>(+90%)</strong></li><li><strong>Desvantagens</strong>:</li><li><strong>Eficiência</strong>: Custo adicional de atenção global. <strong>(-20%)</strong></li><li><strong>Complexidade</strong>: Implementação híbrida. <strong>(-25%)</strong></li><li><strong>Semelhança com PD</strong>: Nenhuma direta (combina múltiplas estratégias).</li></ul><p><strong>Ranking de Melhora de Performance (Relativo ao PD-General Horizon):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*D962jFVyJHA5DPguRGlABQ.png" /></figure><h4>Observações:</h4><p><strong>PD-General Horizon</strong> lidera em <strong>eficiência e precisão</strong> para domínios físicos, mas é <strong>pouco flexível</strong>.</p><p><strong>Hybrid Attention</strong> (ex: Longformer) equilibra eficiência e precisão, sendo o mais versátil para NLP.</p><p><strong>Dynamic Sparse Attention</strong> tem a <strong>menor eficiência</strong> devido ao overhead dinâmico, mas alta flexibilidade.</p><p><strong>Sliding Window</strong> é o mais próximo do “horizonte” do PD, mas sofre em <strong>flexibilidade e contexto global</strong>.</p><h3><strong>Conclusão</strong></h3><p>Este artigo demonstrou que os conceitos de otimização do PD‑General Framework podem oferecer insights valiosos para aprimorar a eficiência dos Transformers, especialmente ao considerar a implementação de um horizonte de atenção. Ressaltamos que o uso de um softmax aproximado traz trade-offs importantes: embora reduza os custos computacionais, pode impactar a estabilidade do treinamento e a precisão do modelo, sendo necessário um equilíbrio cuidadoso.</p><p>O ranking de performance apresentado foi estritamente ilustrativo, servindo para evidenciar potenciais melhorias sem pretender ser uma medida definitiva. Isso reflete a realidade dinâmica do campo dos Transformers, onde as escolhas de design estão em constante evolução e novas abordagens continuam a ser exploradas.</p><p>No próximo artigo, realizaremos uma implementação experimental detalhada para comparar diferentes intervenções. Nosso objetivo é demonstrar, por meio de códigos e benchmarks, como a abordagem do Horizonte de Eventos pode se revelar um caminho promissor para o treinamento e a inferência de modelos superespecializados, integrando otimizações estruturais e paralelização eficiente.</p><p><em>Este artigo também está disponível em inglês</em>: <a href="https://medium.com/p/878d752186af">https://medium.com/p/878d752186af</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=759bf177fd1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>