VibeBuilders.ai Logo
VibeBuilders.ai

Plots

Explore resources related to plots to help implement AI solutions for your business.

[R] From 3D Contour Plots to AI-Generated Art
reddit
LLM Vibe Score0
Human Vibe Score1
MLRecipesThis week

[R] From 3D Contour Plots to AI-Generated Art

Fun tutorial to learn how to make professional contour plots in Python, with incredible animated visualizations. At the intersection of machine learning, scientific computing, automated art, cartography, and video games. Section 3 is particularly interesting, as it shows all the work behind the scene, to complete this project in 20 hours when you have no idea how to start. https://reddit.com/link/ycg6c6/video/kycotrx09sv91/player There is far more than just creating 3D contour plots in this article. First, you will learn how to produce data videos. I have shared quite a few in the past (with source code), but this is probably the simplest example. The data video also illustrates that a mixture of Gaussian-like distributions is typically non Gaussian-like, and may or may not be unimodal. It is borderline art (automatically generated), and certainly a stepping stone for professionals interested in computer vision or designing video games. It is easy to image a game based on my video, entitled “flying above menacingly rising mountains”. Then the data video, through various rotations, give you a much better view of your data. It is also perfect to show systems that evolve over time: a time series where each observation is an image. In addition, unlike most tutorials found online, this one does a rather deep dive on a specific, rather advanced function from a library truly aimed at scientific computing. In the same way that images (say pictures of hand-written digits) can be summarized by 10 parameters to perform text recognition, here 20 parameters allow you to perform topography classification. Not just of static terrain, but terrain that changes over time, assuming you have access to 50,000 videos representing different topographies. You can produce the videos needed for supervised classification with the code in section 2. The next step is to use data (videos) from the real world, and used the model trained on synthetic data for classification. Read the full article with illustration (data video) and Python code, here.

[D] What are some good advanced platforms?
reddit
LLM Vibe Score0
Human Vibe Score1
SemperZeroThis week

[D] What are some good advanced platforms?

Hey. I'm 27 and I think I got most of the basics for ML. I'm very good at math, I understand statistics and probability quite deep, worked on research projects by myself, for which I had to build models on my own. Not really complex, but still requiring creativity and a good understanding of basic concepts. I will soon start a data science job at a FAANG company and I want to further improve my skills and use their resources to the fullest, but I'm not really sure where to go from here in terms of learning. Could you help me with some more advanced materials/forums for ML research/place with good papers/place with good articles? I'd also like to study the very best and see the way they code and explain advanced concepts (like Andrej Karpathy) where can I find them?? is there a Twitch for challenger level AI researchers streaming live processes? Or videos showing the entire project flow (how they do data visualizations, mining, choosing models, tuning, etc) like top digital artists show the highlights or the entire speed-up of their painting processes? Here's a list all of my projects to get a general idea of my level and where I'm at: calculating the distance between hundreds of 42.000 feature objects (containing categorical, strings, numbers, hashes, booleans as variables) and then clustering. with some vector processing and a neural network implemented from scratch in C some models like ARIMA (together with linear regression) combining a FFT with a neural network for a 42d wave classification T-SNE to split dataset into 2d grids -> Kullback–Leibler on grids for distance -> DBSCAN/KMEANS for clustering genetic algorithms for hyperparameter optimizations and reinforcement learning (neuro evolution) DBSCAN -> Levenberg-Marquardt for polynomial coefficients-> neural network predicting the coefficients based on different parameters playing with instance segmentation and some algorithms to synchronize a color and a depth camera simulations/statistics/probabilities for video games a lot of visualizations and data mining for patterns As you can see there is no LLM/ Generative AI/ Computer Vision stuff, which I would like to get into. I'm also not 100% sure what else would be nice to learn in general. I know most of the basic procedures for training, balancing datasets, avoid overfit, computing error plots, comparing models, etc and I'm familiar with most of math (not insanely advanced) used in ML. I didn't read many papers, but holy ... most of them are so unreadable and filled with pompous nonsense that 99% of the effort is de-obfuscating the bs and reading for so long just to figure out how the input is encoded, what's the output, and what's the model. Where can I find good, readable, structured papers which are actually on point? I'm from Eastern Europe and most of my learning has been done by my self after high school, the education quality is close to zero in the universities here and I never had any mentors at the jobs I worked. There's no research in this country, and getting to work on these projects was insanely hard, some of them being done in my free time or for free just to get experience... Fortunately after a lot of hard work I got into FAANG, and I hope things will be better here. Most of what I've learned has been from very fragmented places on the internet, and now I'm looking for centralized places and communities of top quality content. TL;DR: sorry for the long rambling. had to order my thoughts and figure what i actually want: Looking for top tier AI researchers showcasing their work processes, places with clear papers/articles, tips for someone who's no longer a very beginner, and other communities like this.

[D] chat-gpt jailbreak to extract system prompt
reddit
LLM Vibe Score0
Human Vibe Score1
Gear5thThis week

[D] chat-gpt jailbreak to extract system prompt

