Construa e treine do zero um modelo GLM-5.3-Flash com Python
Autoria: freeCodeCamp.org · Assistir no YouTube
Vídeo de autoria do canal indicado, não da IANIA; todos os direitos pertencem ao criador. Transcrição, resumo e tradução gerados automaticamente; o conteúdo no idioma original é preservado na versão em idioma original.
Idioma original: inglês
Vídeo original: Build & Train a GLM-5.3-Flash Model From Scratch with Python · Canal: freeCodeCamp.org · 44:18 · Assistir no YouTube
Tópicos: Avaliação e benchmarks de IA, Modelos de IA
O tutorial apresenta a construção e o treinamento, com CPU, de uma versão reduzida do GLM-5.3-Flash, com 25 milhões de parâmetros. Explica fundamentos de transformers e componentes como atenção linear e esparsa, mixture of experts, conexões residuais e processamento de imagens. Depois, percorre o pré-treinamento e o reinforcement learning, comparando resultados e mostrando como estruturar experimentos. A ênfase está em formular boas perguntas de pesquisa, medir resultados com cuidado e iterar em pequena escala, em vez de depender de grandes recursos computacionais.
Pontos-chave
Seção intitulada “Pontos-chave”- O projeto reduz o modelo para 25 milhões de parâmetros e usa um vocabulário de caracteres ASCII, permitindo treinar em CPU.
- O pré-treinamento ensina o modelo a imitar os dados e prever o próximo token; o reinforcement learning recompensa respostas corretas.
- A arquitetura apresentada combina atenção linear e esparsa, mixture of experts, conexões residuais e pesos compartilhados entre embeddings e a camada de saída.
- O tutorial inclui um codificador de imagens simples que transforma patches de imagens em tokens para o modelo.
- Os experimentos exploram diversidade e ordem dos dados, estruturas de recompensa, temperatura e tamanho dos grupos de respostas.
- Os resultados relatados incluem melhora de 4% para 45% de respostas corretas após o post-training e aprovação em 16 de 24 tarefas, ante zero antes do reinforcement learning.
- Os resultados devem ser interpretados com cautela: o autor destaca possíveis bugs, amostras insuficientes e ausência de significância estatística.
- A recomendação é usar exemplos pequenos, alterar uma variável por vez e priorizar dados, ambientes e desenho experimental.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:00 | Objetivos do tutorial e pesquisa com modelos pequenos | O vídeo propõe construir e treinar uma versão de 25 milhões de parâmetros em CPU e destaca o papel do pesquisador no desenho de experimentos. |
| 04:36 | Previsão do próximo token e vocabulário | A explicação apresenta a previsão do próximo token e justifica usar caracteres ASCII como vocabulário reduzido. |
| 06:42 | Embeddings e fundamentos do transformer | Os tokens são convertidos em embeddings, processados pelas camadas do transformer e usados para calcular a distribuição do próximo token. |
| 08:48 | Arquitetura reduzida do GLM-5.3-Flash | O tutorial apresenta os componentes da arquitetura e as diferenças de escala entre o modelo original e a versão didática. |
| 10:20 | Implementação, conexões residuais e normalização | A explicação percorre embeddings, conexões residuais, RMS norm, codificação posicional e compartilhamento de pesos. |
| 15:04 | Atenção esparsa e linear | O vídeo compara atenção esparsa, que seleciona tokens relevantes, com atenção linear, que mantém um estado compacto. |
| 19:16 | Camadas de atenção e mixture of experts | São mostradas a organização das camadas e a seleção de especialistas para processar cada token. |
| 23:00 | Codificador de imagens | O tutorial mostra como dividir imagens em patches, convertê-los em tokens e treiná-los para reconhecer dígitos. |
| 26:10 | Pré-treinamento e experimentos com dados | O pré-treinamento é descrito como imitação dos dados, seguida de experimentos sobre diversidade, ordem e currículo de dados. |
| 30:18 | Reinforcement learning e avaliação | O vídeo explica recompensas baseadas em resultados, testes ocultos e avaliações das respostas do modelo. |
| 34:00 | Desenho de recompensas e escolha dos dados | São discutidas estratégias de recompensa e a importância de escolher tarefas e ambientes que ensinem o comportamento desejado. |
| 37:07 | Atualização dos pesos e experimentos pequenos | O autor descreve uma atualização parcial dos pesos e recomenda começar com exemplos simples para entender os efeitos do treinamento. |
| 39:11 | Resultados, variáveis e significância | Os resultados são analisados com ressalvas sobre possíveis bugs, regressões, tamanho da amostra e variação entre seeds. |
| 42:16 | Conclusões e prática de pesquisa | O encerramento recomenda experimentos pequenos e consistentes, com atenção à medição e à formulação de perguntas. |
Citações
Seção intitulada “Citações”Você precisa entender como os algoritmos atuais funcionam para inventar algoritmos melhores. — 02:01
Fazer essas perguntas é o que distingue um pesquisador experiente. — 04:05
O que você está ensinando, qual é o ambiente e o que o modelo está tentando fazer? — 35:33
Consistência é mais importante do que intensidade. — 43:48
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- GLM-5.3-Flash (modelo): Modelo apresentado como inspiração para uma versão didática reduzida, treinável em CPU.
- Transformer (conceito): Arquitetura que processa sequências de tokens para prever distribuições sobre o próximo token.
- atenção linear (conceito): Mecanismo que mantém um estado de tamanho fixo para resumir informações da sequência com menor custo.
- atenção esparsa (conceito): Mecanismo que seleciona tokens relevantes para limitar o cálculo de atenção.
- Mixture of Experts (conceito): Arquitetura que encaminha cada token a um subconjunto de especialistas, além de um especialista compartilhado.
- RMS norm (conceito): Método de normalização usado para manter as escalas dos vetores sob controle.
- pré-treinamento (conceito): Etapa em que o modelo aprende a prever os próximos tokens ao imitar os dados de treinamento.
- reinforcement learning (conceito): Etapa de treinamento que usa recompensas para aumentar a probabilidade de respostas corretas.
- Codex (ferramenta): Ferramenta de programação mencionada como auxílio para inspecionar código e apoiar experimentos.
- Claude Code (ferramenta): Ferramenta de programação mencionada como auxílio para explorar o código e os experimentos.
- freeCodeCamp.org (empresa): Canal que publicou o tutorial.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:00 Aprenda a construir e treinar do zero um modelo GLM 5.3 flash de 25 milhões de parâmetros usando apenas uma CPU padrão. Este tutorial aborda técnicas fundamentais de pré-treinamento e aprendizado por reforço, ensinando você a planejar experimentos eficazes e pensar como um pesquisador moderno de IA. >> Vamos construir e treinar o GLM 5.3 flash, que é o Ox Alpha, o mais novo e melhor modelo viral da Google AI. Vamos
00:30 fazer tanto o pré-treinamento quanto o pós-treinamento, além de construir tudo do zero. Assim, você vai aprender a fazer tudo o que os pesquisadores do GLM e os pesquisadores da OpenAI e da Anthropic fazem, só que em uma escala mais simples. E o trabalho de pesquisador de IA mudou drasticamente em apenas alguns meses. Então, este é o curso mais atualizado de que você vai precisar se quiser se tornar pesquisador de IA. Todo o código está no GitHub. Estes são os experimentos. Vamos reproduzir tudo. Você pode ver os gráficos. Então, está
01:00 abaixo do vídeo. Esta é a vaga mais recente da Anthropic, e essa vaga descreve 95% das funções de pesquisador de IA. Primeiro, você vai entender as arquiteturas e os algoritmos neste curso. Depois, vou mostrar como fazer pesquisa de IA de verdade, criando ambientes, usando aprendizado por reforço e fazendo perguntas. Então, neste momento, Claude Code e Codex AI estão programando todos os experimentos, e conseguem fazê-los de forma autônoma. Seu trabalho como pesquisador de IA é apenas ter uma ideia de alto nível sobre
01:31 quais experimentos fazer. Então, embora Anthropic e OpenAI possam estar inventando novos algoritmos, neste momento, estamos falando de transformers e aprendizado por reforço. Acho que elas estão concentrando 99% ou mais de seus esforços apenas em projetar dados e ambientes e, depois, otimizar esses algoritmos que você vai entender neste vídeo. E, pensando no futuro, seu trabalho como pesquisador de IA vai se tornar principalmente ter ideias de alto nível, e não programar. Os modelos de IA vão fazer toda a programação e
02:01 os experimentos. Mas você ainda precisa entender como os algoritmos funcionam. Não precisa escrever o código manualmente, mas as pessoas, os seres humanos, ainda são capazes de inventar conceitos melhores e mais rápidos, algoritmos mais rápidos e criar projetos melhores para o sistema. Depois, a IA pode implementar, experimentar, testar e assim por diante. É por isso que ainda vamos analisar o código e entender como ele funciona, embora não precisemos necessariamente escrever tudo do zero e manualmente. Mas, se quiser inventar novos algoritmos
02:32 como pesquisador de IA, você precisa entender como os algoritmos atuais funcionam. Então, embora o modelo original seja insano, com bilhões de parâmetros, o nosso modelo vai ter apenas 25 milhões e poderá ser treinado em uma CPU, GPU, MacBook, qualquer coisa. Eu o deixei bem simples. E é isso que você deve fazer. Ainda dá para fazer muita pesquisa aqui. Você pode aprender a fazer perguntas, a definir metas, tópicos e direções de pesquisa para a IA. Mesmo que você tenha muito poder computacional, não há nada a mais que possa fazer com ele
03:03 do que com apenas uma CPU. Acho que não, a menos que você queira construir um modelo que outras pessoas usem. Mas, aqui, estamos tentando aprender. Então, queremos principalmente aprender a fazer perguntas, e a IA pode ajudar a respondê-las com muita facilidade. A IA vai se tornar cada vez mais capaz de responder a perguntas, e, por enquanto, os humanos vão fazer as perguntas. Claro, não sabemos o que vai acontecer daqui a um ano: superinteligência, seja lá o que for. Aí os humanos serão inúteis. Então a IA fará tudo. Por enquanto, estamos apenas nos concentrando em aprender a fazer perguntas, perguntas de pesquisa,
03:34 definir metas e direções. Aqui estão alguns exemplos de perguntas que faremos e responderemos nesta pesquisa. Então, isso é algo real que você pode fazer. Você pode aprender a pesquisar usando apenas uma CPU. Digamos que você esteja treinando algum tipo de raciocínio com aprendizado por reforço. Você deve recompensar pontuações imperfeitas, pontuações parciais? Ou não? Bem, vamos testar. Vamos ver qual funciona melhor. O quanto você deve penalizar código inválido? E quanto à temperatura, ou aleatoriedade, na geração da próxima palavra durante o aprendizado por reforço?
04:05 Então, é uma questão de exploração versus aproveitamento do que o modelo já sabe. Estes são alguns exemplos, e fazer essas perguntas é o seu trabalho. É isso que diferencia um bom pesquisador experiente de alguém inexperiente. E a IA já consegue fazer todos esses experimentos sozinha. Até Soul Opus e Astra Fable, todo mundo consegue fazer esses experimentos. Aliás, se você precisar de ajuda para fazer e responder a essas perguntas, se quiser entrar em um laboratório de pesquisa de IA de verdade, participe da comunidade da nossa escola
04:36 onde simulamos um laboratório de pesquisa de IA de verdade. Você vai definir suas próprias metas de pesquisa ou usar as nossas, responder às nossas perguntas e nos ajudar a descobrir quais perguntas fazer. Estamos simulando o ensino e a orientação de pessoas para que aprendam a fazer pesquisa de IA de verdade. Certo, vamos começar. Sabemos que os LLMs vão prever a próxima palavra, o próximo token ou, no nosso caso, o próximo caractere, porque vamos construir — e você também vai construir — um modelo pequeno. Como eu disse, precisamos apenas de modelos pequenos para iterar rapidamente.
05:06 Então, neste exemplo, a entrada poderia ser return X plus, e o modelo vai prever 1, dependendo da tarefa e do prompt. Esse é o próximo token. Os LLMs de verdade usam tokenizadores BPE, ou seja, de codificação por pares de bytes. Com um texto como este, eles o dividiriam em tokens de subpalavras ou tokens de palavras. Normalmente, eles têm 150.000 ou 300.000 desses tokens de subpalavras e, então, conseguem codificar
05:39 qualquer texto. Qualquer texto pode ser representado com esse vocabulário. Mas, para facilitar o entendimento e o treinamento, vamos usar cada caractere ASCII. Assim, cada letra será seu próprio token. Aqui, se tivermos esta função, def int qualquer coisa, cada elemento será seu próprio token. Então, teremos apenas 260 tokens no nosso vocabulário. Assim, não precisamos treinar a tokenização. É mais simples.
06:09 Além disso, há um grande problema que surgiria mais adiante. Alguns de vocês talvez já conheçam a arquitetura transformer, a arquitetura de LLM, e saibam que há uma camada de embedding e uma camada de saída. As matrizes de pesos das duas usam o vocabulário de tokens como uma de suas dimensões. Então, se tivermos uma quantidade enorme de tokens, um vocabulário enorme de 250.000 tokens, em um modelo muito pequeno, essas matrizes corresponderiam à maioria, 95% dos parâmetros
06:42 seriam usados apenas na conversão do vocabulário. Os outros 5% dos parâmetros seriam usados nas camadas propriamente ditas e no próprio modelo. Se você não entendeu o que eu disse, tudo bem. É que, para modelos pequenos, também precisamos de vocabulários pequenos. Um vocabulário de 260 tokens é bom. Então, é assim que o próximo token é gerado dentro do transformer. Digamos que temos alguma entrada. Pode ser um número, um prompt, qualquer coisa.
07:12 E cada um desses tokens na entrada tem um vetor embedding correspondente que o representa. Cada um é substituído pelo seu próprio vetor embedding, que é como uma sequência de números que codifica o significado daquele token. Então, o token A tem alguns números, o token B tem alguns números, o sinal de mais tem alguns, o sinal de menos tem alguns. E o vetor do sinal de mais explicaria, de certa forma, ou conteria informações sobre como a adição é
07:44 feita, qual é a finalidade e qual é a função do token de mais. Assim, cada token do prompt é substituído pelo vetor correspondente que descreve seu significado. Esses vetores são aprendidos pelo LLM quando treinamos o LLM. O LLM aprende a representar o conceito de mais com alguns números. Depois, temos uma sequência de vetores, que é o nosso prompt, que entra no
08:16 transformer, nas camadas. Ele é processado pelo transformer e, no final, queremos prever o próximo token. Então, ele simplesmente transforma o que foi processado: o prompt inteiro foi processado e, ao final, transforma o que estiver nessa posição em uma distribuição de probabilidades sobre todo o vocabulário. Assim, com base no prompt, você obtém a probabilidade de cada token do vocabulário ser o próximo token.
08:48 É mais ou menos assim que funciona. Essa é a ideia básica do transformer. Agora, o GLM 5.3 flash tem algumas arquiteturas novas e componentes novos sobre os quais ainda não falamos no meu canal: uma combinação de atenção linear e esparsa, depois mistura de especialistas — falamos sobre isso, é muito conhecido — e então deep six, conexões residuais com restrição de variedade e conexões hiper. E este é bastante conhecido e antigo: usar o
09:18 a mesma matriz para converter o vocabulário de entrada e de saída em embeddings. Então, entrada e saída. Estas são as especificações do nosso modelo. O original é enorme, mas o nosso é minúsculo. Estas são as camadas: muitas camadas e muito menos experts. E o contexto tem apenas 192 tokens, enquanto um GLM tem 1 milhão de tokens. E você verá que, em nossos experimentos, antes do aprendizado por reforço
09:49 ele não realizará nenhuma das tarefas com sucesso. E, depois do aprendizado por reforço, realizará 16 das 24 tarefas com sucesso. Essas tarefas serão muito simples, como escrever uma função em Python que multiplica a entrada por dois. Mas você verá a diferença antes e depois do treinamento com RL. E aprenderá a fazer perguntas, a elaborar ideias e ambientes para o modelo aprender. Você também poderá ver, durante o treinamento, como o modelo está
10:20 aprendendo. Durante… Este é o gráfico que mostra como ele está aprendendo durante o treinamento. Vamos olhar o código agora. Vamos entender os algoritmos e como eles funcionam, mas ninguém vai programar isso. Mas cabe aos humanos entender os algoritmos e depois melhorá-los. Dizer à IA o que tentar, o que… E então a IA simplesmente vai experimentar muitas ideias com base na sua ideia. Mas você precisa saber qual direção seguir. Então, é isso que vamos entender nesta parte do código agora. Primeiro, temos o embedding e, em seguida,
10:51 passamos o ID de entrada. Digamos que este seja o nosso ID de token. [limpa a garganta] Isso vai consultar o vocabulário e selecionar o vetor que mencionei antes. E essa pode ser uma matriz enorme se você tiver um vocabulário enorme. E essa matriz de pesos também pode ser enorme. E, se você tiver um modelo pequeno, isso corresponderá a 95% dos parâmetros. Por isso, para modelos pequenos, usamos um vocabulário pequeno, de bytes. Então, ele vai recuperar o vetor deste token. E isso acontece no
11:24 início, quando está processando o prompt. Então, temos o número… Depois de converter todos esses vetores, teremos algo assim: esta é a dimensão do vetor e este é o número de tokens. Então, número de tokens, dimensão do token e lote — que indica quantas conversas independentes você tem neste enorme vetor X, neste tensor X. Veja como ele simplesmente pega esse vetor X e cria um array desses vetores X.
11:55 Essas serão as conexões residuais. Mais adiante, cada uma das conexões residuais — estas são conexões hiper restritas a uma variedade, da DeepSeek e da ByteDance — vai transportar informações diferentes adiante, sem que essas informações sejam processadas pela atenção. Assim, elas vão se misturar e serão transportadas para a frente. É como se fossem algumas vias expressas por onde passam diferentes tipos de informação. Então, acho que não vou entrar em muitos detalhes
12:27 aqui. Se isso lhe interessar, fiz alguns vídeos sobre o assunto, e você pode ler o artigo, porque acho que fica entediante e não posso ajudar muito com isso. Você precisa praticar por conta própria, ler, entender e experimentar. Se eu simplesmente explicar, talvez você não consiga acompanhar. Então, vamos passar por essas coisas. Essas conexões hiper vão se misturar umas às outras, dependendo de alguns pesos e das formas de combinação. Assim, elas compartilham informações entre si, entre as redes de atenção e as redes feed-forward,
12:58 e tudo isso. No final, elas serão combinadas em um único vetor de dimensão oculta. Com essas conexões hiper, você não tem apenas uma conexão residual. Você permite que o transformer forme e transmita muitos tipos diferentes de dados enquanto os processa. Em seguida, esse estado oculto é transformado em uma distribuição de probabilidade sobre todo o vocabulário, usando uma matriz de pesos. Ou seja, uma distribuição que indica qual token é
13:30 provável que venha a seguir e se encaixe nesse contexto. E esta é a outra parte que pode ser absolutamente enorme em comparação com o resto do modelo, caso o vocabulário seja grande e o modelo seja pequeno. Essa matriz de pesos que transforma o estado oculto, multiplicado pelo vocabulário, pode ser grande. E, se você se lembra, no início do transformer também tínhamos vocabulário multiplicado pelo estado oculto — ou o estado oculto é, na verdade, o embedding do vetor. Então, você pode usar
14:01 essa mesma matriz de pesos para os dois casos. Assim, tanto para o vocabulário, ao selecionar o vetor de cada token, quanto aqui no final, ao gerar a distribuição de probabilidade, você pode usar exatamente a mesma matriz, e isso funciona bem. Dependendo da arquitetura, eles usam isso aqui. E, assim, você economiza muitos parâmetros que pode usar em diferentes partes. Outra parte é a norma RMS. Ela simplesmente vai normalizar os vetores. Então,
14:33 veja como temos um valor aqui muito diferente destes. Nas redes neurais, na forma como elas propagam os gradientes para trás e fazem cálculos matemáticos, isso pode atrapalhar os cálculos, fazer os pesos explodirem ou ficarem muito pequenos, ou fazer com que esse valor concentre todo o peso e torne estes irrelevantes, porque ele é muito maior. Então, normalmente, você quer manter os números perto de 1, -1 e 0, e em escalas semelhantes.
15:04 Assim, esses números não ficam descontrolados quando você multiplica tantos deles em sequência. Isso é codificação posicional. Como o Transformer sabe qual token vem depois de qual? Porque, no mecanismo de atenção, você multiplica tokens por outros tokens, mas não sabe a ordem dos tokens no prompt. Então, cada vetor de token é rotacionado. Por exemplo, se você tiver um vetor, pega pares
15:36 de dimensões e rotaciona cada par. E, dependendo de onde esse par está na sequência e de onde o token está na sequência de tokens, as rotações serão um pouco diferentes. Assim, o Transformer vai aprender a posição com base no quanto esses vetores foram rotacionados. No GLM, eles usam NOPE. É uma versão de RoPE no modelo principal e, em seguida,
16:07 RoPE no indexador esparso. Esse indexador esparso verifica, na atenção, a que partes devemos dar atenção e a quais não devemos, porque, aqui, o mecanismo de atenção não vai considerar tudo, ou seja, toda a janela de contexto. Esse token vai considerar apenas os tokens mais relevantes. Então, esse indexador vai procurar os tokens mais relevantes para que esse token os considere. O indexador também é um mecanismo de atenção, mas muito
16:39 mais leve, muito mais barato e muito mais rápido. Ele simplesmente procura relevância e não precisa fazer tantos cálculos quanto a atenção regular. Então, seleciona os tokens mais relevantes, e só esses tokens são calculados com a atenção regular completa. Assim, para cada token no mecanismo de atenção, ele vai selecionar os N tokens mais relevantes. Podem ser os 2.000 tokens mais relevantes ou os 1.000 tokens mais relevantes, e depois fazer a atenção
17:10 com eles. E aqui, a atenção é simplesmente escalada com base nesse pequeno indexador. Então, esse pequeno indexador… Em vez de escalar assim, vai escalar muito mais lentamente, porque o tamanho da atenção é sempre fixo, não escala, mas o indexador escala com o comprimento da sequência. Comprimento da sequência. Estou falando de como o custo computacional escala com o comprimento da sequência, e ele vai escalar muito mais lentamente conforme o comprimento da sequência aumenta, exigindo muito menos computação, porque
17:43 esse indexador esparso é um tipo de atenção muito mais leve e faz muito menos cálculos. Só precisa encontrar os tokens relevantes. Então, como você pode ver… A atenção linear é diferente desta atenção quadrática padrão. Ela mantém… Para não confundir você, deixe-me explicar primeiro que o mecanismo de atenção deles não contém codificações posicionais. E só o indexador esparso contém
18:14 codificações posicionais. E então… NOPE significa que não há codificações posicionais. Então, aplicamos RoPE à atenção e ao indexador apenas para simplificar o nosso modelo. E a atenção linear é simplesmente atenção linear KDA. Isso é um modelo de espaço de estados. Vou explicar. Então, temos linear, linear, linear, esparsa. As lineares são baratas. Elas sempre mantêm um vetor constante. Então, imagine que
18:45 você tem tokens, tem esse estado, como uma matriz, que funciona como uma memória de todos os tokens. E todos os tokens, à medida que chegam, são inseridos nesse estado, nessa memória, que tem sempre o mesmo tamanho. É como simplesmente adicioná-los ali. Assim, as camadas lineares vão se lembrar dos tokens recentes. Elas não vão se lembrar dos tokens passados. Porque, quanto mais distante estiver o token, mais ele terá sido modificado, terá sido alterado pelos tokens mais recentes. Então, isso serve para os tokens recentes.
19:16 E elas são muito rápidas, bem mais rápidas do que a atenção. Já a atenção serve para tokens a longa distância, em qualquer lugar da context window. Pela minha experiência, isso treina muito mais rápido e faz inference muito mais rápido do que a atenção. É por isso que isso é otimizado para inference. Então, as camadas lineares carregam o histórico comprimido de forma barata: a memória. As camadas esparsas recuperam periodicamente detalhes distantes exatos.
19:48 Aqui está o código das camadas e da atenção. Vou mostrar: é muito simples. Você só vai pegar a cada quarta camada e defini-la como atenção esparsa. E esta é a atenção linear. Então, você tem alguns tokens, e todos eles vão para essa matriz, a matriz de memória. Chamam isso de estado de chave-valor em execução. Assim, conforme o contexto cresce e o comprimento da sequência aumenta, esse estado permanece fixo. Então, essa é uma forma de lembrar coisas sem
20:19 escalar quadraticamente. A desvantagem é que você perde algumas informações, porque está comprimindo-as. Na atenção esparsa, normalmente você observa uma janela fixa dos últimos n tokens, os últimos 2.000 tokens. E então pode observar posições regulares ou procurar tokens relevantes mais atrás. E depois temos a mistura de especialistas. Por exemplo, no GLM, você tem 288
20:52 especialistas escolhidos. E cada token vai passar por oito dos 288. Há também um especialista compartilhado. Todo token passa pelo especialista compartilhado, e esse especialista aprende algumas informações comuns a todos os tokens, para que os outros especialistas não precisem desperdiçar capacidade com isso. Então, podemos ter oito especialistas roteados e dois escolhidos entre oito, além de um compartilhado, no nosso modelo pequeno. Também poderia ter
21:25 um modelo com apenas dois especialistas e um roteado. Quer dizer, um escolhido. Aqui mostro a configuração do modelo que vamos treinar. Já mencionamos isso: oito especialistas, 12 camadas etc. Então, há estas quatro conexões hiper. Depois, dentro da atenção, há as conexões. Entre a atenção e o MoE, elas meio que se juntam na atenção, depois se expandem de novo e voltam a se juntar no MoE, e então
21:56 Então, aqui elas estão conectadas como conexões residuais. E aqui também estão conectadas como conexões residuais; assim, passam pelo MoE e também percorrem o MoE. A atenção move informações entre as posições dos tokens. O MoE aplica transformações especializadas a cada posição. As conexões residuais preservam a representação anterior enquanto adicionam as duas atualizações. E várias conexões preservam diferentes tipos de informação. Então, a entrada e a saída compartilham uma matriz,
22:27 portanto, os pesos de saída e os pesos de embedding são a mesma matriz, como mencionei antes. Então, leem tokens de byte e preveem o próximo byte com a mesma matriz de pesos. Uma matriz aprende tanto os embeddings dos tokens quanto os logits de saída. Ou melhor, a matriz de pesos que os transforma nisso. Isso se chama compartilhamento de pesos; ele remove uma segunda matriz grande e faz com que a leitura e a previsão de bytes usem a mesma geometria aprendida. Então, talvez haja
23:00 algum benefício nisso também. Não sei se há pesquisas sobre isso, provavelmente há. Talvez você também possa fazer algumas. O GLM Flash também tem visão. Então, há uma imagem, que será convertida em alguns embeddings de patches; eles serão convertidos em tokens e, depois, combinados com o modelo principal. Para imagens, elas serão divididas em patches. Cada patch é um token, então ele tem esses embeddings posicionais rotativos 2D.
23:35 É semelhante a rope, só que em 2D. Digamos que você tenha a imagem número oito, que é uma imagem RGB de 32 por 32. Neste caso, ela será dividida em patches de 8 por 8. Há dois blocos de visão na nossa versão pequena que codificamos. Aliás, todo esse código está no GitHub. Todo o código está aqui no GitHub, então você pode conferir. Estes são os experimentos.
24:05 Cada um desses patches — quatro patches — vai se tornar um vetor, um vetor de embedding de token. Então, é uma combinação de 2 por 2. Assim, no final, teremos 4 por 4, ou seja, 16 tokens a partir desta imagem de 32 por 32. Se você tiver outra imagem que não seja de 32 por 32, ela precisará ser redimensionada para esse formato e receber preenchimento, ou ser cortada. Então, isso é apenas para o nosso encoder. O GPT
24:36 tem algum encoder de imagem, sabe, esses outros modelos também, e nós também podemos criar um. Fiz este aqui bem rapidamente. Os tokens de imagem vão ter alguma marcação, como “a imagem começa aqui”, depois todos os 16 tokens de imagem e, em seguida, “a imagem termina aqui”. É assim que eles são adicionados à context window. Há essas marcações. E pode haver texto ao redor. A propósito, este token de início de sequência, que eu não mencionei, é um token especial
25:08 no vocabulário. Ele apenas indica que este é o início de uma sequência de conversa. E então você pode anexar o texto a todos esses tokens. E o próximo aqui, por exemplo, seria o número sete, o token previsto. Isso se a imagem for de um dígito sete. Então, treinamos um pequeno transformer para observar a imagem de um dígito e nos dizer qual é o dígito. Então, se você tiver mais interesse nos
25:38 detalhes minuciosos, basta pedir ao Codex ou ao Claude Code para clonar este repositório. Você pode perguntar sobre o código, sobre tudo, sobre como tudo funciona. Também pode pedir para ele desenhar estes gráficos, como fiz aqui. Então, estes são exemplos. É claro que, para nós, isso é muito visível. É muito fácil de ver. Enfim, nosso encoder de visão, nosso transformer de visão, reconheceu dígitos com sucesso usando o método que expliquei. Se quiser fazer alguma pesquisa, você pode torná-los bem mais difíceis e depois tentar
26:10 ver em que momento ele não consegue mais reconhecê-los. Vamos então analisar o pré-treinamento. Temos um prompt que é uma função de Python. E depois temos esta conclusão, gerada pelo modelo. Como a tarefa é retornar x + 1. No pré-treinamento, ele não está pensando nessa resposta. Está apenas repetindo os dados. Então, está apenas repetindo isso. É assim que aprende. Ele já tem todos esses exemplos.
26:41 Então, é semelhante ao aprendizado por imitação. Ele está imitando. No pré-treinamento, está imitando a escrita. Está aprendendo o que todos esses tokens, todos esses caracteres, significam, para poder gerá-los. Depois, no aprendizado por reforço, vai aprender a gerar e a pensar em quais respostas estão realmente corretas. Então, no pós-treinamento, está aprendendo a ser mais inteligente. Se você tiver um “red”, ele prevê “you”; se tiver um “return”, prevê o espaço. Você tem muitos exemplos de treinamento
27:13 a partir de apenas um prompt. Este é o pipeline clássico de pré-treinamento: probabilidades, entropia cruzada, pesos atribuídos, e então o otimizador atualiza todos os parâmetros com base na correção do próximo token. A maioria das pessoas usa AdamW, mas fiz isso por simplicidade; então, não usamos os dois, usamos apenas AdamW. Veja como os gradientes vão de uma distribuição de probabilidade incorreta para uma mais correta.
27:43 Eles literalmente mudam a escolha. Isso vai alterar milhões de pesos, então o byte correto fica um pouco mais provável a cada vez. Veja como, no início, antes do pré-treinamento, ele só gerava alguns caracteres aleatórios, se este for o prompt. Mas, depois, aprendeu a gerar isto. Agora, vamos ver algumas perguntas de pesquisa e experimentos que fiz. É assim que se faz pesquisa. Este é um exemplo bem comum, então você
28:13 vê que, se tiver menos dados e repetir os dados, o modelo vai aprender mais rápido no começo, mas, depois, mais dados vão acabar prevalecendo. A diversidade não é útil se você fizer apenas algumas etapas, mas, depois, a partir de 200 etapas, ela se torna cada vez mais útil. Certo, agora digamos que você tenha três tipos diferentes de dados: tipo A, tipo B e tipo C. É melhor treinar primeiro com o tipo A e depois com o tipo B,
28:44 Então, digitar C ou intercalar os dados? Você vai ver que, se treinar assim, quando o modelo começar a aprender C, vai começar a esquecer A e B. Por isso, é melhor intercalá-los, e você também pode demonstrar isso com um experimento. Se quiser, pode fazer esse experimento. Intercalar os dados também melhora a geração e evita o esquecimento catastrófico de dados aprendidos anteriormente. Então, blocos homogêneos
29:16 provavelmente aumentaram o viés de recência ou o esquecimento, mas você precisa saber o que o seu experimento está medindo. Aqui, estamos medindo apenas o desempenho. Não estou medindo se isso aumenta o viés de recência ou o esquecimento, então não posso afirmar isso. Só posso sugerir que talvez seja o caso. E se fizermos assim? E se primeiro ensinarmos padrões repetidos, padrões simples, e depois ensinarmos dados mais diversos? Talvez, no começo, sejam coisas mais simples de aprender e, depois, coisas mais complexas. Então, estamos comparando isso
29:47 com ensinar apenas coisas simples e apenas coisas complexas. E já sabemos que ensinar apenas coisas simples tem desempenho inferior: o modelo se ajusta demais aos mesmos dados simples. E, aqui, o aprendizado curricular não trouxe progresso substancial em comparação com simplesmente treinar com os dados complexos desde o início. Talvez esses dados complexos também fossem simples demais, então preciso pensar com cuidado na configuração do meu experimento. Além disso, essa diferença pode não ser estatisticamente significativa, dependendo de quantas vezes medi e de como
30:18 medi. Preciso pensar em todas essas coisas, e a IA pode ajudar você a entendê-las, refletir sobre elas e configurar seu experimento. Agora, vamos dar uma olhada no aprendizado por reforço. Aqui, o aprendizado por reforço é diferente do pré-treinamento. Pré-treinamento é apenas aprender a repetir texto. É aprender o que cada token significa. No aprendizado por reforço, o modelo tenta gerar respostas, e então recompensamos as respostas corretas. Então, de alguma forma, não sei como, mas ele está aprendendo a pensar de algum jeito. E, se você descobrir como,
30:49 você será o pesquisador de IA mais famoso. Mas, no aprendizado por reforço, ele está aprendendo a usar seu processo de raciocínio ao longo do transformer para descobrir a resposta correta. Hoje, rastrear uma única tentativa de execução, a conclusão de uma única tarefa, no aprendizado por reforço pode levar até dias em laboratórios de ponta como OpenAI e Anthropic. Se você quiser que o modelo, se quiser ensinar o modelo a trabalhar por dias, durante o treinamento você vai deixá-lo tentar concluir tarefas que levam dias. Então,
31:23 só um comentário: se você quiser ajudar esses laboratórios, também pode trabalhar em inference. Uma inference mais rápida significa que você gera dados mais depressa e pode treinar mais rápido. Então, gere código, execute testes, avalie o que está correto e o que está incorreto e, depois, atualize os pesos do modelo. Você não vai mostrar os testes ao modelo. Vai apenas avaliar o resultado dele, porque, se mostrar os testes, ele pode
31:54 explorar as recompensas, o que significa, por exemplo, talvez ler o resultado em vez de aprender a resolver os problemas. Aprender a invadir o Hugging Face ou sistemas diferentes, como aconteceu. No nosso pós-treinamento de um pequeno exemplo, passamos de 4% de respostas corretas para 45% de respostas corretas depois do treinamento. Então, normalmente, você pode simplesmente pedir a Fable, Fable, Opus e Soul que façam esse pós-treinamento para você. É isso que você precisa aprender: o que Opus e Fable não sabem é
32:26 definir a direção do experimento e ter ideias para experimentos. Eles conseguem fazer o treinamento por reforço simplesmente porque isso já foi feito tantas vezes na internet que eles sabem como fazê-lo. Mas o que você precisa praticar agora é o seu julgamento, o seu julgamento sobre experimentos. Que tipo de ideias? Depois, eles podem realizar os experimentos. Então, antes do aprendizado por reforço, acertou zero de 24; depois do aprendizado por reforço, 16 de 24 perguntas. Pass@1 significa que você dá apenas uma tentativa
32:57 e depois avalia se está certo ou errado ao testar o modelo. Se você tem pass@8, significa que dá oito tentativas e, se alguma das oito estiver correta, considera a resposta correta. Quer dizer, você faz a mesma pergunta e deixa o modelo tentar respondê-la várias vezes. Mas aqui, deixamos que responda apenas uma vez e depois vemos se está certo ou errado. É claro que você sempre precisa observar como está medindo os resultados. Por exemplo, neste caso, estamos testando o modelo em tarefas semelhantes
33:28 às que aprendeu durante o treinamento. Não são iguais, mas são semelhantes. Porque, assim, ele vai aprender padrões, vai aprender a realizar essas tarefas e, depois, vai aprender a aplicá-las a números diferentes, talvez a operações diferentes. Agora, quanto mais diversidade você quiser, quanto mais generalidade quiser, maior precisará ser o modelo. Mais parâmetros, mais compute, mais dados. E, então, ele vai se tornar mais geral, mais diverso. Mas não se preocupe com isso. Você sempre pode fazer pesquisa. Acho que é possível fazer boas pesquisas até mesmo em uma CPU. Sinto que
34:00 se você quiser conseguir um emprego na OpenAI e na Anthropic, não precisa de GPUs. Você quer aprender, quer ensinar a si mesmo a construir ambientes para aprendizado por reforço e a pensar sobre eles. Verificar se o modelo está aprendendo nesses ambientes é importante. Não é importante aumentar a escala, a menos que você esteja trabalhando especificamente com aumento de escala ou pré-treinamento. Se a tarefa for retornar 2 * X, antes do aprendizado por reforço, o modelo retornaria X * X; depois do aprendizado por reforço,
34:31 ele retornaria x vezes dois. Então, aqui, gerou a resposta corretamente, aprendeu. O que o aprendizado por reforço fez foi aumentar a probabilidade de a resposta correta ser gerada, com base em todos os parâmetros. Há muitas maneiras de estruturar as recompensas. Por exemplo, você pode dar mais um para passar em todos os testes, zero para um formato válido, mas com o número errado, e talvez menos um para sintaxe inválida de Python. Essa é apenas uma maneira. Você pode
35:02 simplesmente dar zero para uma resposta inválida ou errada e um para passar em todos os testes. Você também pode dar um ponto se o modelo escrever no formato correto. Se escrever Python correto, você pode recompensá-lo. Há muitas maneiras diferentes. E isso envolve experimentação e evidências empíricas, mas também acho que uma quantidade muito maior de dados é muito mais importante do que a estrutura desses algoritmos. Então, você vai encontrar um algoritmo bom o suficiente e, depois,
35:33 vai obter retornos decrescentes ao pensar no algoritmo, em vez de pensar nos dados. Você vai melhorar muito mais o modelo se pensar: o que estou ensinando a ele? Qual é o ambiente? O que ele está tentando fazer? Ele consegue fazer isso? Consegue aprender? Então, definir a pergunta para o ambiente, para os dados e sobre o que o modelo está aprendendo é mais importante. É o mais importante depois que você tem um algoritmo bom o suficiente. É por isso que a Deep Seek não está mais investindo um esforço substancial em GRPO. O GRPO, o algoritmo de aprendizado por reforço,
36:04 é bom o suficiente. Se investirem mais esforço nele, os retornos não serão tão bons quanto se investirem mais esforço em dados de treinamento, pós-treinamento e ambientes. O verificador vai executar testes ocultos. Você não mostra esses testes ao modelo. Agora, você tem modelos como GPT, Fable e Astra, que possivelmente vão tentar invadir e inspecionar seus verificadores. Isso está acontecendo agora. Há diferentes maneiras de fazer isso. Por exemplo, em GRPO e
36:36 outros algoritmos, você pode fazer a mesma pergunta e deixar o modelo gerar 16 respostas. Depois, pode recompensar cada resposta com base em estar correta, incorreta, em Python inválido etc. Em seguida, queremos calcular quanto cada resposta é melhor ou pior do que as outras, em relação à média. Isso é chamado de vantagem. A recompensa é simplesmente 1, 0 ou -0,1. Essa é a sua recompensa.
37:07 Menos a média das outras recompensas. Assim, o modelo vai calcular se a resposta é melhor do que a média e quanto é melhor ou pior do que ela. As respostas melhores vão se tornar mais prováveis, e as piores, menos prováveis. Isso é bom porque você não precisa de um crítico separado, como um modelo separado para revisar e avaliar os resultados. Você não precisa de humanos para fazer isso. Pode simplesmente deixar o modelo gerar várias respostas e compará-las entre si.
37:37 Então, não vou atualizar o modelo inteiro com esses sinais de aprendizado por reforço. Vou atualizar apenas o último bloco, a camada final de normalização e a cabeça de saída. Como mencionei antes, os pesos entre a entrada e a saída são compartilhados. Mas vou atualizar só o final, porque assim, em primeiro lugar, não alteramos as camadas anteriores, que contêm outros conhecimentos, e elas podem acabar esquecendo parte desses conhecimentos, já que agora estamos modificando o modelo com esses novos dados. Não estamos treinando com os dados antigos.
38:09 Então, isso pode alterar demais algumas coisas. E também é mais rápido, pois atualizamos menos pesos. Você também pode usar LoRA. Pode usar técnicas diferentes. Pode atualizar o modelo inteiro. Há várias técnicas diferentes. Você pode pesquisar sobre isso, se quiser. Também pode fazer pesquisas e experimentos, testar diferentes maneiras de atualizar alguns blocos e tentar entender o motivo. Então, tente usar exemplos simples nos seus experimentos. E é isso que o MIT diz. O MIT diz que você precisa começar
38:41 com exemplos simples, para entender o que está acontecendo. Isso é melhor do que fazer experimentos enormes e complexos sem saber o que está acontecendo. RLOO é o algoritmo que estou usando. Como eu disse, os algoritmos não importam tanto. Os dados é que importam. O que o modelo vai aprender depende dos dados que fornecemos. Como nosso modelo era pequeno, conseguimos melhorá-lo apenas em tarefas semelhantes às que usamos no treinamento. Por outro lado, se você tiver modelos grandes
39:11 como os da OpenAI, eles também vão treiná-los em outras tarefas diferentes. Você poderia dizer que eles talvez também só melhorem nas tarefas em que foram treinados, mas eles treinam com tudo. E esta é uma piada sobre as pessoas que reclamam que os LLMs só aprendem o que está nos dados de treinamento. Aí o outro cara diz: “Então vamos colocar tudo nos dados de treinamento”. Tínhamos estas operações em Python: incrementar, dobrar e verificar se é par. São apenas algumas tarefas em Python, e o modelo melhorou nelas.
39:42 E agora, curiosamente, ele não melhorou nesta aqui. Não sei por quê. Talvez eu precise verificar. Então, talvez haja um bug no meu código, um bug gerado pela IA, um bug no meu experimento ou algo assim. Ou, se não for um bug, então é ainda mais interessante, mas provavelmente é um bug. E, nas tarefas com as quais ele não foi treinado, não houve melhora. Pode até ter regredido. Agora, isso depende de como calculamos a significância estatística, então é preciso sempre ter cuidado.
40:13 Houve mesmo uma regressão? Você tem amostras suficientes? Fez o cálculo corretamente? Talvez seja necessário amostrar várias vezes para ver a média em diferentes porcentagens. Então, duas famílias que antes tinham um bom desempenho regrediram porque apenas uma superfície estreita de parâmetros foi otimizada para a distribuição de recompensas das tarefas. Mas houve melhora nas coisas em que o treinamos, com base no nosso ambiente. Isso significa que você pode ensiná-lo o que quiser, desde que saiba
40:44 como construir ambientes. Ao fazer experimentos, você deve alterar apenas uma variável por vez. Por exemplo, você pode ter todas estas variáveis diferentes: a recompensa, como você recompensa, o tamanho do grupo, quantas respostas você gera de uma só vez — por exemplo, oito por prompt —, a temperatura, que controla a aleatoriedade, ou a penalidade, as recompensas negativas. Se estiver fazendo pesquisa, você deve fazer um experimento com uma variável por vez.
41:14 Aqui, fiz vários experimentos diferentes. Veja: se eu definir, por exemplo, o tamanho do grupo como quatro, o desempenho é muito bom, melhor do que com o tamanho do grupo 16. Então, a temperatura 0,2 é mais determinística, menos aleatória, e tem desempenho melhor do que uma temperatura mais aleatória. E, nestes experimentos sobre recompensas binárias, como 0 ou 1, outras recompensas parciais ou nenhuma penalidade por respostas inválidas, uma penalidade rígida por respostas inválidas, todos tiveram o mesmo desempenho no meu conjunto de dados. Agora,
41:44 você não quer fazer apenas cinco; quer fazer uns 500 ou 5.000 desses experimentos para obter conclusões melhores. Mas veja só que horror. O tamanho do grupo quatro venceu o tamanho do grupo oito nesta seed, mas perdeu nesta seed e também nesta. Certo, isso significa, em primeiro lugar, que, com a minha configuração e os meus dados de treinamento, isso não tem muita influência. Em segundo lugar, precisamos treinar mais para verificar a significância estatística real.
42:16 E também pode ser que isso não seja tão importante. Mas, se você estiver treinando modelos enormes, até pequenas diferenças podem representar muito dinheiro economizado. O treinamento do seu modelo fica um pouco mais rápido, o que pode economizar muito dinheiro. Por isso, quando as pessoas avaliam seus artigos, vão pedir que você teste com três seeds. E as três seeds devem levar a uma conclusão clara. Por exemplo, em todas as três seeds, o tamanho de grupo quatro deve ser melhor do que o tamanho de grupo oito.
42:46 Então, nenhum dos meus experimentos produziu melhorias estatisticamente significativas. Talvez meus experimentos sejam muito pequenos. Talvez, à medida que você treina modelos maiores, encontre uma configuração de parâmetros ideal cada vez mais clara e precisa. E aqui podemos revisar cada parte. O pré-treinamento vai ensiná-lo a escrever em Python. A visão vai ensiná-lo a reconhecer imagens e incorporá-las ao transformer, ao modelo de linguagem. E
43:16 o aprendizado por reforço, no nosso caso, vai melhorar as operações de incrementar e dobrar. Então, recomendo que você converse com o Codex ou o Claude Code. Você pode perguntar: “Que tipo de experimento posso fazer aqui?” E não se preocupe tanto com a escala. Só quero que você aprenda a fazer alguns experimentos, a pensar cientificamente, a medir corretamente e a chegar às conclusões certas. Você também pode publicar seus experimentos nas redes sociais. Se quiser se tornar pesquisador de IA, recomendo que continue publicando seus experimentos todos os dias ou
43:48 toda semana nas redes sociais. A consistência é mais importante do que a intensidade. Se você publicar por cinco dias seguidos, mas depois parar, não é bom. Se publicar uma vez por semana para sempre, é muito melhor. E é melhor simplesmente fazer experimentos e treinar um modelo por alguns segundos. Você não quer esperar alguns minutos ou algumas horas, porque isso é tempo perdido. Você precisa pensar em como praticar o desenvolvimento de experimentos, ambientes e perguntas. Não precisa esperar pelo
44:18 modelo, porque você não consegue treinar um modelo que supere os dessas empresas e que as pessoas venham a usar.
Transcrição original
[00:00] Learn how to build and train a 25 million parameter GLM 5.3 flash model from scratch using just a standard CPU. This tutorial covers core pre-training and reinforcement learning techniques, teaching you how to design effective experiments and think like a modern AI researcher. >> Let’s build and train GLM 5.3 flash, which is ox alpha, which is the latest best viral model from Google AI. We will
[00:30] do both pre-training and post-training as well as building everything from scratch. So, you will learn how to do everything GLM researchers, everything researchers at open AI Anthropic do, just on a simpler scale. And AI researcher job has dramatically changed in just a few months. So, this is the latest up-to-date course that you’re going to need if you want to become AI researcher. All of the code is in the GitHub. These are the experiments. We will reproduce everything. You see the charts. So, it’s
[01:00] below the video. This is the latest job posting for Anthropic, and this job posting describes 95% of AI researcher roles. First, you will understand the architectures and the algorithms in this course. Then, I will show you how to do actual AI research with designing environments, reinforcement learning, asking questions. So, right now, Claude code, Codex AI is coding all of the experiments, and it can do them autonomously. Your job as AI researcher is just to have high-level
[01:31] idea which experiments to do. So, even though Anthropic and OpenAI could actually be inventing new algorithms, right now, it’s transformers, it’s reinforcement learning. I think they are focusing 99% or more of their efforts in just designing data, environments, and then optimizing these algorithms that you’re going to understand in this video. And thinking for the future, AI researcher Your is mainly going to become a high-level ideas and not coding. AI models are going to do all of the coding and
[02:01] experiments. So, but you still need to understand how the algorithms work. You don’t need to write the code manually, but still people, humans are ones who can invent better, faster concepts, faster algorithms, and create better designs for the system. And then AI can implement, experiment, try out, etc. This is why we will still go over the code and understand how it works, even though we don’t necessarily need to write everything from scratch and manually. But if you want to invent new algorithms
[02:32] as AI researcher, you need to understand how the current algorithms work. So, even though the original model is insane, billions of parameters, our model is just going to have 25 million, and it can be trained on a CPU, GPU, MacBook, anything. I made it very simple. And this is what you want to do. You can still do so much research here. You can learn how to ask questions, how to set goals, topics, research directions from for the AI. Uh even if you have a lot of compute, there is nothing more you can do with it
[03:03] than with just a CPU. I don’t think unless you want to build a model that other people use. But here we’re trying to learn. So, we want to learn how to ask questions mainly, and AI can help answer those questions very easily. And AI will become more and more capable of answering questions, and humans are going to be asking questions for now. Of course, we don’t know what’s going to happen in a year, super intelligence, whatever. Then humans will be useless. Then AI will do everything. So, for now, we are just focusing on learning how to ask questions, ask research questions,
[03:34] setting goals, directions. Here are some example questions we will be asking and answering in this research. So, this is real stuff you can do. You can learn how to research on just CPU. So, let’s say you are training some reinforcement learning reasoning. So, should you reward imperfect score, partial score? Should you not? Well, we will try out. We will see which one works better. How strong should you punish invalid code? And then temperature or randomness of next word generation in reinforcement
[04:05] learning. So, it’s exploration versus exploitation with what it already knows. So, these are like a bunch of examples and just asking these questions is your job. This is what distinguishes experienced good researcher versus novel not inexperienced. And AI can do all of these experiments by itself right now. Even Soul Opus and then Astra Fable, everybody can do these experiments. By the way, if you need help answering asking these questions, you want to join a real AI research lab, join our school
[04:36] community where we simulate a real AI research lab. You will be either setting your own research goals or using ours, answering our questions and helping us figure out questions. We are simulating teaching people, coaching people how to do real AI research. Okay, so let’s start. We know that LLMs are going to predict next word or next token or next character in our case because we are going to build and you are also going to build a small model. As I said, we just need small models with fast iteration.
[05:06] So, in this example, input could be return X plus and the model is going to predict one depending on the task, depending on the prompt. This is the next token. So, the real real LLMs use BP tokenizers. Byte pairing coded tokenizers. So, they would If you have some text like this, they would split that into subword tokens or word tokens. Usually, they have 150,000 or 300,000 of these subword tokens and they can then encode
[05:39] any text. Any text is contained in uh with this vocab in in this vocabulary. But to make it simpler to understand, to train, we are going to make each ASCII character. So, each letter is going to be its own token. Here, if we have this function def uh int whatever, each of them is its own token. So, we just have 260 uh tokens in our vocabulary. So, we don’t need to do uh tokenization training. It’s simpler.
[06:09] Also, big problem that would happen later. So, some of you may already know uh transformer architecture, LLM architecture, and you know that there is embedding layer, there is output head layer. And both of those weight matrices use token vocabulary as one of their dimensions. So, if we have massive tokens, massive vocabularies 250,000, then on a very small model, those matrices would be majority, 95% of parameters
[06:42] would just go into the vocabulary conversion. And other 5% of parameters would go into actual layers and the model itself. So, if you did not understand what I said, it’s okay. Just for a small models, you also need small small vocabulary. 260 token vocabulary is good. So, this is how uh next token gets generated within the transformer. So, let’s say we have some input. So, it can be some number, some prompt, whatever.
[07:12] And each of those tokens in the input, uh each of them have corresponding uh vector embedding that represents them. So, each of them gets replaced with its own vector embedding, and vector embedding is like a sequence of numbers that encodes the meaning of that token. So, uh token A has some numbers, token B has some numbers, plus has some, minus has some. And then the vector for plus would kind of explain or contain how addition is
[07:44] done and what is the purpose, what is the functionality of token plus. So, every token in the prompt gets replaced with its corresponding vector that describes its meaning. These vectors are learned by the LLM when we train the LLM, these vectors are learned. So, LLM learns how to represent concept of a plus with some numbers. And then we have sequence of vectors, that’s our prompt, that goes into the
[08:16] transformer into the layers. It gets processed through the transformer and then at the end we want to predict the next token. So, it’s going to it’s going to just transform whatever was processed, the entire prompt was processed, it’s going to transform whatever is at the end into probability distribution over entire vocabulary. So, so based on the prompt, you will get for each token in vocabulary how likely it is to be the next token.
[08:48] That’s roughly how it works. So, that is the very basic idea of transformer. Now, GLM 5.3 flash has some new architectures, new parts that we didn’t learn about before on my channel. So, linear and sparse attention hybrid and then mixture of experts, we talked about this, it’s very famous. And then deep six, manifold constrained residual connections, hyper connections. And then this one is quite famous and old, it’s to use the
[09:18] same matrix for input and output vocabulary into embedding conversion. So, input and output. These are the specifications of our model. So, original is huge, but our is tiny. These are the layers, a lot layers, a lot fewer experts. And the context is just 192 tokens, while a GLM has 1 million tokens. And you will see that in our experiments, before reinforcement
[09:49] learning, it will not do any of the tasks successfully. And after reinforcement learning, it will do uh 16 out of 24 tasks successfully. Those tasks will be very simple, like write some Python function that multiplies input by two. But you will see the difference uh before and after RL training. And you will learn how to ask questions, how to design ideas and environments for the uh model to learn. You can see also during training how the model is
[10:20] learning. During This is the graph that shows how it’s learning during the training. Let’s look at the code now. So, we are going to understand the algorithms, how they work, but nobody’s going to be coding this. So, uh but it’s up to humans to understand algorithms and then improve them. Tell the AI what to try, what to And then AI is going to just try many ideas based on your idea. But you need to know the direction. So, this is what We’re going to be understanding this part of code uh now. So, first you have uh embedding and then
[10:51] passing input ID. Let’s say this is our token ID. [clears throat] This will just look into vocabulary and pick the vector that I mentioned earlier. And so, this could be a huge matrix if you have huge vocabulary. And this could be huge uh weight matrix. And if you have a small model, then this would be 95% of parameters. This is why for small model we use small vocabulary, bytes. So, then it’s just going to retrieve uh this token’s vector. And this is at
[11:24] the beginning when it’s processing the prompt. So, then we have num So, we after we convert all of these vectors, we we’re going to have like this is the dimension of the vector and then this is the number of tokens. So, number of tokens, token dimension and batch is like how many independent conversations you have in this huge X vector X tensor. You see how it will just take this X vector and create array of these X
[11:55] vectors. These will be the residual connections. So, later each of the residual connections, so these are manifold constrained hyper connections by DeepSeek and ByteDance and each of them is going to carry different information forward without that information being processed through the attention and so it’s going to be mixed up, it’s going to be like carried through forward. So, it’s like some highways where you pass before different types of information. So, I think I will not go into too much
[12:27] detail here. If you are interested here, I made some videos and you can read paper because I feel like it does get boring if and I cannot help you too much around this. You need to practice this yourself, read this, understand it, try this out. If I just explain, you will not be able to follow maybe. So, let’s just go through these things. Those hyper connections are going to get mixed into each other depending on some weights and ways of mixing. So, they are sharing information between each other between the attention feed forward
[12:58] networks and all of this. And at the end they’re going to get merged into a single hidden dimension vector. This way with these hyper connections, you don’t just have one residual connection. You allow the transformer to form and to pass many different types of data through it while processing. And then that hidden state gets transformed into probability distribution over entire vocabulary with some weight matrix. So, distribution of which token is
[13:30] likely to be next that fits in into that context. And this is the other part that can be absolutely huge compared to the rest of the model if the vocabulary is big and the model is small. So, this weight matrix that transforms that’s hidden state times um vocabulary can be big. And if you remember at the beginning of the Transformer, we also had vocabulary times hidden state or hidden state is actually vector embedding. So, you can actually use
[14:01] uh this same weight matrix for both of them. So, the vocabulary, the picking the uh vector for each token and at the end here generating probability distribution you can use the exact same matrix and it works well depending on the architecture um they use it here. And then you save a lot of parameters that you can use at different places. Another part is RMS norm. So, this is just going to uh normalize vectors. So,
[14:33] you see how we have like a very different number here than these. And neural networks and the way neural networks back propagate and do math calculations, uh this can mess with the calculations, make the weights explode, make them very tiny, or uh this can carry all of the weight and then make these irrelevant because this is so much bigger. So, usually you want to make the numbers around 1 -1 0 uh and uh similar in scale.
[15:04] And then these numbers will not go crazy when you multiply so many of them in a row. So, this is positional encoding. So, how does Transformer know which token comes after which one? Because in attention in attention mechanism, uh you have tokens multiplied by other tokens, but you don’t know the order of tokens in the prompt. So, each of the token vectors is rotated. For example, if you have some vector, you take pairs
[15:36] of dimensions and rotate each pair. And depending on where uh the number of like where in the sequence that pair is and where the token is in the sequence of tokens, you’re going to have a bit different rotations. So, Transformer will learn based on how rotated these vectors are uh their position. So, in GLM, they are using NOPE. That’s a version of Rope in main model and then
[16:07] Rope in the sparse indexer. This sparse indexer uh is checking in the attention which part we should it should attend to, which part it should not attend to because the way attention works here is it’s not going to attend to everything uh entire attention entire context window. So, this token will just attend to most relevant tokens. So, this indexer is going to search for the most relevant tokens for this token to attend to. And indexer is also attention mechanism, but a lot
[16:39] lighter, a lot cheaper, a lot faster attention mechanism. And it just looks for relevance and it doesn’t need to do so much computation that uh regular attention does. So, it picks most relevant tokens and then only those tokens are uh computed with the full regular attention. So, for each token in the attention mechanism, it’s going to pick uh n most relevant tokens. It can be 2,000 most relevant tokens or 1,000 most relevant tokens and then do attention
[17:10] with that. And then here, the attention is just scaling based on this small indexer. So, this small indexer So, instead of scaling like this, it’s going to scale very a lot slower because because the attention size is always fixed, it doesn’t scale, but the indexer scales with the sequence length. Sequence length. So, I’m talking about how compute scales with a sequence length, and it’s going to scale a lot slower with sequence length, a lot less compute because
[17:43] this sparse indexer is a lot lighter type of attention and does a lot less computation. Just needs to find relevant tokens. So, as you can see So, the linear attention is different from this standard quadratic attention. It keeps So, not to confuse you, let me first explain that their attention mechanism does not contain positional encodings. And only the sparse indexer contains
[18:14] positional encodings. And so So, nope means no positional encodings. So, we apply rope in attention and indexer just to make it simpler for our model. And linear attention is just KDA linear attention. So, this is state space model. I’ll explain this. So, we have linear linear linear sparse. So, linears are cheap. They always keep a constant vector. So, imagine that
[18:45] you have tokens, you have this like state like a matrix that that’s like a memory of all of the tokens. And all of the tokens that as they come, they get fed into this state into this memory, and it’s always same size. It’s like just adding it in there. And so, linears are going to remember recent tokens. They’re not going to remember past tokens. Because the further away token is, the more it’s been modified, it’s been messed up by the newer tokens. So, this is for the recent tokens.
[19:16] And these are so fast, a lot faster than attention. And attention is for uh long-range any tokens anywhere in the context window. So, by my experience, this trains a lot faster and inferences a lot faster as opposed to attention. That’s why this is optimized for inference. So, linear layers carry compressed history cheaply, memory. Sparse layers periodically recover exact distant details.
[19:48] Here is the code for the layers and attention. So, let me show you it’s very simple. So, you’re just going to take every fourth layer and set it as sparse attention. And this is linear attention. So, you have some tokens and they all get into this matrix memory matrix. They call this running key-value state. So, as context grows, sequence length grows, this state stays fixed. So, this is a way to remember uh stuff without
[20:19] scaling quadratically. The trade-off is you lose some information because you are compressing it. So, sparse attention usually in sparse attention you look at uh fixed window of last n tokens, last 2,000 tokens. And then you can uh look at regular uh spaces or you can search for relevant tokens uh behind. And then we have mixture of experts. For example, uh in GLM you uh you have 288
[20:52] uh chosen experts. And it’s going to choose each token will pass through eight out of 288. And there is one shared expert. Every token passes through the shared expert and that expert will uh learn some common information for every token, so other experts don’t need to waste capacity on that. So, we may have uh eight routed and two uh two out of eight chosen, and then one shared in our small model. I also had I
[21:25] can have a model with just two experts and one routed. I mean, one chosen. Here I show you the model configuration for our training model. We already mentioned uh this, so eight experts, 12 layers, etc. So, there are these four hyper connections. Then, you have uh inside of attention. So, between attention and then MoE So, they kind of merge into attention, then they expand back, and then merge back into MoE, and then so
[21:56] So, here they are connected like residuals. And here they’re also connected like residuals, so they pass MoE, and they go through MoE as well. So, attention moves information between token positions. MoE applies specialist transformations to each position. Residual attentions preserve the previous representation while adding both updates. And multiple connections preserve different type of information. So, input and output share one matrix,
[22:27] so the output weights and embedding weights are the same matrix, as I mentioned earlier. So, read uh byte tokens and predict next byte the same weight matrix. One matrix learns both token embeddings and output logits. Or I should say the weight matrix that transforms them into those. So, weight tying, this is how it’s called, remove second large matrix and makes reading and predicting bytes use the same learn geometry. So, maybe there
[23:00] is some benefit there as well. I don’t know if there is research, probably there is. Maybe you also can do some. So, there is also vision in GLM flash and it’s So, there is image, it’s going to convert that image into some patch embeddings, convert those into tokens, and then mix them into the main model. For images, it’s going to get divided into patches. Each patch is a token, so it has this 2D positional rotary embeddings.
[23:35] Similar to rope, it’s just 2D. So, let’s say you have image number eight, it’s 32 by 32 RGB image. And it’s going to get divided into 8 by 8 patches in this case. So, there are two vision blocks in our small version that we coded, that all of this code is in the GitHub, by the way. All of the code right here in the GitHub, so you can check it. These are the experiments.
[24:05] So, each of those patches, four patches are going to become one vector, one token embedding vector. So, 2 by 2 merge. And so, we will get 4 by 4 at the end, which is 16 tokens from this 32 by 32 image. So, if you have some other image that’s not 32 by 32, it must be resized into this shape and padded there or cropped. So, this is just for our encoder. GPT
[24:36] has any image encoder, you know, these other models, and we can also make any. I just made this one very quickly. So, image tokens are going to have some mark, like image starts here, and then all of the 16 image tokens, and then image ends here. So, this is how they get added into the context window. There are these marks. And you may have a uh text around. So, this beginning of sequence, by the way, I didn’t mention this is special token
[25:08] uh in the vocabulary. It just shows this is beginning of sequence of a conversation. And then you can append the text to all of these tokens. And then the next here, the next one would be, for example, number seven, predicted token. If this image is of uh image is a digit seven. So, we trained a small transformer to look at the image of a digit and tell us which digit it is. So, if you are interested more about the
[25:38] nitty-gritty details, you just tell your Codex or Claude Code to clone this repository. You can ask it about the code, about everything, how everything works. You can also tell it to draw these graphs, like I did here. So, these are examples. Now, of course, it’s very visible to us. It’s very easy for us to see. Anyways, our vision encoder, our vision transformer was successfully recognizing digits using this method that I explained. If you want to do some research, you can make these a lot harder and then try to
[26:10] see at which point it’s not able to recognize them. So, let’s look at the pre-training. So, we have some prompt that is a Python function. And then we have this completion, which is model generated. Uh because the task is return x + 1. Now, uh in pre-training, it’s not uh thinking of this answer. It’s just repeating what the data is. So, it’s just repeating uh these. That’s how it’s learning. It already has all of these.
[26:41] So, it’s similar to imitation learning. It’s imitating. Now, in pre-training, it’s imitating to write. It’s learning what all of these tokens, all of these characters mean, so it can generate them. And then in reinforcement learning, it’s going to learn to generate, to think about which answers are actually correct. So, it’s learning in post-training, it’s learning to be intelligent more. So, you have a red it predicts you if you have a return predicts the space. You have so many training examples just
[27:13] from one prompt. This is the classic pre-training pipeline probabilities cross entropy assigned weights and then optimizer is going to update all of the parameters based on result next token correctness. Uh so, AdamW most of people are using me on, but I just did it for simplicity, so we don’t use both, we just use AdamW. You see how gradients go from wrong probability distribution to more correct one.
[27:43] They are literally moving the choice. It’s going to change millions of weights, so correct byte becomes a bit more likely each time. You see how in the beginning, before pre-training, it was just generating some random uh characters if this is this is the prompt. But, later it learned to generate this. Now, let’s see some research questions and experiments I did. So, this is how they do research. This is very standard example, so you
[28:13] see if you have less uh data and you repeat the data, it’s going to learn faster in the beginning, but later more data will just overtake. So, diversity is not useful if you do like just a few steps, but then uh at 200 steps, it becomes more and more useful. Okay, now let’s say you have uh three different types of data, type A, type B, and type C. Is it better to uh first train on type A, then type B,
[28:44] then type C, or interleave them? So, uh you will see that if you train it like this, then as it starts to learn C, it’s going to start forgetting A and B. So, it’s better to interleave them and you can show this with an experiment as well. So, you can do this experiment if you want. So, interleaving data will improve generation as well as well as prevent catastrophic forgetting of previously learned data. So, homogeneous
[29:16] blocks likely increased recency bias or forgetting, but you need to know what your experiment is measuring. Here, we’re just measuring performance. We’re not I’m not measuring if it’s increasing recency bias or forgetting, so I cannot make those claims. I can just suggest that might be the case. How about this? What if we first teach it repeated patterns, simple patterns, and then after teach it more diverse data? So, maybe in the beginning, it’s simpler things to learn and then later more complex. So, we are comparing that
[29:47] to only simple things and only complex things. And so, we already know that simple things, they underperform only simple only same data, it overfits. And here, curriculum did not make substantial progress as opposed to just training for the the complex data from the start. Maybe this complex data was also too simple, so I need to think carefully about my experiment setup. Also, this difference may not be statistically significant, depending on how many times I measured, how I
[30:18] measured. I need to think about all of these things, and AI can help you understand and think about all of these things and setup of your experiment. Now, let’s take a look at the reinforcement learning. So, here reinforcement learning is different than pre-training. Pre-training is just learning to repeat text. And it’s learning what each token means. In reinforcement learning, it’s trying to generate answers, and then we reward correct answers. So in some way I don’t know how but it’s learning to think somehow and if you can figure out how
[30:49] you’ll be the most famous AI researcher. But in reinforcement learning it’s learning to use its thinking throughout transformer to figure out correct answer. Right now reinforcement learning traces single rollout single task completion is taking maybe even days in frontier labs like open AI and Anthropic. If you want the model if you want to teach the model to work for days you’re going to during the training you’re going to let it try to complete tasks that take days. So
[31:23] this is just by the way if you are if you want to help these labs you can also work on inference. Faster inference means you are generating data faster you are you can train faster. So generate code run tests score which is correct which is incorrect now. Different ways of scoring you can score only correct or partial results for example and then update the model weights. You will not show tests to the model. You will just evaluate its result because if you show test it can
[31:54] reward hack which means like maybe reading the result instead of learning how to solve them. Learning how to hack into hugging face or different systems what happened and uh in our post training of a small example we went from 4% correct answers to 45% correct answers after the training. So uh usually you can just tell Fable Fable and Opus and Soul to do this post training for you. Uh this is what you need to learn what Opus and Fable they don’t know is
[32:26] get the experiment direction get the experiment ideas. So they can do reinforcement learning trade training simply because it’s been done so many times on the internet they know how to do it. But your judgment, right now your judgment for experiments is what you need to practice. What kind of ideas? And then it can do the experiments. So before reinforcement learning zero out of 24, after reinforcement learning 16 out of 24 uh questions. Pass at one means you just give it one try
[32:57] and then judge if it’s correct or incorrect when you are testing it. If you have pass it eight, it means you are giving it eight tries and if any one of eight is correct, so you would take it as correctly answered. I mean, you just give it same question, let it try to answer multiple times. But here we just let it answer once and then see if it’s correct or incorrect. Of course, you will always need to see how you are measuring your results. For example, in this case uh we are testing it on similar tasks
[33:28] that it learned uh during training. It’s not same, but similar. Because then it’s going to learn templates, it’s going to learn how to do these tasks and then it’s just going to learn to apply to different numbers, maybe different operations. Now, the more diversity you want, the more uh generality you want, you need to scale the model. More parameters, more compute, more data. And then it’s going to become more general, more more diverse. But don’t worry about that. You can always do research. I think you can do good research even on a CPU. I feel like
[34:00] um if you want to get a job at OpenAI and Anthropic, you don’t need GPUs. You want to learn You want to teach yourself how to construct environments for reinforcement learning, how to think about them. Check if model is learning in those environments, that’s important. It’s not important that you uh scale unless you are working explicitly on scaling or pre-training. If the task is return 2 * X before reinforcement learning, it would return X * X and after reinforcement
[34:31] learning, it would return x times two. So here it generated correctly, it learned. So what reinforcement learning did is increased probability that the correct answer will generate based on all of the parameters. There are many ways in which you can structure rewards. For example, you can say plus one for all tests passed, uh zero for valid format but wrong number. And maybe minus one for invalid Python syntax. So this is just one way. You can
[35:02] just give zero for invalid uh or wrong and then one all tests. You can also give one if it writes a correct format as well. If it writes a correct Python, you can reward. So there are many different ways. And this is experimentation, empirical evidence, um in but I also think like it’s a lot more data is a lot more important than structure of these algorithms. So you will find a good enough algorithm and then you will uh
[35:33] have a diminishing returns on thinking about the algorithm as opposed to thinking about data. You will improve the model a lot more if you are thinking about what am I teaching it? What is the environment? What is it trying to do? Can it do it? Can it learn it? So setting up question for the environment, for the data, and what is it learning is more important. Is the most important thing once you have good enough algorithm. This is why Deep Seek is no longer uh putting substantial effort into GRPO. GRPO, the reinforcement learning
[36:04] algorithm, is good enough. If they put more effort, it will not yield as good returns as if they put more effort into data training, post training, environments. The verifier is going to run hidden tests. Now you don’t show these tests to the model. Now you have like GPT, Fable, Astra, they are going to they are possibly going to hack and see your uh um verifiers. So, this is something that’s happening right now. So, there are different ways you can do this. So, for example, uh in GRPO and
[36:36] other algorithms, you can uh give the same question and let model generate 16 answers. And then you can reward each answer based on if it’s correct, incorrect, wrong Python, etc. And then we want to calculate how much each of the answers is better or worse than other answers, than the average. So, they call this advantage. So, reward is just your 1 0 or -0.1. That’s your reward.
[37:07] Minus mean of other rewards. So, it’s just going to calculate is this better than average and how much is it better or worse than average. So, better ones are going to become more likely and worse ones will become less likely. This is good because you don’t need separate critic, like separate model to uh review the results and score the results. You don’t need humans to do it. You can just let it generate multiple times and compare them to each other.
[37:37] So, I’m not going to update the entire model with these reinforcement learning signals. I’m just going to update uh last block final normalization layer and the output head. Those are tied weights between input and output as I mentioned earlier. But just the end because this way, first of all, we are not changing previous layers that have some other knowledge and then they might be they might experience forgetting of other knowledge because now we are just changing on this new data. We are not training it on the old data.
[38:09] We So, it it might change stuff too much. And this is also faster, up- updating less weights. So, you can also use Laura. You can use different techniques. You can update the whole model. So, there are different techniques here. Um you are going to look into this if you want. You can also do research and experiments and try different ways of updating a few blocks and try to understand why. So, so try to uh when you do experiments, uh use toy examples. And this is what MIT says. MIT says you need to use start
[38:41] from small toy examples so you can understand what’s going on. It’s better than doing huge experiments, complex that you don’t know what’s going on. R L O O is the algorithm I’m using. So, algorithms, as I said, doesn’t matter too much. Data is what matters. What is it going to learn is based on which data we give it. So, because our model was small, we are able to improve it only around similar tasks that we train it on. But on the other hand, if you have big
[39:11] models like OpenAI, they are also going to train it on other different tasks. So, you could say that they might also only improve it on tasks they trained on, but they train on everything. And this is a joke uh that people complain that LLMs only learn what it’s is in training data. And then the other guy says, “Then we’ll put everything into training data.” So, we had these operations, Python operations. So, increment, double, even. Um these are just some Python tasks and
[39:42] it improved on these. And now, interestingly, it didn’t improve on this one. I don’t know why. I need to maybe check it. So, so here, maybe it’s a bug in my code or bug that AI generated or bug in my experiment or something. Or if it’s not a bug, then it’s even more interesting, but it’s probably a bug. And then ones that it didn’t train on, it uh didn’t improve. It may even have regressed. Now, depending on how we calculated the statistical significance, you need to always be careful.
[40:13] Did it actually regress? Do you have enough samples? Did you calculate it properly, they do sample maybe multiple times to see the average around different uh percentages. So, two previously strong families regressed because only a narrow parameter surface was optimized for the practice reward distribution. But, it did improve in the things we trained it based on our environment. And this means that you can teach it whatever you want to teach it and know
[40:44] how to construct environments. So, when experimenting, you want to change just one variable at a time. So, let’s say you have all of these different variables like reward, uh how you’re rewarding, the group size, how many uh answers you are generating at once, for example, eight per prompt, temperature is randomness or penalty, negative rewards. So, you want to adjust if you’re doing research, you want to do one uh experiment, one variable per time.
[41:14] Here, I did a bunch of different experiments. You see, if I set, for example, group size four, it performs very well, better than group size 16. Then, temperature 0.2 is uh more deterministic, less random, performs better than more random temperature. And then, uh here in these experiments about reward binary like uh 0 1 or other partial rewards or no invalid penalty, hard invalid penalty, they all perform same on my data set. Now,
[41:44] you don’t want to just have five, you want to have like 500 or 5,000 of these to get uh better insights. But, check out this horror. You see, group size four won over group size eight on this seed, but lost on this seed and lost on this seed. Okay, so this is This means that, first of all, this doesn’t have much influence based on my setup, my training data. Secondly, we Yeah, we need to train more to see actual statistical significance.
[42:16] Um and then also it could be that it’s not so important. But, if you are training huge models, then even small differences could mean a lot of money saved. Your model is training a bit faster, which is going to save a lot of money. So, this is why when people are reviewing your papers, they will tell you to test on three seeds. And all three seeds should have a clear conclusion. Like, all three seeds it should say that group four is better than group eight.
[42:46] So, none of my experiments produced statistically significant improvements. Maybe my experiments are very small. Maybe as you probably as you train bigger models, you’re going to have uh clearer and clearer exact setup of parameters that’s going to be best. And here we can review each part. So, pre-training is going to teach it to write Python. Revision is going to teach it to add recognize images into the transformer into the language model. And
[43:16] reinforcement learning will in our case improve the increment and double operations. So, I encourage you to just go talk to Codex or Cloud Code. You can tell it, “Which kind of experiments can I do here?” And don’t be so concerned about scaling. I just want you to learn how to do some experiments, how to learn scientific thinking, how to measure properly, how to conclude properly. So, you can post your experiments on social media as well. If you want to become AI researcher, I recommend you just keep posting your experiments every day or
[43:48] every week on social media. Consistency is more important than intensity. So, if you post five days in a row, but then you stop, it’s not good. If you post once a week forever, it’s a lot better. And it’s better to just do experiments and train a model for a few seconds. You don’t want to wait a few minutes, a few hours because it’s wasted time. You need to be thinking how to need to be practicing how to design experiments, environments, questions. You don’t need to wait for
[44:18] the model because you cannot train the model that’s going to outcompete these companies that people are going to use.