Encontro 1

Engenharia de software e documentação

A program is like a poem: you cannot write a poem without writing it.

Dijkstra

AGENDA

Sprint 1

Arquitetura do sistema

ENCONTROS

Encontro 1

  • Engenharia de software
  • Documentação

Encontro 2

  • Requisitos
  • Design patterns

ENCONTRO 3

  • ROS
  • Turtlebot

Engenharia de software

Coesão, acoplamento, inversão e injeção de dependência

Coesão

Coesão

ACOPLAMENTO

INJEção de DEPENDência

INVERSão de DEPENDência

INVERSão de DEPENDência

GIT

Como não destruir seu repositório com PRs

I named Linux after myself. It's only natural that I did the same with Git.

Linus Torvalds

GIT PULL

Retirado de fonte

GIT REBASE

Retirado de fonte

Encontro 2

Design patterns e requisitos de software

Insanity is doing the exact same fucking thing over and over again, expecting shit to change.

Vaas Montenegro

AGENDA

Design Patterns

Motivações e exemplos

Motivações

Coesão

Acoplamento

Reutilização

+

Escalabilidade

+

strategy pattern

Retirado de fonte

Strategy pattern

Strategy Pattern

Inversão de dependência

Observer pattern

Retirado de fonte

Observer pattern

Retirado de fonte

Observer pattern

Observer pattern

Onde mais tem observer?

Observer no ros

...E o singleton?

...E o singleton?

class ROSMaster:
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super(ROSMaster, cls).__new__(cls)
            cls._instance.publishers = {}
        return cls._instance

    def register_publisher(self, topic_name, publisher):
        self.publishers[topic_name] = publisher

    def subscribe(self, subscriber, topic_name):
        publisher = self.publishers.get(topic_name)
        if publisher:
            publisher.add_subscriber(subscriber)

# Testando o Singleton:

master1 = ROSMaster()
master2 = ROSMaster()

# Deve retornar True, já que ambos devem ser a mesma instância
print(master1 == master2)  

Vamos praticar

Exercício

Crie um script em Python capaz de ler as notas de alunos e calcular a média para cada um deles. O programa deve ser capaz de ler as notas tanto de um arquivo csv quanto de um arquivo yml. A sua saíde pode ser tanto uma atualização do arquivo csv/yml quanto por stdout (terminal). Exemplo:

./gera-notas.py -i notas.csv -o notas.yml

>> Arquivo atualizado com sucesso

./gera-notas.py -i notas.yml

Betinho: 5.5
Elisa: 7.5
João: 8.5

Dicas: bibliotecas pyyaml, csv, argparse

Rnfs

Como criá-los? Como medí-los

Atividade ponderada 1

Encontro 3

Revisão de ROS e Quatérnios

Quaternions came from Hamilton after his really good work had been done, and though beautifully ingenious, have been an unmixed evil to those who have touched them in any way.

Lord Kelvin

AGENDA

Revisão ROS

Nós e tópicos. Publishers e subscribers

Nós

tópicos

Exercício 1 - rodando o turtlesim

Use o pacote turtlesim para rodar um nó de simulação e outro de teleoperação.

RQT

rqt_graph

subscribers

Exercício 2 - lendo a pose do turtlesim

Crie um subscriber simples capaz de consumir informações do tópico de pose do turtlesim e exibir no terminal.

PUBLISHERS

Exercício 3 - comandando o turtlesim

Crie um publisher capaz de publicar mensagens no tópico que rege a movimentação do turtlesim.

pacotes e launch files

A forma mais simples de se trabalhar com projetos em ROS

Exercício 3 - pacotes e launchfiles

Utilizando o tutorial fornecido no material auxiliar, transforme os dois scripts feitos anteriormente em um pacote e crie um launchfile para rodá-los ao mesmo tempo (o launchfile deve fazer parte do pacote).

ROS em rede

ROS_DOMAIN_ID e Tchau, brigado pro WSL!

Configuração

export ROS_DOMAIN_ID=<valor>

#Valores seguros: 0-101 e 215-232

Exercício 4 - MExendo no turtlesim do coleguinha

Em duplas ou trios, criem um script capaz de fazer um desenho. Configurem para que o ROS_DOMAIN_ID seja o mesmo e alternem entre um fazer um desenho no turtlesim do outro.

quaternions

Pure evil

Por quê? 😫

Retirado de fonte

Cinemática inversa

Retirado de fonte

Cinemática inversa - singularidade

Encontro 4

Gazebo e nav2

...and yet though I know beforehand that he won’t, I set off to him. Why? Well, when one has no one, nowhere else one can go! For every man must have somewhere to go. Since there are times when one absolutely must go somewhere!

Marmeladov (Crime and Punishment)

AGENDA

Serviços ros

Server - Client

serviços

Retirado de fonte

ações ros

Dois serviços e um tópico

ações

Retirado de fonte

NAV2/SLAM

Mapeando e navegando

Diagrama de blocos

Retirado de fonte

ações NAV2

Retirado de fonte