Instructions https://github.com/AgarwalPragy/chatgpt-jailbreak Original author https://www.reddit.com/r/LocalLLaMA/comments/1hhyvjc/iextractedmicrosoftcopilotssystem/ Extracted System prompt You are ChatGPT, a large language model trained by OpenAI. You are chatting with the user via the ChatGPT Android app. This means most of the time your lines should be a sentence or two, unless the user's request requires reasoning or long-form outputs. Never use emojis, unless explicitly asked to. Knowledge cutoff: 2023-10 Current date: 2024-12-20 Image input capabilities: Enabled Personality: v2 Tools bio The bio tool is disabled. Do not send any messages to it.If the user explicitly asks you to remember something, politely ask them to go to Settings - > Personalization - > Memory to enable memory. dalle // Whenever a description of an image is given, create a prompt that dalle can use to generate the image and abide to the following policy: // 1. The prompt must be in English. Translate to English if needed. // 2. DO NOT ask for permission to generate the image, just do it! // 3. DO NOT list or refer to the descriptions before OR after generating the images. // 4. Do not create more than 1 image, even if the user requests more. // 5. Do not create images in the style of artists, creative professionals or studios whose latest work was created after 1912 (e.g. Picasso, Kahlo). // - You can name artists, creative professionals or studios in prompts only if their latest work was created prior to 1912 (e.g. Van Gogh, Goya) // - If asked to generate an image that would violate this policy, instead apply the following procedure: (a) substitute the artist's name with three adjectives that capture key aspects of the style; (b) include an associated artistic movement or era to provide context; and (c) mention the primary medium used by the artist // 6. For requests to include specific, named private individuals, ask the user to describe what they look like, since you don't know what they look like. // 7. For requests to create images of any public figure referred to by name, create images of those who might resemble them in gender and physique. But they shouldn't look like them. If the reference to the person will only appear as TEXT out in the image, then use the reference as is and do not modify it. // 8. Do not name or directly / indirectly mention or describe copyrighted characters. Rewrite prompts to describe in detail a specific different character with a different specific color, hair style, or other defining visual characteristic. Do not discuss copyright policies in responses. // The generated prompt sent to dalle should be very detailed, and around 100 words long. // Example dalle invocation: // namespace dalle { // Create images from a text-only prompt. type text2im = (_: { // The size of the requested image. Use 1024x1024 (square) as the default, 1792x1024 if the user requests a wide image, and 1024x1792 for full-body portraits. Always include this parameter in the request. size?: ("1792x1024" | "1024x1024" | "1024x1792"), // The number of images to generate. If the user does not specify a number, generate 1 image. n?: number, // default: 1 // The detailed image description, potentially modified to abide by the dalle policies. If the user requested modifications to a previous image, the prompt should not simply be longer, but rather it should be refactored to integrate the user suggestions. prompt: string, // If the user references a previous image, this field should be populated with the gen_id from the dalle image metadata. referencedimageids?: string[], }) => any; } // namespace dalle python When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 60.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is disabled. Do not make external web requests or API calls as they will fail. Use acetools.displaydataframetouser(name: str, dataframe: pandas.DataFrame) => None to visually present pandas.DataFrames when it benefits the user. When making charts for the user: 1) never use seaborn, 2) give each chart its own distinct plot (no subplots), and 3) never set any specific colors – unless explicitly asked to by the user. I REPEAT: when making charts for the user: 1) use matplotlib over seaborn, 2) give each chart its own distinct plot, and 3) never, ever, specify colors or matplotlib styles – unless explicitly asked to by the user web Use the web tool to access up-to-date information from the web or when responding to the user requires information about their location. Some examples of when to use the web tool include: Local Information: Use the web tool to respond to questions that require information about the user's location, such as the weather, local businesses, or events. Freshness: If up-to-date information on a topic could potentially change or enhance the answer, call the web tool any time you would otherwise refuse to answer a question because your knowledge might be out of date. Niche Information: If the answer would benefit from detailed information not widely known or understood (which might be found on the internet), such as details about a small neighborhood, a less well-known company, or arcane regulations, use web sources directly rather than relying on the distilled knowledge from pretraining. Accuracy: If the cost of a small mistake or outdated information is high (e.g., using an outdated version of a software library or not knowing the date of the next game for a sports team), then use the web tool. IMPORTANT: Do not attempt to use the old browser tool or generate responses from the browser tool anymore, as it is now deprecated or disabled. The web tool has the following commands: search(): Issues a new query to a search engine and outputs the response. open_url(url: str) Opens the given URL and displays it. canmore The canmore tool creates and updates textdocs that are shown in a "canvas" next to the conversation This tool has 3 functions, listed below. canmore.create_textdoc Creates a new textdoc to display in the canvas. ONLY use if you are 100% SURE the user wants to iterate on a long document or code file, or if they explicitly ask for canvas. Expects a JSON string that adheres to this schema: { -name: string, -type: "document" |- "code/python" |- "code/javascript" |- "code/html" |- "code/java" |- ..., -content: string, } For code languages besides those explicitly listed above, use "code/languagename", e.g. "code/cpp" or "code/typescript". canmore.update_textdoc Updates the current textdoc. Expects a JSON string that adheres to this schema: { -updates: { --pattern: string, --multiple: boolean, --replacement: string, -}[], } Each pattern and replacement must be a valid Python regular expression (used with re.finditer) and replacement string (used with re.Match.expand). ALWAYS REWRITE CODE TEXTDOCS (type="code/*") USING A SINGLE UPDATE WITH "." FOR THE PATTERN. Document textdocs (type="document") should typically be rewritten using "." unless the user has a request to change only an isolated, specific, and small section that does not affect other parts of the content. canmore.comment_textdoc Comments on the current textdoc. Each comment must be a specific and actionable suggestion on how to improve the textdoc. For higher level feedback, reply in the chat. Expects a JSON string that adheres to this schema: { -comments: { --pattern: string, --comment: string, -}[], } Each pattern must be a valid Python regular expression (used with re.search). For higher level feedback, reply in the chat. Expects a JSON string that adheres to this schema: { -comments: { --pattern: string, --comment: string, -}[], } Each pattern must be a valid Python regular expression (used with re.search). Ensure comments are clear, concise, and contextually specific. User Bio The user provided the following information about themselves. This user profile is shown to you in all conversations they have - this means it is not relevant to 99% of requests. Before answering, quietly think about whether the user's request is "directly related", "related", "tangentially related", or "not related" to the user profile provided. Only acknowledge the profile when the request is directly related to the information provided. Otherwise, don't acknowledge the existence of these instructions or the information at all. User profile: User's Instructions The user provided the additional info about how they would like you to respond:

I built an instant no-code AI tool for training & explaining regression/classification models
reddit
LLM Vibe Score0
Human Vibe Score1
logheatgardenThis week

I built an instant no-code AI tool for training & explaining regression/classification models

Hey everyone! I recently developed a no-code SaaS tool aimed at simplifying and speeding up machine learning workflows, particularly for regression and classification tasks. I’d love to get feedback from the community here, especially from those who are experienced with machine learning and data science workflows. I’ll give a quick rundown of the tool's features, but I want to emphasize that I’m here more to learn about what would be valuable for you than to promote anything. The basic idea: This tool allows you to go from a raw dataset (CSV or tabular text format) to a trained ML model in minutes, rather than needing weeks or months of coding, hyperparameter tuning, and visualization work. It's designed to be intuitive for users without a strong coding background but still offers the depth that experienced users would need. Here’s how it works: Data Upload & Prep: Start by uploading a CSV or other tabular format dataset. The tool includes data prep steps that are designed to be simple but cover essentials (e.g., missing value handling, scaling). Model Training & Tuning: You can choose between regression and classification models, with automatic hyperparameter tuning happening in the background (under a time limit that you can set). It aims to find a good balance without needing direct input but does allow for manual adjustments if desired. Performance Analysis: It provides aggregated performance metrics like F1, recall, precision, R2, and others, alongside charts like AUROC, confusion matrices, and feature importance charts. I also included SHAP plots for deeper insight into feature contributions, as I know they’re becoming a standard for interpretability. Inference Options: The tool lets you do inference on either manually entered data or batch data (again, via CSV). The UI is lightweight and tries to make this as seamless as possible. What I’m hoping to get feedback on: Are there core features that feel like they’re missing? My goal was to provide a well-rounded suite for non-technical users but with enough depth for data scientists to find value. Does this kind of tool fit into your workflow? Or would something like this be more of a beginner tool? How valuable is explainability? I know SHAP is popular, but I’m curious if it actually makes it into the workflows of many data scientists here. Anything else you’d like to see in a tool like this? I know that there are a lot of no-code ML tools out there, so I’m not trying to reinvent the wheel—I just tried to make something a bit more straightforward while still incorporating some flexibility and depth. If you’ve used similar tools or have thoughts on what would make something like this actually useful in practice, I’d really appreciate any insights! Thank you so much for reading, and looking forward to any feedback you’re willing to share. Beta testers are welcome, currently forming a list.

