Esta seção é atualizada automaticamente a cada 24 horas pela nossa pipeline de GitHub Actions, consumindo a própria API deste projeto.
Prompt: "Qual é uma reflexão interessante sobre a intersecção entre tecnologia e finanças?"
Resposta da IA: Aguardando a primeira execução da pipeline para gerar um insight...
Este projeto implementa um serviço de geração de texto utilizando o modelo pré-treinado DistilGPT2. Ele é projetado com práticas de MLOps em mente, oferecendo uma API web construída com Flask, containerizada com Docker, e validada por uma pipeline de Integração Contínua (CI) com testes automatizados.
- Geração de Texto: Utiliza o Modelo base: DistilGPT2 (leve, otimizado para CPU e ambientes com baixa memória, como Render Free Tier) para gerar texto com base em um prompt.
- API Web com Flask: Oferece um endpoint
/generate(via POST) para interação com o modelo. - Containerização com Docker: Permite empacotamento e implantação consistentes.
- Testes Automatizados: Inclui testes unitários e de integração com
pytestpara garantir a qualidade e a robustez da API. - Integração Contínua (CI): Utiliza GitHub Actions para rodar os testes automaticamente a cada alteração no código.
- Implantação Serverless (Opcional): Fornece um handler para implantar a funcionalidade como uma função AWS Lambda.
- Python 3.8+
- Flask
- Hugging Face Transformers
- Docker
- Pytest (para testes)
- GitHub Actions (para CI/CD)
- AWS Lambda / Boto3
- Python 3.8 ou superior
- Docker instalado
- Construa a imagem Docker:
docker build -t gpt2-text-generator . - Execute o container Docker:
A API estará acessível em
docker run -p 5000:5000 gpt2-text-generator
http://localhost:5000.
Envie uma requisição POST para http://localhost:5000/generate.
Exemplo com curl:
curl -X POST -H "Content-Type: application/json" \
-d '{"prompt": "A inteligência artificial está transformando o mundo"}' \
http://localhost:5000/generateEnglish 🇬🇧
- Description
This project implements a text generation service using the pre-trained DistilGPT2 model. It is designed with MLOps practices in mind, offering a web API built with Flask, containerized with Docker, and validated by a Continuous Integration (CI) pipeline with automated tests.
-
Key Features
-
Text Generation: Uses the DistilGPT2 model to generate text based on a user-provided prompt.
-
Flask Web API: Provides a /generate endpoint (via POST) for model interaction.
-
Docker Containerization: Allows for consistent packaging and deployment.
-
Automated Testing: Includes unit and integration tests with pytest to ensure API quality and robustness.
-
Continuous Integration (CI): Uses GitHub Actions to automatically run tests on every code change.
-
Serverless Deployment (Optional): Provides a handler to deploy the functionality as an AWS Lambda function.
-
-
Technologies Used
-
Python 3.8+
-
Flask
-
Hugging Face Transformers
-
-
Docker
-
Pytest (for testing)
-
GitHub Actions (for CI/CD)
-
AWS Lambda / Boto3
-
-
Python 3.8 or higher
-
Docker installed
- Build the Docker image:
docker build -t gpt2-text-generator .
Run the Docker container:docker run -p 5000:5000 gpt2-text-generator
The API will be accessible at http://localhost:5000.
Using the API
Send a POST request to http://localhost:5000/generate.
Example using curl:curl -X POST -H "Content-Type: application/json" \
-d '{"prompt": "Artificial intelligence is transforming the world"}' \
http://localhost:5000/generateO coração deste serviço está no arquivo app.py. O fluxo de operação é o seguinte:
- Inicialização: Ao iniciar a aplicação, o modelo pré-treinado
DistilGPT2e seuTokenizersão carregados do Hub da Hugging Face e mantidos em memória. Isso otimiza o desempenho, evitando recargas a cada requisição. - Endpoint
/generate: Um endpointPOSTestá disponível para receber as solicitações. - Processamento da Requisição:
- O
promptde texto é extraído do payload JSON da requisição. - O
Tokenizerconverte o texto do prompt em um Tensor PyTorch (encode). - O
model.generate()realiza a inferência, utilizando o tensor como entrada para gerar uma nova sequência de tokens. - O
Tokenizerentão decodifica (decode) a sequência de tokens de volta para um texto legível.
- O
- Resposta: O texto gerado é retornado ao cliente em um objeto JSON.
The core of this service resides in the app.py file. The operational flow is as follows:
- Initialization: When the application starts, the pre-trained
DistilGPT2model and itsTokenizerare loaded from the Hugging Face Hub and kept in memory. This optimizes performance by avoiding reloads on every request. /generateEndpoint: APOSTendpoint is available to receive requests.- Request Processing:
- The text
promptis extracted from the request's JSON payload. - The
Tokenizerconverts the prompt text into a PyTorch Tensor (encode). - The
model.generate()method performs the inference, using the tensor as input to generate a new sequence of tokens. - The
Tokenizerthen decodes (decode) the token sequence back into a human-readable string.
- The text
- Response: The generated text is returned to the client within a JSON object.
- 2.1. Alternativas de Modelos e Tokenizers Gratuitos O ecossistema de modelos de código aberto é vasto. Então, o DistilGPT2 é um excelente ponto de partida, mas existem alternativas mais modernas e/ou eficientes. Todas estão disponíveis no Hugging Face Hub.
Modelo Vantagens Desvantagens Classe Principal (Exemplo)
-
DistilGPT2 Versão "destilada" do DistilGPT2. Muito mais leve e rápido, ideal para prototipagem e ambientes com menos recursos. Menos poderoso/criativo que o DistilGPT2 base.
-
GPT2LMHeadModel -
GPT-Neo/ GPT-J Criados pela EleutherAI como alternativas open-source ao GPT-3. Significativamente mais poderosos que o DistilGPT2. Maiores e mais lentos, exigem mais VRAM. -
GPTNeoForCausalLM -
BLOOMModelo multilíngue massivo. Ótimo para tarefas em idiomas além do inglês. Muito grande e pesado para uso casual. BloomForCausalLM -
Mistral-7BUm dos modelos mais populares atualmente. Desempenho comparável a modelos muito maiores. Excelente balanço entre performance e tamanho. Requer a biblioteca accelerate. MistralForCausalLM -
Para usar qualquer um deles, você normalmente mudaria
model_namee a classe do modelo no seuapp.py. Frequentemente, pode-se usar a classeAutoModelForCausalLMque carrega a arquitetura correta automaticamente.
2.2. Aprofundamento Técnico: Como o GPT2LMHeadModel Funciona
O GPT2LMHeadModel é mais do que apenas uma caixa preta. Seu funcionamento é baseado em três pilares:
Arquitetura Transformer: DistilGPT2 é baseado na arquitetura "Transformer", que revolucionou o PLN. Seu componente principal é o mecanismo de auto-atenção (self-attention). Ele permite que o modelo, ao processar uma palavra, "preste atenção" e pese a importância de todas as outras palavras na sequência de entrada. Isso o torna extremamente eficaz em capturar o contexto de longo prazo em um texto.
Treinamento (Causal Language Modeling): O DistilGPT2 foi pré-treinado em um volume gigantesco de texto da internet com um objetivo simples: prever a próxima palavra. Ele recebe um trecho de texto (ex: "A melhor parte de programar é") e seu objetivo é prever a palavra mais provável a seguir ("o"). Ele faz isso milhões de vezes, ajustando seus parâmetros internos para ficar cada vez melhor em entender a estrutura, gramática, fatos e até mesmo os estilos da linguagem humana.
A "Cabeça" (Language Model Head): A classe GPT2LMHeadModel indica que sobre a arquitetura Transformer base, existe uma "cabeça de modelagem de linguagem". Esta é uma camada final, geralmente uma camada linear seguida por uma função softmax, que pega as representações numéricas complexas geradas pelo Transformer e as converte em uma distribuição de probabilidade sobre todo o vocabulário do modelo. Ou seja, para a próxima palavra, ela atribui uma pontuação de probabilidade a cada palavra possível (ex: "o": 30%, "a": 15%, "resolver": 5%, etc.)`. A função model.generate usa essa distribuição para selecionar a próxima palavra de forma inteligente, continuando o processo de forma autorregressiva (a palavra gerada é adicionada ao final da sequência, que é então usada como nova entrada para gerar a próxima palavra).
The core of this service resides in the app.py file. The operational flow is as follows:
- Initialization: When the application starts, the pre-trained
DistilGPT2model and itsTokenizerare loaded from the Hugging Face Hub and kept in memory. This optimizes performance by avoiding reloads on every request. /generateEndpoint: APOSTendpoint is available to receive requests.- Request Processing:
- The text
promptis extracted from the request's JSON payload. - The
Tokenizerconverts the prompt text into a PyTorch Tensor (encode). - The
model.generate()method performs the inference, using the tensor as input to generate a new sequence of tokens. - The
Tokenizerthen decodes (decode) the token sequence back into a human-readable string.
- The text
- Response: The generated text is returned to the client within a JSON object.
The open-source model ecosystem is vast. DistilGPT2 is an excellent starting point, but more modern and/or efficient alternatives exist. All are available on the Hugging Face Hub.
| Model | Advantages | Disadvantages | Main Class (Example) |
|---|---|---|---|
| DistilGPT2 | A "distilled" version of DistilGPT2. Much lighter and faster, ideal for prototyping and resource-constrained environments. | Less powerful/creative than the base DistilGPT2. | GPT2LMHeadModel |
| GPT-Neo / GPT-J | Created by EleutherAI as open-source alternatives to GPT-3. Significantly more powerful than DistilGPT2. | Larger and slower, require more VRAM. | GPTNeoForCausalLM |
| BLOOM | Massive multilingual model. Great for tasks in languages other than English. | Very large and heavy for casual use. | BloomForCausalLM |
| Mistral-7B | One of the most popular models today. Performance is comparable to much larger models. Excellent balance between performance and size. | Requires the accelerate library. |
MistralForCausalLM |
To use any of them, you would typically change the model_name and the model class in your app.py. Often, you can use the AutoModelForCausalLM class, which automatically loads the correct architecture.
The GPT2LMHeadModel is more than just a black box. Its operation is based on three pillars:
-
Transformer Architecture: DistilGPT2 is based on the "Transformer" architecture, which revolutionized NLP. Its main component is the self-attention mechanism. It allows the model, when processing a word, to "pay attention" to and weigh the importance of all other words in the input sequence. This makes it extremely effective at capturing long-term context in a text.
-
Training (Causal Language Modeling): DistilGPT2 was pre-trained on a gigantic volume of text from the internet with a simple objective: to predict the next word. It receives a piece of text (e.g., "The best part of programming is") and its goal is to predict the most likely next word ("the"). It does this millions of times, adjusting its internal parameters to become increasingly better at understanding the structure, grammar, facts, and even the styles of human language.
-
The "Head" (Language Model Head): The
GPT2LMHeadModelclass indicates that on top of the base Transformer architecture, there is a "language modeling head." This is a final layer, usually a linear layer followed by a softmax function, which takes the complex numerical representations generated by the Transformer and converts them into a probability distribution over the model's entire vocabulary. In other words, for the next word, it assigns a probability score to every possible word (e.g., "the": 30%, "a": 15%, "solving": 5%, etc.). Themodel.generatefunction uses this distribution to intelligently select the next word, continuing the process autoregressively (the generated word is added to the end of the sequence, which is then used as the new input to generate the next word).
Jefferson Firmino Mendes Consultor em Inteligência Financeira e Análise de Dados
📱 WhatsApp: (83) 99625-8911
📧 Email: jefferson.ds.consultoria@gmail.com
🌐 Website: jfnegociospro.wixsite.com/consultoria
Jefferson Firmino Mendes Financial Intelligence and Data Analysis Consultant
📱 WhatsApp: (83) 99625-8911
📧 Email: jefferson.ds.consultoria@gmail.com
🌐 Website: jfnegociospro.wixsite.com/consultoria