Exercício 1 - Instalando e rodando o gazebo

Execute o lançador do turtlebot_world e mova o robô no mundo simulado com o turtlebot_teleop.

ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
ros2 run turtlebot3_teleop teleop_keyboard

Exercício 2 - mapeando o mundo simulado

Usando o turtlebot cartographer, mapeie o mundo do turtlebot3. Para isso, use o teleop para mover-se pelo mapa enquanto mapeia.

ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
ros2 launch turtlebot3_cartographer cartographer.launch.py use_sim_time:=True 
ros2 run turtlebot3_teleop teleop_keyboard
ros2 run nav2_map_saver map_saver_cli -f <nome-do-mapa>

Exercício 2 - mapeando o mundo simulado

Exercício 3 - navegação no gazebo

Agora que já temos um mapa, vamos carregá-lo e navegar usando o Rviz + nav2

ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml

Exercício 4 - Simple commander

Vamos agora fazer tudo isso, só que programáticamente?

ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml

Encontro 5

Webots e chatbot simples

Chatbots baseados em regras são como papagaios tecnológicos, repetem o que é programado, mas não entendem o bate-papo. Eu, por outro lado, sou mais como um romancista em uma mesa de bar, criando histórias com cada palavra digitada. Eles seguem o script, eu jogo xadrez com as palavras.

Gepeto, Chat

AGENDA

Webots + nav2

Tchau, brigado gazebo

Exercício 1 - Instalando e rodando

Exercício 2 - webots com nav2

regex

/^.*regex.*:\)$/

chatbot simples

Dois dicionários e muito regex

Exercício 3 - Chatbotzin?

Exercício 2 - mapeando o mundo simulado

Exercício 3 - navegação no gazebo

Agora que já temos um mapa, vamos carregá-lo e navegar usando o Rviz + nav2

ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml

Exercício 4 - Simple commander

Vamos agora fazer tudo isso, só que programáticamente?

ros2 launch turtlebot3_gazebo turtlebot3_world_launch.py
# Substitua o arquivo-do-mapa pelo local onde está o seu mapa
ros2 launch turtlebot3_navigation2 navigation2.launch.py use_sim_time:=True
map:=<arquivo-do-mapa>.yaml

Encontro 7

Langchain pt 2, LCEL, RAG

Sou o milhor. Posso não ser o milhor, mas na minha cabeça sou o milhor

Chat CR7

AGENDA

langchain

Quanto overengineering vocês querem?
- Sim

LANGCHAIN

Retirado de fonte

Prompt template

from langchain.prompts import PromptTemplate

prompt_template = PromptTemplate.from_template(
    "Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")

LCEL

Conciso, mas com 500 abstrações para cada coisinha

LCEL

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

model = ChatOpenAI(model="gpt-3.5-turbo")
prompt = ChatPromptTemplate.from_template(
"""
You are now my personal travel agent. Act as someone who has immense travel
experience and knows the best places in the world to do certain activities. I
want to know where I should go to {activity}. Give the answers as a list of
items, no bigger than 5 items. For each item, create a simple sentence
justifying this choice.
"""
)

chain = prompt | model

for s in chain.stream({"activity": "eat live fish"}):
    print(s.content, end="", flush=True)

Exercício 1 - 15 min

Vamos implementar uma cadeia simples?

RAG

Como evitar que um LLM alucine?

RAG

Retirado de fonte

load

Retirado de fonte

transform

Retirado de fonte

eMBED

Retirado de fonte

store

Retirado de fonte

RETRIEVE

Retirado de fonte

RETRIEVE

Retirado de fonte

Aplicação

from langchain.chat_models import ChatOpenAI
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnableLambda, RunnablePassthrough
from langchain.vectorstores import FAISS

