O mapa antes do territórioThe map before the territory
"IA" virou uma palavra guarda-chuva. Para não se perder, vale saber quem está dentro de quem.
"AI" has become an umbrella word. To avoid getting lost, it helps to know what sits inside what.
- Inteligência artificialArtificial intelligence
- O campo inteiro: qualquer técnica que faz uma máquina executar tarefas que parecem exigir inteligência. Um programa de xadrez baseado em regras já conta.The whole field: any technique that makes a machine perform tasks that seem to require intelligence. A rule-based chess program already counts.
- Aprendizado de máquina (ML)Machine learning (ML)
- Em vez de escrever as regras à mão, você mostra exemplos e o sistema encontra o padrão sozinho.Instead of writing the rules by hand, you show examples and the system finds the pattern by itself.
- Aprendizado profundo (DL)Deep learning (DL)
- ML feito com redes neurais de muitas camadas. É a família por trás de reconhecimento de imagem, voz e dos modelos de linguagem.ML done with many-layer neural networks. The family behind image recognition, speech and language models.
- IA generativaGenerative AI
- Modelos profundos que produzem conteúdo novo: texto (LLMs), imagens, áudio, vídeo, código.Deep models that produce new content: text (LLMs), images, audio, video, code.
Quatro jeitos de aprenderFour ways to learn
SupervisionadoSupervised
Exemplos com a resposta certa. Foto de radiografia + "pneumonia: sim/não". É o caso mais comum no dia a dia.Examples with the right answer. A chest X-ray + "pneumonia: yes/no". The most common everyday case.
Não supervisionadoUnsupervised
Só os dados, sem resposta. O modelo acha grupos e estruturas. Exemplo: agrupar pacientes parecidos.Only data, no answers. The model finds groups and structure. Example: clustering similar patients.
Auto-supervisionadoSelf-supervised
Os próprios dados fornecem a resposta. O LLM esconde a próxima palavra e tenta adivinhá-la, trilhões de vezes.The data supplies its own answer. An LLM hides the next word and tries to guess it, trillions of times.
Por reforçoReinforcement
Tentativa, erro e recompensa. Um agente joga, ganha ou perde pontos e ajusta a estratégia. Também refina assistentes de texto.Trial, error and reward. An agent plays, gains or loses points and adjusts its strategy. Also used to refine text assistants.
Por onde começarWhere to start
Uma linha do tempo curtaA short timeline
O campo continua acelerando; a linha termina onde o consenso histórico já está firme.The field keeps accelerating; the line stops where the historical consensus is already firm.
Conceitos, um de cada vezConcepts, one at a time
Cada bloco tem uma ideia, um simulador e, se você quiser, a matemática por trás. Pule o que já conhece.
Each block has one idea, one simulator and, if you want it, the math behind it. Skip what you already know.
O neurônio artificialThe artificial neuron
Um neurônio artificial faz uma conta só: multiplica cada entrada por um peso, soma tudo, acrescenta um viés e passa o resultado por uma função de ativação. Os pesos dizem o que importa; o viés desloca o ponto de decisão; a ativação decide a força da resposta. Mexa nos controles e veja a saída mudar.
An artificial neuron does one calculation: it multiplies each input by a weight, adds everything up, adds a bias, and passes the result through an activation function. Weights say what matters; the bias shifts the decision point; the activation sets how strongly it responds. Move the controls and watch the output change.
A matemáticaThe math
Um neurônio com degrau separa o plano por uma reta. Por isso AND e OR cabem em um neurônio, mas XOR não: é preciso uma camada oculta. Você vai ver isso no Laboratório.
A step neuron splits the plane with a straight line. That's why AND and OR fit in one neuron but XOR doesn't: it needs a hidden layer. You'll see it in the Lab.
Da conta simples à redeFrom one calculation to a network
Empilhe neurônios em camadas: a saída de uma camada vira a entrada da próxima. Camadas do meio (ocultas) aprendem a recombinar a entrada em características cada vez mais abstratas: bordas, depois formas, depois objetos; ou sílabas, depois palavras, depois ideias.
Stack neurons into layers: one layer's output becomes the next layer's input. The middle (hidden) layers learn to recombine the input into increasingly abstract features: edges, then shapes, then objects; or syllables, then words, then ideas.
Os parâmetros do modelo são todos os pesos e vieses. Um modelo "de 8 bilhões de parâmetros" tem 8 bilhões desses números, todos ajustados pelo treino.
The model's parameters are all its weights and biases. An "8-billion-parameter" model has 8 billion of those numbers, all adjusted by training.
Aprender é diminuir um erroLearning is shrinking an error
Para ensinar, você precisa de um número que diga o quanto o modelo errou: a função de perda (loss). Treinar é mexer nos pesos para que esse número caia. O jeito de saber para que lado mexer é o gradiente, a inclinação da perda em cada peso. A taxa de aprendizado é o tamanho do passo.
To teach, you need one number saying how wrong the model is: the loss function. Training means nudging the weights so that number falls. The way to know which direction to nudge is the gradient, the slope of the loss with respect to each weight. The learning rate is the step size.
Abaixo, um único peso w e sua perda. A bolinha desce a ladeira, passo a passo. Teste três coisas: passo pequeno (lento), passo grande demais (oscila ou explode) e largar em pontos diferentes (o vale mais fundo nem sempre é o que você encontra).
Below, one weight w and its loss. The ball rolls down the slope, step by step. Try three things: a tiny step (slow), a step too big (oscillates or blows up) and different starting points (the deepest valley isn't always the one you find).
A matemáticaThe math
O ciclo de treino, em seis passosThe training loop in six steps
Todo treino de rede neural, de 1.000 ou de 1 trilhão de parâmetros, repete o mesmo laço. Clique em cada etapa para ver o que acontece e qual linha de código a executa (PyTorch).
Every neural-network training, from 1,000 or 1 trillion parameters, repeats the same loop. Click each stage to see what happens and which line of code runs it (PyTorch).
Decorar não é aprenderMemorizing is not learning
O objetivo não é acertar os exemplos que o modelo já viu, e sim os que nunca viu. Por isso os dados se dividem em treino (onde se aprende), validação (para ajustar escolhas) e teste (a prova final, usada uma vez). Quando o erro de treino cai e o de validação sobe, o modelo está decorando: overfitting. O contrário, errar nos dois, é underfitting.
The goal isn't to get right the examples the model has seen, but the ones it hasn't. So data is split into training (where it learns), validation (to tune choices) and test (the final exam, used once). When training error falls and validation error rises, the model is memorizing: overfitting. The opposite, being wrong on both, is underfitting.
Como um modelo de texto escolhe a próxima palavraHow a text model picks the next word
Tokens. O texto é cortado em pedaços (palavras ou fragmentos) chamados tokens, e cada token vira um número. Embeddings. Cada número é trocado por um vetor de centenas de dimensões em que significados parecidos ficam perto. Atenção. Em cada camada, cada token olha para os outros e decide quais importam para ele.
Tokens. Text is cut into pieces (words or fragments) called tokens, and each token becomes a number. Embeddings. Each number is swapped for a vector of hundreds of dimensions where similar meanings sit close together. Attention. In every layer, each token looks at the others and decides which ones matter to it.
No fim da pilha de camadas, o modelo entrega uma pontuação (logit) para cada token do vocabulário. Essas pontuações viram probabilidades e um token é sorteado. Os botões de temperatura, top-k e top-p controlam esse sorteio.
At the end of the layer stack, the model outputs a score (logit) for every token in the vocabulary. Those scores become probabilities and one token is drawn. The temperature, top-k and top-p knobs control that draw.
Temperatura baixa: sempre a palavra mais provável (previsível). Alta: mais variedade e mais risco de dizer bobagem.
Low temperature: always the most likely word (predictable). High: more variety and more risk of nonsense.
A matemáticaThe math
Laboratório de treino ao vivoLive training lab
Uma rede neural de verdade, treinando agora no seu navegador. O fundo colorido mostra o que ela acha de cada ponto do plano; as bolinhas são os exemplos. Azul e laranja são as duas classes.
A real neural network, training right now in your browser. The colored background shows what it thinks about every point on the plane; the dots are the examples. Blue and orange are the two classes.
Cinco experimentos para fazerFive experiments to try
O que este simulador calcula de verdadeWhat this simulator really computes
Uma rede totalmente conectada com saída sigmoide, perda de entropia cruzada binária, retropropagação escrita à mão em JavaScript e os otimizadores SGD e Adam. São 200 pontos, 70% para treino e 30% para teste. É o mesmo algoritmo que treina modelos gigantes, só que em miniatura.
A fully connected network with sigmoid output, binary cross-entropy loss, hand-written backpropagation in JavaScript and the SGD and Adam optimizers. 200 points, 70% for training and 30% for test. It's the same algorithm that trains giant models, just in miniature.
Os principais modelosThe main models
Cada família resolve um tipo de problema. O selo mostra até onde dá para ir em casa: treina do zero versões pequenas cabem em um PC comum; ajuste fino você adapta um modelo pronto; só uso o treino original é inviável, mas rodar é possível.
Each family solves one kind of problem. The badge shows how far you can go at home: train from scratch small versions fit on an ordinary PC; fine-tune you adapt a ready-made model; run only the original training is out of reach, but running it is possible.
Atalho: seus dados, seu ponto de partidaShortcut: your data, your starting point
| Seus dados / tarefaYour data / task | Comece porStart with | Por quêWhy |
|---|---|---|
| Planilha, prontuário estruturadoSpreadsheet, structured records | XGBoost / LightGBM | Ainda vence redes profundas na maioria das tabelas, treina em segundos na CPU.Still beats deep nets on most tables, trains in seconds on CPU. |
| Poucas centenas ou milhares de imagensA few hundred or thousand images | CNN ou ViT pré-treinado (transfer learning)Pretrained CNN or ViT (transfer learning) | O modelo já sabe ver bordas e formas; você ensina só a última camada.The model already sees edges and shapes; you only teach the last layer. |
| Segmentar exames 2D/3D (TC, RM)Segment 2D/3D scans (CT, MRI) | U-Net / nnU-Net | Configura-se sozinho para o seu conjunto e é referência em segmentação médica.Configures itself for your dataset and is a reference in medical segmentation. |
| Classificar textoClassify text | Encoder (BERT) com ajuste fino, ou um LLM com promptEncoder (BERT) fine-tuned, or an LLM with a prompt | Encoders são pequenos, rápidos e baratos para rodar em volume.Encoders are small, fast and cheap to run at volume. |
| Conversar, resumir, escrever, programarChat, summarize, write, code | LLM pronto (API ou pesos abertos locais) + RAGReady-made LLM (API or local open weights) + RAG | Treinar um LLM útil do zero custa milhões; adaptar um existente custa horas.Training a useful LLM from scratch costs millions; adapting an existing one costs hours. |
| Gerar imagens com um estiloGenerate images in a style | Difusão + LoRADiffusion + LoRA | 20 a 50 imagens bastam para um estilo ou personagem.20 to 50 images are enough for a style or character. |
| Áudio para textoAudio to text | Whisper | Roda offline, em português, inclusive em notebook.Runs offline, in many languages, even on a laptop. |
| Decisões em sequência (jogos, controle)Sequential decisions (games, control) | Aprendizado por reforço (PPO)Reinforcement learning (PPO) | Só funciona se você puder simular o ambiente milhares de vezes.Only works if you can simulate the environment thousands of times. |
Os nomes de modelos e produtos mudam rápido; as famílias e as ideias, bem menos. Confira sempre a versão e a licença atuais antes de usar.Model and product names change fast; the families and ideas change far less. Always check the current version and license before using one.
Construa o seuBuild yours
Treinar um modelo não exige um data center. Exige saber qual degrau da escada você precisa: usar um modelo pronto, ajustá-lo ou treinar do zero. Escolha o seu objetivo.
Training a model doesn't take a data center. It takes knowing which rung of the ladder you need: use a ready-made model, adapt it, or train from scratch. Pick your goal.
O passo a passo universalThe universal step by step
Defina a pergunta e o número que mede sucessoDefine the question and the number that measures success
O que você quer prever, a partir de quê, e como saberá que está bom? Escolha a métrica antes de treinar: acurácia, AUC, erro médio, coeficiente de Dice, perplexidade. Sem métrica, não há como saber se melhorou.
What do you want to predict, from what, and how will you know it's good? Choose the metric before training: accuracy, AUC, mean error, Dice coefficient, perplexity. Without a metric there's no way to tell whether it improved.
Reúna e prepare os dadosGather and prepare the data
Dados limpos valem mais que um modelo maior. Separe treino, validação e teste antes de olhar qualquer resultado, e divida por indivíduo (paciente, usuário) ou por período, nunca embaralhando linhas do mesmo indivíduo. Confira desequilíbrio entre classes, valores ausentes e rótulos errados.
Clean data beats a bigger model. Split training, validation and test before looking at any result, and split by individual (patient, user) or by period, never by shuffling rows of the same individual. Check for class imbalance, missing values and wrong labels.
Escolha o ponto de partida: suba a escada só se precisarChoose the starting point: climb the ladder only when needed
(a) modelo clássico, como boosting; (b) modelo pré-treinado usado como está; (c) ajuste fino de um modelo pré-treinado (transfer learning, LoRA); (d) treino do zero. Cada degrau custa mais dados, tempo e memória. Quase todo projeto pessoal resolve-se em (a) a (c).
(a) a classical model such as boosting; (b) a pretrained model used as is; (c) fine-tuning a pretrained model (transfer learning, LoRA); (d) training from scratch. Each rung costs more data, time and memory. Almost every personal project is solved at (a) to (c).
Monte o ambienteSet up the environment
Python em um ambiente virtual, driver da placa e PyTorch. O último comando confirma que o Python enxerga a GPU. A tabela mais abaixo diz o que instalar em cada tipo de máquina.
Python in a virtual environment, the GPU driver and PyTorch. The last command confirms that Python can see the GPU. The table further down says what to install on each kind of machine.
TreineTrain
É o laço que você viu na aba Conceitos, agora de verdade. Este exemplo ensina uma rede a reconhecer dígitos manuscritos (MNIST: 70 mil imagens). Roda em minutos, até na CPU.
It's the loop you saw in the Concepts tab, for real now. This example teaches a network to recognize handwritten digits (MNIST: 70,000 images). It runs in minutes, even on CPU.
Quer treinar um modelo de linguagem em miniatura?Want to train a miniature language model?
Um mini-GPT que aprende a escrever caractere por caractere a partir de um arquivo de texto seu (um livro, suas anotações). Tem a mesma arquitetura dos LLMs, só que com cerca de 2 milhões de parâmetros. Sai texto estranho, mas você vê a perda cair e o modelo aprender a ortografia e o estilo. Cabe em uma placa de 4 GB.
A mini-GPT that learns to write character by character from a text file of yours (a book, your notes). Same architecture as LLMs, just with about 2 million parameters. The text comes out odd, but you watch the loss fall and the model pick up spelling and style. It fits on a 4 GB card.
Avalie e diagnostiqueEvaluate and diagnose
Compare as curvas de treino e validação. Treino bom e validação ruim (overfitting): mais dados, aumento de dados, dropout, weight decay, modelo menor, parar mais cedo. Ambos ruins (underfitting): modelo maior, treinar mais, melhores características, taxa de aprendizado diferente. Use o conjunto de teste uma única vez, no fim.
Good training, bad validation (overfitting): more data, data augmentation, dropout, weight decay, a smaller model, early stopping. Both bad (underfitting): a bigger model, train longer, better features, a different learning rate. Use the test set only once, at the end.
Use, guarde e monitoreUse, save and monitor
Salve os pesos (
torch.save(model.state_dict(), "modelo.pt")), registre a versão dos dados e do código, e acompanhe o desempenho depois: dados do mundo real mudam e o modelo envelhece. Para rodar um LLM pronto localmente, o caminho mais curto é o Ollama.Save the weights (
torch.save(model.state_dict(), "model.pt")), record the data and code versions, and keep tracking performance afterwards: real-world data drifts and the model ages. To run a ready-made LLM locally, the shortest path is Ollama.Rodar um LLM pronto no seu computadorRun a ready-made LLM on your computer
O que instalar, por tipo de máquinaWhat to install, by kind of machine
| Você temYou have | InstaleInstall | ObservaçãoNote |
|---|---|---|
| PC com Windows e placa NVIDIAWindows PC with an NVIDIA card | Driver NVIDIA atual + WSL2 com Ubuntu + PyTorch com CUDACurrent NVIDIA driver + WSL2 with Ubuntu + PyTorch with CUDA | Python direto no Windows funciona, mas ferramentas de quantização e ajuste fino rodam melhor em Linux, e o WSL2 dá isso sem trocar de sistema.Python directly on Windows works, but quantization and fine-tuning tools run better on Linux, and WSL2 gives you that without switching systems. |
| Linux com placa NVIDIALinux with an NVIDIA card | Driver proprietário + ambiente virtual + PyTorch com CUDAProprietary driver + virtual environment + PyTorch with CUDA | É o caminho com mais suporte de ferramentas.The path with the most tooling support. |
| Mac com chip Apple (M1 ou superior)Mac with an Apple chip (M1 or later) | PyTorch (backend MPS) ou MLX, LM Studio, OllamaPyTorch (MPS backend) or MLX, LM Studio, Ollama | A memória é unificada, então modelos grandes cabem; o treino é mais lento que em NVIDIA. Ótimo para rodar modelos e fazer ajustes pequenos.Memory is unified, so large models fit; training is slower than on NVIDIA. Great for running models and small fine-tunes. |
| Placa AMDAMD card | PyTorch com ROCm (Linux)PyTorch with ROCm (Linux) | Funciona, com menos ferramentas prontas que CUDA. Confira a compatibilidade do seu modelo de placa antes.Works, with fewer ready-made tools than CUDA. Check your card model's compatibility first. |
| Só CPUCPU only | scikit-learn, XGBoost, whisper.cpp, llama.cpp | Basta para dados de planilha, modelos pequenos e inferência quantizada. Para treinar redes maiores, use Google Colab ou Kaggle (GPU gratuita com limite de uso) ou alugue GPU por hora.Enough for spreadsheet data, small models and quantized inference. To train larger networks, use Google Colab or Kaggle (free GPU with usage limits) or rent a GPU by the hour. |
A memória acabou (OOM). O que fazer, nesta ordemOut of memory (OOM). What to do, in this order
- Reduzir o tamanho do lote e usar acúmulo de gradiente para manter o efeito.Cut the batch size and use gradient accumulation to keep the effect.
- Ligar precisão mista (bf16 ou fp16).Turn on mixed precision (bf16 or fp16).
- Ligar gradient checkpointing: troca tempo por memória.Turn on gradient checkpointing: trades time for memory.
- Encurtar o contexto, as sequências ou a resolução das imagens.Shorten the context, sequences or image resolution.
- Trocar ajuste completo por LoRA ou QLoRA.Swap full fine-tuning for LoRA or QLoRA.
- Usar otimizador de 8 bits.Use an 8-bit optimizer.
- Escolher um modelo menor ou quantizado.Choose a smaller or quantized model.
- Alugar uma GPU com mais VRAM só pelas horas do treino.Rent a GPU with more VRAM just for the training hours.
A aba Hardware calcula o efeito de cada uma dessas escolhas.
The Hardware tab calculates the effect of each of these choices.
Hardware: cabe na minha placa?Hardware: will it fit my card?
O que decide se um modelo roda na sua GPU é quase sempre a memória de vídeo (VRAM). Escolha o modelo, o que quer fazer com ele e veja onde cada pedaço da memória vai parar.
What decides whether a model runs on your GPU is almost always video memory (VRAM). Pick the model, what you want to do with it, and see where each piece of memory goes.
Estimativa com margem de erro de uns 20 a 30%. Frameworks, kernels e fragmentação mudam o resultado real. Arquitetura aproximada, tipo Llama.Estimate with a 20 to 30% margin of error. Frameworks, kernels and fragmentation change the real result. Approximate Llama-like architecture.
Regra de bolso: bytes por parâmetroRule of thumb: bytes per parameter
| SituaçãoSituation | Bytes/parâmetroBytes/parameter | Modelo de 7 B7 B model |
|---|---|---|
| Rodar em fp32Run in fp32 | 4 | 28 GB |
| Rodar em bf16/fp16Run in bf16/fp16 | 2 | 14 GB |
| Rodar em int8Run in int8 | ≈ 1 | ≈ 7 GB |
| Rodar em int4 (quantizado)Run in int4 (quantized) | ≈ 0,5 – 0,6 | ≈ 4 GB |
| Treino completo com AdamW em precisão mistaFull training with AdamW in mixed precision | ≈ 16 | ≈ 112 GB |
Por que 16 no treino completo? Cada parâmetro guarda uma cópia em bf16 (2), seu gradiente (2), uma cópia mestra em fp32 (4) e dois acumuladores do Adam em fp32 (8). Ativações e cache vêm por cima.
Why 16 for full training? Each parameter keeps a bf16 copy (2), its gradient (2), an fp32 master copy (4) and two fp32 Adam accumulators (8). Activations and cache come on top.
Quatro coisas que ocupam a VRAMFour things that fill VRAM
PesosWeights
O modelo em si. Quantizar reduz o número de bytes por peso.The model itself. Quantizing lowers the bytes per weight.
Gradientes e otimizadorGradients and optimizer
Só no treino. LoRA treina uma fração minúscula e quase elimina esse custo.Training only. LoRA trains a tiny fraction and nearly removes this cost.
AtivaçõesActivations
Resultados intermediários guardados para a retropropagação. Crescem com lote × contexto. Checkpointing recalcula em vez de guardar.Intermediate results kept for backpropagation. They grow with batch × context. Checkpointing recomputes instead of storing.
Cache KVKV cache
Na geração de texto, guarda o que já foi lido. Cresce com o contexto e com o lote.In text generation, it stores what was already read. Grows with context and batch.
Onde conferir a sua: nvidia-smi no terminal mostra a VRAM total e em uso; dentro do Python, torch.cuda.mem_get_info().Where to check yours: nvidia-smi in the terminal shows total and used VRAM; inside Python, torch.cuda.mem_get_info().
Quiz: teste o que você aprendeuQuiz: test what you learned
Dez situações reais, cada uma com dados objetivos, uma pergunta e quatro alternativas. Escolha uma resposta para ver a correção comentada.
Ten real situations, each with objective data, one question and four options. Pick an answer to see the explained correction.
GlossárioGlossary
Os termos que mais aparecem quando se fala de IA, em linguagem direta.
The terms that come up most when talking about AI, in plain language.