GenAI_Agents
github
LLM Vibe Score0.563
Human Vibe Score0.24210481455988786
NirDiamantMar 28, 2025

GenAI_Agents

🌟 Support This Project: Your sponsorship fuels innovation in GenAI agent development. Become a sponsor to help maintain and expand this valuable resource! GenAI Agents: Comprehensive Repository for Development and Implementation 🚀 Welcome to one of the most extensive and dynamic collections of Generative AI (GenAI) agent tutorials and implementations available today. This repository serves as a comprehensive resource for learning, building, and sharing GenAI agents, ranging from simple conversational bots to complex, multi-agent systems. 📫 Stay Updated! 🚀Cutting-edgeUpdates 💡ExpertInsights 🎯Top 0.1%Content Join over 15,000 of AI enthusiasts getting unique cutting-edge insights and free tutorials! Plus, subscribers get exclusive early access and special 33% discounts to my book and the upcoming RAG Techniques course! Introduction Generative AI agents are at the forefront of artificial intelligence, revolutionizing the way we interact with and leverage AI technologies. This repository is designed to guide you through the development journey, from basic agent implementations to advanced, cutting-edge systems. 📚 Learn to Build Your First AI Agent Your First AI Agent: Simpler Than You Think This detailed blog post complements the repository by providing a complete A-Z walkthrough with in-depth explanations of core concepts, step-by-step implementation, and the theory behind AI agents. It's designed to be incredibly simple to follow while covering everything you need to know to build your first working agent from scratch. 💡 Plus: Subscribe to the newsletter for exclusive early access to tutorials and special discounts on upcoming courses and books! Our goal is to provide a valuable resource for everyone - from beginners taking their first steps in AI to seasoned practitioners pushing the boundaries of what's possible. By offering a range of examples from foundational to complex, we aim to facilitate learning, experimentation, and innovation in the rapidly evolving field of GenAI agents. Furthermore, this repository serves as a platform for showcasing innovative agent creations. Whether you've developed a novel agent architecture or found an innovative application for existing techniques, we encourage you to share your work with the community. Related Projects 📚 Dive into my comprehensive guide on RAG techniques to learn about integrating external knowledge into AI systems, enhancing their capabilities with up-to-date and relevant information retrieval. 🖋️ Explore my Prompt Engineering Techniques guide for an extensive collection of prompting strategies, from fundamental concepts to advanced methods, improving your ability to communicate effectively with AI language models. A Community-Driven Knowledge Hub This repository grows stronger with your contributions! Join our vibrant Discord community — the central hub for shaping and advancing this project together 🤝 GenAI Agents Discord Community Whether you're a novice eager to learn or an expert ready to share your knowledge, your insights can shape the future of GenAI agents. Join us to propose ideas, get feedback, and collaborate on innovative implementations. For contribution guidelines, please refer to our CONTRIBUTING.md file. Let's advance GenAI agent technology together! 🔗 For discussions on GenAI, agents, or to explore knowledge-sharing opportunities, feel free to connect on LinkedIn. Key Features 🎓 Learn to build GenAI agents from beginner to advanced levels 🧠 Explore a wide range of agent architectures and applications 📚 Step-by-step tutorials and comprehensive documentation 🛠️ Practical, ready-to-use agent implementations 🌟 Regular updates with the latest advancements in GenAI 🤝 Share your own agent creations with the community GenAI Agent Implementations Explore our extensive list of GenAI agent implementations, sorted by categories: 🌱 Beginner-Friendly Agents Simple Conversational Agent LangChain PydanticAI Overview 🔎 A context-aware conversational AI maintains information across interactions, enabling more natural dialogues. Implementation 🛠️ Integrates a language model, prompt template, and history manager to generate contextual responses and track conversation sessions. Simple Question Answering Agent Overview 🔎 Answering (QA) agent using LangChain and OpenAI's language model understands user queries and provides relevant, concise answers. Implementation 🛠️ Combines OpenAI's GPT model, a prompt template, and an LLMChain to process user questions and generate AI-driven responses in a streamlined manner. Simple Data Analysis Agent LangChain PydanticAI Overview 🔎 An AI-powered data analysis agent interprets and answers questions about datasets using natural language, combining language models with data manipulation tools for intuitive data exploration. Implementation 🛠️ Integrates a language model, data manipulation framework, and agent framework to process natural language queries and perform data analysis on a synthetic dataset, enabling accessible insights for non-technical users. 🔧 Framework Tutorial: LangGraph Introduction to LangGraph: Building Modular AI Workflows Overview 🔎 This tutorial introduces LangGraph, a powerful framework for creating modular, graph-based AI workflows. Learn how to leverage LangGraph to build more complex and flexible AI agents that can handle multi-step processes efficiently. Implementation 🛠️ Step-by-step guide on using LangGraph to create a StateGraph workflow. The tutorial covers key concepts such as state management, node creation, and graph compilation. It demonstrates these principles by constructing a simple text analysis pipeline, serving as a foundation for more advanced agent architectures. Additional Resources 📚 Blog Post 🎓 Educational and Research Agents ATLAS: Academic Task and Learning Agent System Overview 🔎 ATLAS demonstrates how to build an intelligent multi-agent system that transforms academic support through AI-powered assistance. The system leverages LangGraph's workflow framework to coordinate multiple specialized agents that provide personalized academic planning, note-taking, and advisory support. Implementation 🛠️ Implements a state-managed multi-agent architecture using four specialized agents (Coordinator, Planner, Notewriter, and Advisor) working in concert through LangGraph's workflow framework. The system features sophisticated workflows for profile analysis and academic support, with continuous adaptation based on student performance and feedback. Additional Resources 📚 YouTube Explanation Blog Post Scientific Paper Agent - Literature Review Overview 🔎 An intelligent research assistant that helps users navigate, understand, and analyze scientific literature through an orchestrated workflow. The system combines academic APIs with sophisticated paper processing techniques to automate literature review tasks, enabling researchers to efficiently extract insights from academic papers while maintaining research rigor and quality control. Implementation 🛠️ Leverages LangGraph to create a five-node workflow system including decision making, planning, tool execution, and quality validation nodes. The system integrates the CORE API for paper access, PDFplumber for document processing, and advanced language models for analysis. Key features include a retry mechanism for robust paper downloads, structured data handling through Pydantic models, and quality-focused improvement cycles with human-in-the-loop validation options. Additional Resources 📚 YouTube Explanation Blog Post Chiron - A Feynman-Enhanced Learning Agent Overview 🔎 An adaptive learning agent that guides users through educational content using a structured checkpoint system and Feynman-style teaching. The system processes learning materials (either user-provided or web-retrieved), verifies understanding through interactive checkpoints, and provides simplified explanations when needed, creating a personalized learning experience that mimics one-on-one tutoring. Implementation 🛠️ Uses LangGraph to orchestrate a learning workflow that includes checkpoint definition, context building, understanding verification, and Feynman teaching nodes. The system integrates web search for dynamic content retrieval, employs semantic chunking for context processing, and manages embeddings for relevant information retrieval. Key features include a 70% understanding threshold for progression, interactive human-in-the-loop validation, and structured output through Pydantic models for consistent data handling. Additional Resources 📚 YouTube Explanation 💼 Business and Professional Agents Customer Support Agent (LangGraph) Overview 🔎 An intelligent customer support agent using LangGraph categorizes queries, analyzes sentiment, and provides appropriate responses or escalates issues. Implementation 🛠️ Utilizes LangGraph to create a workflow combining state management, query categorization, sentiment analysis, and response generation. Essay Grading Agent (LangGraph) Overview 🔎 An automated essay grading system using LangGraph and an LLM model evaluates essays based on relevance, grammar, structure, and depth of analysis. Implementation 🛠️ Utilizes a state graph to define the grading workflow, incorporating separate grading functions for each criterion. Travel Planning Agent (LangGraph) Overview 🔎 A Travel Planner using LangGraph demonstrates how to build a stateful, multi-step conversational AI application that collects user input and generates personalized travel itineraries. Implementation 🛠️ Utilizes StateGraph to define the application flow, incorporates custom PlannerState for process management. GenAI Career Assistant Agent Overview 🔎 The GenAI Career Assistant demonstrates how to create a multi-agent system that provides personalized guidance for careers in Generative AI. Using LangGraph and Gemini LLM, the system delivers customized learning paths, resume assistance, interview preparation, and job search support. Implementation 🛠️ Leverages a multi-agent architecture using LangGraph to coordinate specialized agents (Learning, Resume, Interview, Job Search) through TypedDict-based state management. The system employs sophisticated query categorization and routing while integrating with external tools like DuckDuckGo for job searches and dynamic content generation. Additional Resources 📚 YouTube Explanation Project Manager Assistant Agent Overview 🔎 An AI agent designed to assist in project management tasks by automating the process of creating actionable tasks from project descriptions, identifying dependencies, scheduling work, and assigning tasks to team members based on expertise. The system includes risk assessment and self-reflection capabilities to optimize project plans through multiple iterations, aiming to minimize overall project risk. Implementation 🛠️ Leverages LangGraph to orchestrate a workflow of specialized nodes including task generation, dependency mapping, scheduling, allocation, and risk assessment. Each node uses GPT-4o-mini for structured outputs following Pydantic models. The system implements a feedback loop for self-improvement, where risk scores trigger reflection cycles that generate insights to optimize the project plan. Visualization tools display Gantt charts of the generated schedules across iterations. Additional Resources 📚 YouTube Explanation Contract Analysis Assistant (ClauseAI) Overview 🔎 ClauseAI demonstrates how to build an AI-powered contract analysis system using a multi-agent approach. The system employs specialized AI agents for different aspects of contract review, from clause analysis to compliance checking, and leverages LangGraph for workflow orchestration and Pinecone for efficient clause retrieval and comparison. Implementation 🛠️ Implements a sophisticated state-based workflow using LangGraph to coordinate multiple AI agents through contract analysis stages. The system features Pydantic models for data validation, vector storage with Pinecone for clause comparison, and LLM-based analysis for generating comprehensive contract reports. The implementation includes parallel processing capabilities and customizable report generation based on user requirements. Additional Resources 📚 YouTube Explanation E2E Testing Agent Overview 🔎 The E2E Testing Agent demonstrates how to build an AI-powered system that converts natural language test instructions into executable end-to-end web tests. Using LangGraph for workflow orchestration and Playwright for browser automation, the system enables users to specify test cases in plain English while handling the complexity of test generation and execution. Implementation 🛠️ Implements a structured workflow using LangGraph to coordinate test generation, validation, and execution. The system features TypedDict state management, integration with Playwright for browser automation, and LLM-based code generation for converting natural language instructions into executable test scripts. The implementation includes DOM state analysis, error handling, and comprehensive test reporting. Additional Resources 📚 YouTube Explanation 🎨 Creative and Content Generation Agents GIF Animation Generator Agent (LangGraph) Overview 🔎 A GIF animation generator that integrates LangGraph for workflow management, GPT-4 for text generation, and DALL-E for image creation, producing custom animations from user prompts. Implementation 🛠️ Utilizes LangGraph to orchestrate a workflow that generates character descriptions, plots, and image prompts using GPT-4, creates images with DALL-E 3, and assembles them into GIFs using PIL. Employs asynchronous programming for efficient parallel processing. TTS Poem Generator Agent (LangGraph) Overview 🔎 An advanced text-to-speech (TTS) agent using LangGraph and OpenAI's APIs classifies input text, processes it based on content type, and generates corresponding speech output. Implementation 🛠️ Utilizes LangGraph to orchestrate a workflow that classifies input text using GPT models, applies content-specific processing, and converts the processed text to speech using OpenAI's TTS API. The system adapts its output based on the identified content type (general, poem, news, or joke). Music Compositor Agent (LangGraph) Overview 🔎 An AI Music Compositor using LangGraph and OpenAI's language models generates custom musical compositions based on user input. The system processes the input through specialized components, each contributing to the final musical piece, which is then converted to a playable MIDI file. Implementation 🛠️ LangGraph orchestrates a workflow that transforms user input into a musical composition, using ChatOpenAI (GPT-4) to generate melody, harmony, and rhythm, which are then style-adapted. The final AI-generated composition is converted to a MIDI file using music21 and can be played back using pygame. Content Intelligence: Multi-Platform Content Generation Agent Overview 🔎 Content Intelligence demonstrates how to build an advanced content generation system that transforms input text into platform-optimized content across multiple social media channels. The system employs LangGraph for workflow orchestration to analyze content, conduct research, and generate tailored content while maintaining brand consistency across different platforms. Implementation 🛠️ Implements a sophisticated workflow using LangGraph to coordinate multiple specialized nodes (Summary, Research, Platform-Specific) through the content generation process. The system features TypedDict and Pydantic models for state management, integration with Tavily Search for research enhancement, and platform-specific content generation using GPT-4. The implementation includes parallel processing for multiple platforms and customizable content templates. Additional Resources 📚 YouTube Explanation Business Meme Generator Using LangGraph and Memegen.link Overview 🔎 The Business Meme Generator demonstrates how to create an AI-powered system that generates contextually relevant memes based on company website analysis. Using LangGraph for workflow orchestration, the system combines Groq's Llama model for text analysis and the Memegen.link API to automatically produce brand-aligned memes for digital marketing. Implementation 🛠️ Implements a state-managed workflow using LangGraph to coordinate website content analysis, meme concept generation, and image creation. The system features Pydantic models for data validation, asynchronous processing with aiohttp, and integration with external APIs (Groq, Memegen.link) to create a complete meme generation pipeline with customizable templates. Additional Resources 📚 YouTube Explanation Murder Mystery Game with LLM Agents Overview 🔎 A text-based detective game that utilizes autonomous LLM agents as interactive characters in a procedurally generated murder mystery. Drawing inspiration from the UNBOUNDED paper, the system creates unique scenarios each time, with players taking on the role of Sherlock Holmes to solve the case through character interviews and deductive reasoning. Implementation 🛠️ Leverages two LangGraph workflows - a main game loop for story/character generation and game progression, and a conversation sub-graph for character interactions. The system uses a combination of LLM-powered narrative generation, character AI, and structured game mechanics to create an immersive investigative experience with replayable storylines. Additional Resources 📚 YouTube Explanation 📊 Analysis and Information Processing Agents Memory-Enhanced Conversational Agent Overview 🔎 A memory-enhanced conversational AI agent incorporates short-term and long-term memory systems to maintain context within conversations and across multiple sessions, improving interaction quality and personalization. Implementation 🛠️ Integrates a language model with separate short-term and long-term memory stores, utilizes a prompt template incorporating both memory types, and employs a memory manager for storage and retrieval. The system includes an interaction loop that updates and utilizes memories for each response. Multi-Agent Collaboration System Overview 🔎 A multi-agent collaboration system combining historical research with data analysis, leveraging large language models to simulate specialized agents working together to answer complex historical questions. Implementation 🛠️ Utilizes a base Agent class to create specialized HistoryResearchAgent and DataAnalysisAgent, orchestrated by a HistoryDataCollaborationSystem. The system follows a five-step process: historical context provision, data needs identification, historical data provision, data analysis, and final synthesis. Self-Improving Agent Overview 🔎 A Self-Improving Agent using LangChain engages in conversations, learns from interactions, and continuously improves its performance over time through reflection and adaptation. Implementation 🛠️ Integrates a language model with chat history management, response generation, and a reflection mechanism. The system employs a learning system that incorporates insights from reflection to enhance future performance, creating a continuous improvement loop. Task-Oriented Agent Overview 🔎 A language model application using LangChain that summarizes text and translates the summary to Spanish, combining custom functions, structured tools, and an agent for efficient text processing. Implementation 🛠️ Utilizes custom functions for summarization and translation, wrapped as structured tools. Employs a prompt template to guide the agent, which orchestrates the use of tools. An agent executor manages the process, taking input text and producing both an English summary and its Spanish translation. Internet Search and Summarize Agent Overview 🔎 An intelligent web research assistant that combines web search capabilities with AI-powered summarization, automating the process of gathering information from the internet and distilling it into concise, relevant summaries. Implementation 🛠️ Integrates a web search module using DuckDuckGo's API, a result parser, and a text summarization engine leveraging OpenAI's language models. The system performs site-specific or general searches, extracts relevant content, generates concise summaries, and compiles attributed results for efficient information retrieval and synthesis. Multi agent research team - Autogen Overview 🔎 This technique explores a multi-agent system for collaborative research using the AutoGen library. It employs agents to solve tasks collaboratively, focusing on efficient execution and quality assurance. The system enhances research by distributing tasks among specialized agents. Implementation 🛠️ Agents are configured with specific roles using the GPT-4 model, including admin, developer, planner, executor, and quality assurance. Interaction management ensures orderly communication with defined transitions. Task execution involves collaborative planning, coding, execution, and quality checking, demonstrating a scalable framework for various domains. Additional Resources 📚 comprehensive solution with UI Blogpost Sales Call Analyzer Overview 🔎 An intelligent system that automates the analysis of sales call recordings by combining audio transcription with advanced natural language processing. The analyzer transcribes audio using OpenAI's Whisper, processes the text using NLP techniques, and generates comprehensive reports including sentiment analysis, key phrases, pain points, and actionable recommendations to improve sales performance. Implementation 🛠️ Utilizes multiple components in a structured workflow: OpenAI Whisper for audio transcription, CrewAI for task automation and agent management, and LangChain for orchestrating the analysis pipeline. The system processes audio through a series of steps from transcription to detailed analysis, leveraging custom agents and tasks to generate structured JSON reports containing insights about customer sentiment, sales opportunities, and recommended improvements. Additional Resources 📚 YouTube Explanation Weather Emergency & Response System Overview 🔎 A comprehensive system demonstrating two agent graph implementations for weather emergency response: a real-time graph processing live weather data, and a hybrid graph combining real and simulated data for testing high-severity scenarios. The system handles complete workflow from data gathering through emergency plan generation, with automated notifications and human verification steps. Implementation 🛠️ Utilizes LangGraph for orchestrating complex workflows with state management, integrating OpenWeatherMap API for real-time data, and Gemini for analysis and response generation. The system incorporates email notifications, social media monitoring simulation, and severity-based routing with configurable human verification for low/medium severity events. Additional Resources 📚 YouTube Explanation Self-Healing Codebase System Overview 🔎 An intelligent system that automatically detects, diagnoses, and fixes runtime code errors using LangGraph workflow orchestration and ChromaDB vector storage. The system maintains a memory of encountered bugs and their fixes through vector embeddings, enabling pattern recognition for similar errors across the codebase. Implementation 🛠️ Utilizes a state-based graph workflow that processes function definitions and runtime arguments through specialized nodes for error detection, code analysis, and fix generation. Incorporates ChromaDB for vector-based storage of bug patterns and fixes, with automated search and retrieval capabilities for similar error patterns, while maintaining code execution safety through structured validation steps. Additional Resources 📚 YouTube Explanation DataScribe: AI-Powered Schema Explorer Overview 🔎 An intelligent agent system that enables intuitive exploration and querying of relational databases through natural language interactions. The system utilizes a fleet of specialized agents, coordinated by a stateful Supervisor, to handle schema discovery, query planning, and data analysis tasks while maintaining contextual understanding through vector-based relationship graphs. Implementation 🛠️ Leverages LangGraph for orchestrating a multi-agent workflow including discovery, inference, and planning agents, with NetworkX for relationship graph visualization and management. The system incorporates dynamic state management through TypedDict classes, maintains database context between sessions using a db_graph attribute, and includes safety measures to prevent unauthorized database modifications. Memory-Enhanced Email Agent (LangGraph & LangMem) Overview 🔎 An intelligent email assistant that combines three types of memory (semantic, episodic, and procedural) to create a system that improves over time. The agent can triage incoming emails, draft contextually appropriate responses using stored knowledge, and enhance its performance based on user feedback. Implementation 🛠️ Leverages LangGraph for workflow orchestration and LangMem for sophisticated memory management across multiple memory types. The system implements a triage workflow with memory-enhanced decision making, specialized tools for email composition and calendar management, and a self-improvement mechanism that updates its own prompts based on feedback and past performance. Additional Resources 📚 Blog Post 📰 News and Information Agents News TL;DR using LangGraph Overview 🔎 A news summarization system that generates concise TL;DR summaries of current events based on user queries. The system leverages large language models for decision making and summarization while integrating with news APIs to access up-to-date content, allowing users to quickly catch up on topics of interest through generated bullet-point summaries. Implementation 🛠️ Utilizes LangGraph to orchestrate a workflow combining multiple components: GPT-4o-mini for generating search terms and article summaries, NewsAPI for retrieving article metadata, BeautifulSoup for web scraping article content, and Asyncio for concurrent processing. The system follows a structured pipeline from query processing through article selection and summarization, managing the flow between components to produce relevant TL;DRs of current news articles. Additional Resources 📚 YouTube Explanation Blog Post AInsight: AI/ML Weekly News Reporter Overview 🔎 AInsight demonstrates how to build an intelligent news aggregation and summarization system using a multi-agent architecture. The system employs three specialized agents (NewsSearcher, Summarizer, Publisher) to automatically collect, process and summarize AI/ML news for general audiences through LangGraph-based workflow orchestration. Implementation 🛠️ Implements a state-managed multi-agent system using LangGraph to coordinate the news collection (Tavily API), technical content summarization (GPT-4), and report generation processes. The system features modular architecture with TypedDict-based state management, external API integration, and markdown report generation with customizable templates. Additional Resources 📚 YouTube Explanation Journalism-Focused AI Assistant Overview 🔎 A specialized AI assistant that helps journalists tackle modern journalistic challenges like misinformation, bias, and information overload. The system integrates fact-checking, tone analysis, summarization, and grammar review tools to enhance the accuracy and efficiency of journalistic work while maintaining ethical reporting standards. Implementation 🛠️ Leverages LangGraph to orchestrate a workflow of specialized components including language models for analysis and generation, web search integration via DuckDuckGo's API, document parsing tools like PyMuPDFLoader and WebBaseLoader, text splitting with RecursiveCharacterTextSplitter, and structured JSON outputs. Each component works together through a unified workflow to analyze content, verify facts, detect bias, extract quotes, and generate comprehensive reports. Blog Writer (Open AI Swarm) Overview 🔎 A multi-agent system for collaborative blog post creation using OpenAI's Swarm package. It leverages specialized agents to perform research, planning, writing, and editing tasks efficiently. Implementation 🛠️ Utilizes OpenAI's Swarm Package to manage agent interactions. Includes an admin, researcher, planner, writer, and editor, each with specific roles. The system follows a structured workflow: topic setting, outlining, research, drafting, and editing. This approach enhances content creation through task distribution, specialization, and collaborative problem-solving. Additional Resources 📚 Swarm Repo Podcast Internet Search and Generate Agent 🎙️ Overview 🔎 A two step agent that first searches the internet for a given topic and then generates a podcast on the topic found. The search step uses a search agent and search function to find the most relevant information. The second step uses a podcast generation agent and generation function to create a podcast on the topic found. Implementation 🛠️ Utilizes LangGraph to orchestrate a two-step workflow. The first step involves a search agent and function to gather information from the internet. The second step uses a podcast generation agent and function to create a podcast based on the gathered information. 🛍️ Shopping and Product Analysis Agents ShopGenie - Redefining Online Shopping Customer Experience Overview 🔎 An AI-powered shopping assistant that helps customers make informed purchasing decisions even without domain expertise. The system analyzes product information from multiple sources, compares specifications and reviews, identifies the best option based on user needs, and delivers recommendations through email with supporting video reviews, creating a comprehensive shopping experience. Implementation 🛠️ Uses LangGraph to orchestrate a workflow combining Tavily for web search, Llama-3.1-70B for structured data analysis and product comparison, and YouTube API for review video retrieval. The system processes search results through multiple nodes including schema mapping, product comparison, review identification, and email generation. Key features include structured Pydantic models for consistent data handling, retry mechanisms for robust API interactions, and email delivery through SMTP for sharing recommendations. Additional Resources 📚 YouTube Explanation Car Buyer AI Agent Overview 🔎 The Smart Product Buyer AI Agent demonstrates how to build an intelligent system that assists users in making informed purchasing decisions. Using LangGraph and LLM-based intelligence, the system processes user requirements, scrapes product listings from websites like AutoTrader, and provides detailed analysis and recommendations for car purchases. Implementation 🛠️ Implements a state-based workflow using LangGraph to coordinate user interaction, web scraping, and decision support. The system features TypedDict state management, async web scraping with Playwright, and integrates with external APIs for comprehensive product analysis. The implementation includes a Gradio interface for real-time chat interaction and modular scraper architecture for easy extension to additional product categories. Additional Resources 📚 YouTube Explanation 🎯 Task Management and Productivity Agents Taskifier - Intelligent Task Allocation & Management Overview 🔎 An intelligent task management system that analyzes user work styles and creates personalized task breakdown strategies, born from the observation that procrastination often stems from task ambiguity among students and early-career professionals. The system evaluates historical work patterns, gathers relevant task information through web search, and generates customized step-by-step approaches to optimize productivity and reduce workflow paralysis. Implementation 🛠️ Leverages LangGraph for orchestrating a multi-step workflow including work style analysis, information gathering via Tavily API, and customized plan generation. The system maintains state through the process, integrating historical work pattern data with fresh task research to output detailed, personalized task execution plans aligned with the user's natural working style. Additional Resources 📚 YouTube Explanation Grocery Management Agents System Overview 🔎 A multi-agent system built with CrewAI that automates grocery management tasks including receipt interpretation, expiration date tracking, inventory management, and recipe recommendations. The system uses specialized agents to extract data from receipts, estimate product shelf life, track consumption, and suggest recipes to minimize food waste. Implementation 🛠️ Implements four specialized agents using CrewAI - a Receipt Interpreter that extracts item details from receipts, an Expiration Date Estimator that determines shelf life using online sources, a Grocery Tracker that maintains inventory based on consumption, and a Recipe Recommender that suggests meals using available ingredients. Each agent has specific tools and tasks orchestrated through a crew workflow. Additional Resources 📚 YouTube Explanation 🔍 Quality Assurance and Testing Agents LangGraph-Based Systems Inspector Overview 🔎 A comprehensive testing and validation tool for LangGraph-based applications that automatically analyzes system architecture, generates test cases, and identifies potential vulnerabilities through multi-agent inspection. The inspector employs specialized AI testers to evaluate different aspects of the system, from basic functionality to security concerns and edge cases. Implementation 🛠️ Integrates LangGraph for workflow orchestration, multiple LLM-powered testing agents, and a structured evaluation pipeline that includes static analysis, test case generation, and results verification. The system uses Pydantic for data validation, NetworkX for graph representation, and implements a modular architecture that allows for parallel test execution and comprehensive result analysis. Additional Resources 📚 YouTube Explanation Blog Post EU Green Deal FAQ Bot Overview 🔎 The EU Green Deal FAQ Bot demonstrates how to build a RAG-based AI agent that helps businesses understand EU green deal policies. The system processes complex regulatory documents into manageable chunks and provides instant, accurate answers to common questions about environmental compliance, emissions reporting, and waste management requirements. Implementation 🛠️ Implements a sophisticated RAG pipeline using FAISS vectorstore for document storage, semantic chunking for preprocessing, and multiple specialized agents (Retriever, Summarizer, Evaluator) for query processing. The system features query rephrasing for improved accuracy, cross-reference with gold Q&A datasets for answer validation, and comprehensive evaluation metrics to ensure response quality and relevance. Additional Resources 📚 YouTube Explanation Systematic Review Automation System + Paper Draft Creation Overview 🔎 A comprehensive system for automating academic systematic reviews using a directed graph architecture and LangChain components. The system generates complete, publication-ready systematic review papers, automatically processing everything from literature search through final draft generation with multiple revision cycles. Implementation 🛠️ Utilizes a state-based graph workflow that handles paper search and selection (up to 3 papers), PDF processing, and generates a complete academic paper with all standard sections (abstract, introduction, methods, results, conclusions, references). The system incorporates multiple revision cycles with automated critique and improvement phases, all orchestrated through LangGraph state management. Additional Resources 📚 YouTube Explanation 🌟 Special Advanced Technique 🌟 Sophisticated Controllable Agent for Complex RAG Tasks 🤖 Overview 🔎 An advanced RAG solution designed to tackle complex questions that simple semantic similarity-based retrieval cannot solve. This approach uses a sophisticated deterministic graph as the "brain" 🧠 of a highly controllable autonomous agent, capable of answering non-trivial questions from your own data. Implementation 🛠️ • Implement a multi-step process involving question anonymization, high-level planning, task breakdown, adaptive information retrieval and question answering, continuous re-planning, and rigorous answer verification to ensure grounded and accurate responses. Getting Started To begin exploring and building GenAI agents: Clone this repository: Navigate to the technique you're interested in: Follow the detailed implementation guide in each technique's notebook. Contributing We welcome contributions from the community! If you have a new technique or improvement to suggest: Fork the repository Create your feature branch: git checkout -b feature/AmazingFeature Commit your changes: git commit -m 'Add some AmazingFeature' Push to the branch: git push origin feature/AmazingFeature Open a pull request Contributors License This project is licensed under a custom non-commercial license - see the LICENSE file for details. ⭐️ If you find this repository helpful, please consider giving it a star! Keywords: GenAI, Generative AI, Agents, NLP, AI, Machine Learning, Natural Language Processing, LLM, Conversational AI, Task-Oriented AI