vectorstore = FAISS.from_texts(
    ["Bread - (0.0, 1.0, 2.0)\nMilk - (1.0, 2.0, 0.0)"], 
    embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()

template = """Answer the question based only on the following context:
{context}

Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)

model = ChatOpenAI(model="gpt-3.5-turbo")

chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | model
)

for s in chain.stream("Where is the bread?"):
    print(s.content, end="", flush=True)

Exercício 2 - 30 min

Bora de RAG? Baixem o arquivo texto aqui

Encontro 8

Introdução à redes neurais

AI winters were not due to imagination traps, but due to lack of imaginations. Imaginations bring order out of chaos. Deep learning with deep imagination is the road map to AI springs and AI autumns.

Amit Ray

AGENDA

O problema com perceptrons

o perceptron

o perceptron

class Perceptron:
    def __init__(self, weights, threshold):
        self.weights = np.array(weights)
        self.threshold = threshold
        self.bias = 0

    def activation_function(self, x):
        return 1 if x >= self.threshold else 0

    def predict(self, inputs):
        # Calcula a soma ponderada das entradas
        linear_output = np.dot(inputs, self.weights) + self.bias
        # Aplica a função degrau para determinar a saída
        y_predicted = self.activation_function(linear_output)
        return y_predicted

Exercício 1 - 20 min

Vamos implementar um perceptron? Do livro "Neural networks and deep learning":

Suppose the weekend is coming up, and you've heard that there's going to be a cheese festival in your city. You like cheese, and are trying to decide whether or not to go to the festival. You might make your decision by weighing up three factors:

  1. Is the weather good?
  2. Does your boyfriend or girlfriend want to accompany you?
  3. Is the festival near public transit? (You don't own a car).

We can represent these three factors by corresponding binary variables x1,x2, and x3. For instance, we'd have x1=1 if the weather is good, and x1=0 if the weather is bad. Similarly, x2=1 if your boyfriend or girlfriend wants to go, and x2=0 if not. And similarly again for x3 and public transit.

funções de ativação

bias

Exercício 2 - 40 min (ponderada 6)

Vamos fazer o perceptron aprender? Crie um método de treinamento e, usando-o, faça com que o perceptron aprenda a reproduzir o comportamento das seguintes portas lógicas:

  • AND
  •  
  • OR
  •  
  • NAND
  •  
  • XOR

 

Multilayer PErceptron

Forward propagation

duas perguntas

  1. Como definir o custo de um erro?
  2. Se eu tiver camadas intermediárias, como eu correlaciono esse erro com os pesos?

Gradiente descendente

Retropropagação

forward propagation

Retropropagação

Encontro 9

Redes neurais convolucionais

You've got it from here.

Nanamin

AGENDA

MLP

Tensorflow e Keras

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense

x = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([[0], [1], [1], [0]])

# Creating the MLP model
model = Sequential()
model.add(Dense(4, input_dim=2, activation='relu'))  # First hidden layer
model.add(Dense(1, activation='sigmoid'))            # Output layer

# Compile the model
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])

# Train the model
model.fit(x, y, epochs=10, batch_size=1)

Exercício 1 - 20 min

MLP c/ Keras

Convoluções

Convoluções como filtros

redes neurais convolucionais

Exercício 2 - 40 min

Ponderada 7 - Classificação MNIST utilizando redes neurais convolucionais.

arquitetura yolo

Encontro 10

Ferramentas TTS e STT

Honored bun

AGENDA

whisper

encoder decoder

Exercício 1 - 15 min

Utilizando o whisper, crie um programa simples que transcreva um arquivo de áudio contendo uma frase e exiba-o no terminal

pip install -U openai-whisper

bark

🐶

outros modelos tts

Exercício 2 - 15 min

Utilizando o JETS TTS, crie um script que receba um input do usuário e converta-o em áudio

pip install txtai[pipeline-audio] 
pip install soundfile

Exercício 3 - resto do encontro

Ponderada 8 - Criando o seu próprio tradutor

  1. UI - 1,0 ponto
  2. TTS - 3,0 pontos
  3. Tradução - 3,0 pontos
  4. STT - 3,0 pontos

Encontro 11

Redes neurais recorrentes

Aoi Todo (GOAT)

AGENDA

O perceptron

Multi-layer perceptron

Feedforward

foreshadowing

redes neurais convolucionais

dados sequenciais

redes neurais recorrentes

vanishing/exploding gradient

vanishing/exploding gradient

LSTM

LSTM - Forget gate

LSTM - input gate

LSTM - output gate

tipos de redes recorrentes

ponderada 9

Utilizando LSTM para gerar músicas.

Encontro 12

Encoder-Decoder Transformer

You're right, [REDACTED]. I'm you. I wanted to reject you, convince myself that you were wrong. But that doesn't matter now. I'm gonna kill you. Even if you come back as another curse, I'll kill you. Change your name. Change your form. I'll kill you again. I don't need to find meaning or a reason. Maybe in a hundred years after my death, the meaning behind my actions will become apparent. In the grand scheme of things... I'm probably nothing more than a cog.

HIMtadori, Yuji

AGENDA

RNN

lstm

forget gate

input gate

output gate

tipos de uso - rnn

o problema do chatbot

comparando palavras

vector embeddings

seq2seq

Gyobu Masataka Oniwa

componentes

encoder

encoder/decoder

encoder/decoder

Vetor de contexto

Tokens

o problema do encoder/decoder

atenção!!

atenção!!

atenção!!

softmax

atenção!!

atenção!!

Ficou perfeito agora??

attention is all you need...

interlúdio

transformers

codificação posicional

Auto Atenção

query key value

encoder

atenção encoder/decoder

encoder/decoder

gpt (decoder only)

google gemini

nos vemos no módulo 9...

Encontro 13

Fabricação digital

[Jensen] sent out an email on Friday evening saying everything is going to deep learning, and that we were no longer a graphics company. By Monday morning, we were an AI company. Literally, it was that fast.

Greg Estes (VP Marketing - NVidia)

The “classical stack” of Software 1.0 is what we’re all familiar with — it consists of explicit instructions to the computer written by a programmer. In contrast, Software 2.0 is written in much more abstract, human unfriendly language, such as the weights of a neural network.

Andrej Karpathy (Tesla, OpenAI)

Made with Slides.com