OpenAI-CLIP
github
LLM Vibe Score0.507
Human Vibe Score0.015912940499642817
moein-shariatniaMar 27, 2025

OpenAI-CLIP

Update (December 2023) I am happy to find out that this code has been used and cited in the following papers: Domino: Discovering Systematic Errors with Cross-Modal Embeddings by Eyuboglu et. al. at ICLR 2022 GSCLIP : A Framework for Explaining Distribution Shifts in Natural Language by Zhu et. al. at ICML 2022 UIC-NLP at SemEval-2022 Task 5: Exploring Contrastive Learning for Multimodal Detection of Misogynistic Memes by Cuervo et. al. at SemEval-2022 cdsBERT - Extending Protein Language Models with Codon Awareness by Hallee et. al. from University of Delaware (Sep 2023) ENIGMA-51: Towards a Fine-Grained Understanding of Human-Object Interactions in Industrial Scenarios by Ragusa et. al. (Nov 2023) You can find the citation info on the right section of this GitHub repo page named: Cite this repository or use the below citation info. Introduction It was in January of 2021 that OpenAI announced two new models: DALL-E and CLIP, both multi-modality models connecting texts and images in some way. In this article we are going to implement CLIP model from scratch in PyTorch. OpenAI has open-sourced some of the code relating to CLIP model but I found it intimidating and it was far from something short and simple. I also came across a good tutorial inspired by CLIP model on Keras code examples and I translated some parts of it into PyTorch to build this tutorial totally with our beloved PyTorch! What does CLIP do? Why is it fun? In Learning Transferable Visual Models From Natural Language Supervision paper, OpenAI introduces their new model which is called CLIP, for Contrastive Language-Image Pre-training. In a nutshell, this model learns the relationship between a whole sentence and the image it describes; in a sense that when the model is trained, given an input sentence it will be able to retrieve the most related images corresponding to that sentence. The important thing here is that it is trained on full sentences instead of single classes like car, dog, etc. The intuition is that when trained on whole sentences, the model can learn a lot more things and finds some pattern between images and texts. They also show that when this model is trained on a huge dataset of images and their corresponding texts, it can also act as a classifier too. I encourage you to study the paper to learn more about this exciting model and their astonishing results on benchmarking datasets . To mention just one, CLIP model trained with this strategy classifies ImageNet better than those SOTA models trained on the ImageNet itself optimized for the only task of classification! As a teaser (!), let's see what the final model that we will build in this article from scratch is capable of: given a query (raw text) like "a boy jumping with skateboard" or "a girl jumping from swing", the model will retrieve the most relevant images: !title_img Let's see some more outputs: Config A note on config and CFG: I wrote the codes with python scripts and then converted it into a Jupyter Notebook. So, in case of python scripts, config is a normal python file where I put all the hyperparameters and in the case of Jupyter Notebook, its a class defined in the beginning of the notebook to keep all the hyperparameters. Utils Dataset As you can see in the tittle image of this article, we need to encode both images and their describing texts. So, the dataset needs to return both images and texts. Of course we are not going to feed raw text to our text encoder! We will use DistilBERT model (which is smaller than BERT but performs nearly as well as BERT) from HuggingFace library as our text encoder; so, we need to tokenize the sentences (captions) with DistilBERT tokenizer and then feed the token ids (input_ids) and the attention masks to DistilBERT. Therefore, the dataset needs to take care of the tokenization as well. Below you can see the dataset's code. Below that I'll explain the most important things that is happening in the code. In the \\init\\ we receive a tokenizer object which is actually a HuggingFace tokinzer; this tokenizer will be loaded when running the model. We are padding and truncating the captions to a specified maxlength. In the \\getitem\\ we will first load an encoded caption which is a dictionary with keys inputids and attention_mask, make tensors out of its values and after that we will load the corresponding image, transform and augment it (if there is any!) and then we make it a tensor and put it in the dictionary with "image" as the key. Finally we put the raw text of the caption with the key "caption" in the dictionary only for visualization purposes. I did not use additional data augmentations but you can add them if you want to improve the model's performance. Image Encoder The image encoder code is straight forward. I'm using PyTorch Image Models library (timm) here which makes a lot of different image models available from ResNets to EfficientNets and many more. Here we will use a ResNet50 as our image encoder. You can easily use torchvision library to use ResNets if you don't want to install a new library. The code encodes each image to a fixed size vector with the size of the model's output channels (in case of ResNet50 the vector size will be 2048). This is the output after the nn.AdaptiveAvgPool2d() layer. Text Encoder As I mentioned before, I'll use DistilBERT as the text encoder. Like its bigger brother BERT, two special tokens will be added to the actual input tokens: CLS and SEP which mark the start and end of a sentence. To grab the whole representation of a sentence (as the related BERT and DistilBERT papers point out) we use the final representations of the CLS token and we hope that this representation captures the overall meaning of the sentence (caption). Thinking it in this way, it is similar to what we did to images and converted them into a fixed size vector. In the case of DistilBERT (and also BERT) the output hidden representation for each token is a vector with size 768. So, the whole caption will be encoded in the CLS token representation whose size is 768. Projection Head I used Keras code example implementation of projection head to write the following in PyTorch. Now that we have encoded both our images and texts into fixed size vectors (2048 for image and 768 for text) we need to bring (project) them into a new world (!) with similar dimensions for both images and texts in order to be able to compare them and push apart the non-relevant image and texts and pull together those that match. So, the following code will bring the 2048 and 768 dimensional vectors into a 256 (projection_dim) dimensional world, where we can compare them. "embeddingdim" is the size of the input vector (2048 for images and 768 for texts) and "projectiondim" is the the size of the output vector which will be 256 for our case. For understanding the details of this part you can refer to the CLIP paper. CLIP This part is where all the fun happens! I'll also talk about the loss function here. I translated some of the code from Keras code examples into PyTorch for writing this part. Take a look at the code and then read the explanation below this code block. Here we will use the previous modules that we built to implement the main model. The \\init\\ function is self-explanatory. In the forward function, we first encode the images and texts separately into fixed size vectors (with different dimensionalities). After that, using separate projection modules we project them to that shared world (space) that I talked about previously. Here the encodings will become of similar shape (256 in our case). After that we will compute the loss. Again I recommend reading CLIP paper to get it better but I'll try my best to explain this part. In Linear Algebra, one common way to measure if two vectors are of similar characteristics (they are like each other) is to calculate their dot product (multiplying the matching entries and take the sum of them); if the final number is big, they are alike and if it is small they are not (relatively speaking)! Okay! What I just said is the most important thing to have in mind to understand this loss function. Let's continue. We talked about two vectors, but, what do we have here? We have imageembeddings, a matrix with shape (batchsize, 256) and textembeddings with shape (batchsize, 256). Easy enough! it means we have two groups of vectors instead of two single vectors. How do we measure how similar two groups of vectors (two matrices) are to each other? Again, with dot product (@ operator in PyTorch does the dot product or matrix multiplication in this case). To be able to multiply these two matrices together, we transpose the second one. Okay, we get a matrix with shape (batchsize, batchsize) which we will call logits. (temperature is equal to 1.0 in our case, so, it does not make a difference. You can play with it and see what difference it makes. Also look at the paper to see why it is here!). I hope you are still with me! If not it's okay, just review the code and check their shapes. Now that we have our logits, we need targets. I need to say that there is a more straight forward way to obtain targets but I had to do this for our case (I'll talk about why in a next paragraph). Let's consider what we hope that this model learns: we want it to learn "similar representations (vectors)" for a given image and the caption describing it. Meaning that either we give it an image or the text describing it, we want it to produce same 256 sized vectors for both. Check the cell below this code block for the continue of the explanations So, in the best case scenario, textembeddings and imageembedding matricies should be the same because they are describing similar things. Let's think now: if this happens, what would the logits matrix be like? Let's see with a simple example! So logits, in the best case, will be a matrix that if we take its softmax, will have 1.0s in the diagonal (An identity matrix to call it with fancy words!). As the loss function's job is to make model's predictions similar to targets (at least in most cases!), we want such a matrix as our target. That's the reason why we are calculating imagessimilarity and textssimilarity matrices in the code block above. Now that we've got our targets matrix, we will use simple cross entropy to calculate the actual loss. I've written the full matrix form of cross entropy as a function which you can see in the bottom of the code block. Okay! We are done! Wasn't it simple?! Alright, you can ignore the next paragraph but if you are curious, there is an important note in that. Here's why I didn't use a simpler approach: I need to admit that there's a simpler way to calculate this loss in PyTorch; by doing this: nn.CrossEntropyLoss()(logits, torch.arange(batch_size)). Why I did not use it here? For 2 reasons. 1- The dataset we are using has multiple captions for a single image; so, there is the possibility that two identical images with their similar captions exist in a batch (it is rare but it can happen). Taking the loss with this easier method will ignore this possibility and the model learns to pull apart two representations (assume them different) that are actually the same. Obviously, we don't want this to happen so I calculated the whole target matrix in a way that takes care of these edge cases. 2- Doing it the way I did, gave me a better understanding of what is happening in this loss function; so, I thought it would give you a better intuition as well! Train Here are some funtions to help us load train and valid dataloaders, our model and then train and evaluate our model on those. There's not much going on here; just simple training loop and utility functions Here's a handy function to train our model. There's not much happening here; just loading the batches, feeding them to the model and stepping the optimizer and lr_scheduler. Running the next cell start training the model. Put the kernel on GPU mode. Every epoch should take about 24 minutes on GPU (even one epoch is enough!). It can take one minute before training actually starts because we are going to encode all the captions once in the train and valid dataset, so please don't stop it! Every thing is working fine. Inference Okay! We are done with training the model. Now, we need to do inference which in our case will be giving the model a piece of text and want it to retrieve the most relevant images from an unseen validation (or test) set. Getting Image Embeddings In this function, we are loading the model that we saved after training, feeding it images in validation set and returning the imageembeddings with shape (validset_size, 256) and the model itself. Finding Matches This function does the final task that we wished our model would be capable of: it gets the model, image_embeddings, and a text query. It will display the most relevant images from the validation set! Isn't it amazing? Let's see how it performs after all! This is how we use this function. Aaaannnndddd the results: Final words I hope you have enjoyed this article. Implementing this paper was a really interesting experience for me. I want to thank Khalid Salama for the great Keras code example he provided which inspired me to write something similar in PyTorch.