<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Reut Dayan on Medium]]></title>
        <description><![CDATA[Stories by Reut Dayan on Medium]]></description>
        <link>https://medium.com/@reutdayan1?source=rss-f59fb93eab8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SJVb95fat-hKCbu8mHfjMw.png</url>
            <title>Stories by Reut Dayan on Medium</title>
            <link>https://medium.com/@reutdayan1?source=rss-f59fb93eab8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:58:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reutdayan1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing Images for the Brain: From fMRI Encoding Models to Brain-Guided Generation]]></title>
            <link>https://medium.com/@reutdayan1/optimizing-images-for-the-brain-from-fmri-encoding-models-to-brain-guided-generation-fe9d686f0599?source=rss-f59fb93eab8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe9d686f0599</guid>
            <category><![CDATA[image-optimization]]></category>
            <category><![CDATA[fmri]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[activation-maximization]]></category>
            <dc:creator><![CDATA[Reut Dayan]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 08:49:13 GMT</pubDate>
            <atom:updated>2026-06-16T08:49:13.661Z</atom:updated>
            <content:encoded><![CDATA[<p>In standard neural encoding, we train a model that maps an image to predicted brain activity. But once this model is differentiable, we can reverse the question: instead of asking “what brain response will this image produce?”, we can ask “what image would produce the strongest response in this brain region?”</p><h3>Motivation: From Prediction to Intervention</h3><p>What image would make a face-selective brain region respond as strongly as possible? What about a place-selective region, or a region that responds to written words?</p><p>Traditionally, neuroscience studies answer these questions by designing stimulus sets, showing them to participants in an fMRI scanner, and measuring which images activate which regions. But this process is inherently limited by the images we choose to test.</p><p>Recent work suggests a different approach. First, train an image-to-fMRI model: a neural network that receives an image and predicts the brain response it would evoke. Then, instead of only using this model for prediction, use it as an objective. Search for images that maximize the predicted activity of a target voxel, region of interest (ROI), or cortical pattern.</p><p>In machine learning terms, image to fMRI models turns the brain into a differentiable loss function. The image, or the latent code of a generative model, becomes the variable we optimize. The output is a synthetic image that the model predicts will strongly activate a chosen part of the visual cortex.</p><p>This idea connects three fields: neural encoding models, feature visualization, and generative modeling. Together, they allow us to move from asking “can we predict brain activity?” to asking “can we synthesize stimuli that reveal what a brain region represents?”</p><h3>Background: Image-to-fMRI Encoding Models</h3><p>In a <a href="https://medium.com/@reutdayan1/from-brain-scans-to-encoding-models-a-beginners-guide-to-fmri-for-machine-learning-d73dc484eaae">previous post</a>, I introduced the basic idea of <strong>image-to-fMRI encoding models</strong>: models that receive a visual stimulus, such as an image, and predict the brain response it would evoke.</p><p>A central dataset in this field is the <a href="https://naturalscenesdataset.org/"><strong>Natural Scenes Dataset (NSD)</strong></a>. NSD contains high-resolution 7T fMRI responses from participants viewing thousands of natural images, creating paired examples of the image and the participant&#39;s fMRI activity. This provides supervised examples for learning image-to-brain encoding models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56PNXxgCRGFdqnvZF3TYVw.png" /><figcaption><a href="https://naturalscenesdataset.org/"><strong>The Natural Scenes Dataset</strong></a><strong>.</strong> Participants view natural images inside an fMRI scanner, to get image-fMRI pairs.</figcaption></figure><p>Modern approaches usually do not train the visual representation from scratch. Instead, they use a pretrained vision model as a feature extractor. A common example is <a href="https://www.nature.com/articles/s42256-023-00753-y"><strong>CLIP2Brain</strong></a>, which uses CLIP visual representations and learns a prediction head that maps those representations to fMRI responses. After training, the model can predict how strongly different brain regions are expected to respond to a new image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WP_0OT4EhXbKGI2s5j9N3w.png" /><figcaption><strong>Image-to-fMRI encoding with CLIP features.</strong> A pretrained CLIP vision model extracts an image representation, and a learned prediction head maps this representation to voxel-wise fMRI responses. These predictions can then be analyzed inside specific regions of interest, such as face-, body-, scene-, or early visual areas.</figcaption></figure><p>A full fMRI prediction can contain tens of thousands of voxel values. To make the output interpretable, researchers often focus on <strong>regions of interest (</strong>ROIs) — groups of voxels associated with a meaningful anatomical or functional area.</p><p>For example, in the visual cortex, we may care about:</p><ul><li>Face-selective regions (e.g., FFA)</li><li>Place- or scene-selective regions (e.g., PPA)</li><li>Body-selective regions</li><li>Word-selective regions</li><li>Early visual areas (e.g., V1, V2)</li></ul><p>This ROI-level view is important because it lets us connect model predictions to semantic hypotheses about brain function. If an ROI is known to respond to faces, then images that strongly activate it should, ideally, contain faces or face-like features.</p><p>Before generating new images, a simple way to understand an ROI is to look at the natural images that activate it the most. Given a trained image-to-fMRI model, we can rank a dataset of images according to the average activation in a target ROI.</p><p>For example, we can take all images from NSD, compute the mean activation in a face-selective region, and retrieve the top images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*ewHommktU37mHbi0J-6RPA.png" /><figcaption><strong>Top-activating images for a face-selective region.</strong> Ranking natural images by their measured or predicted activation can reveal what types of visual content drive a target ROI. In this example, many highly activating images contain people, faces, or animals.</figcaption></figure><p>This retrieval-based approach is intuitive and useful, but it has one major limitation: it can only show us images that already exist in the dataset. If the most informative stimulus is not present in NSD, retrieval will never find it.</p><h3>Activation Maximization: Reversing the Flow</h3><p>Once an encoding model is differentiable, we can use it in the opposite direction. This idea is known as <strong>activation maximization</strong>.</p><p>In classic deep learning interpretability, activation maximization is used to visualize what a neuron is sensitive to by iteratively updating the pixels of a random image so that the chosen neuron becomes more active. In the brain setting, the target is a predicted fMRI response.</p><p>Recent work on <a href="https://arxiv.org/pdf/2506.04379"><strong>Voxel-Weighted Activation Maximization</strong></a> shows that this can be applied directly to encoding models of human visual cortex. Starting from a random image, the pixels are iteratively optimized to increase the predicted response of a target voxel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1ijEjFOsiyder0NNN-xjg.png" /><figcaption><strong>Activation maximization.</strong> Starting from random noise, the image is iteratively optimized with gradient ascent to maximize the <strong>mean predicted activation of the voxels in a target ROI</strong>, producing an image predicted by the model to strongly drive that brain region.</figcaption></figure><p>For early visual areas (like V2), the optimized images contain localized high-contrast patches consistent with classic retinotopic mapping. In higher-level regions, the images become more semantic: face-selective areas (FFA) produce face-like structures, while place-selective areas (PPA) yield ground planes and buildings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*4uX3SchVOQXGmWN0sK_Wcw.png" /><figcaption>results from <a href="https://arxiv.org/pdf/2506.04379">paper</a>.</figcaption></figure><h3>NeuroGen &amp; BrainDiVE: Adding a Generative Prior</h3><p>Direct pixel optimization has an important weakness: because the optimizer can change every pixel freely, it often finds adversarial patterns that strongly activate the model but look unnatural.</p><p>A natural next step is to optimize inside the latent space of a generative model. This is the idea behind NeuroGen. Instead of directly changing pixels, NeuroGen combines an fMRI-trained encoding model with a deep generative network. The generator provides a natural-image prior,and therefore restricts the search to images that are more likely to look like real visual stimuli.</p><h4>BrainDiVE: Diffusion Based Generation</h4><p><a href="https://arxiv.org/pdf/2306.03089"><strong>BrainDiVE</strong> — <em>Brain Diffusion for Visual Exploration</em></a> — takes this a step further by replacing older generators with a modern diffusion model. During generation, an estimated clean image is passed through a differentiable brain encoder that predicts voxel-wise fMRI activity. Gradients from this score are then used to guide the diffusion process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*pF1CJMkhfYoGt3rxB2B3mA.png" /><figcaption><a href="https://arxiv.org/pdf/2306.03089"><strong>BrainDiVE pipeline</strong></a><strong>.</strong> Starting from noise, a diffusion model iteratively denoises an image representation. At each step, the current image is decoded and passed through a brain encoder, which predicts activation in a target brain region. The predicted activation is then used as a guidance signal, and gradients are backpropagated through the generation process to steer the image toward stimuli that are predicted to strongly activate the selected cortical region.</figcaption></figure><p>What makes <strong>BrainDiVE</strong> especially interesting is that the generated images are not random or arbitrary. When the authors target well-known category-selective regions, the generated images show semantic structure that matches what we already know about these areas. For example, images generated for <strong>face-selective regions</strong> contain face-like structure, images generated for <strong>place-selective regions</strong> resemble rooms, buildings, or spatial layouts, and images generated for <strong>body-, word-, and food-selective regions</strong> also reflect the expected visual categories.</p><p>This makes the results easy to interpret: the model is not only increasing a numerical activation score, but producing images that visually reveal what kind of content the target region is predicted to prefer. BrainDiVE validates this idea on known ROIs such as faces, places, bodies, food, and words, showing that brain-guided diffusion can synthesize preferred images with appropriate semantic specificity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*Tq_DPGMNDMze1Lw7CV2Mug.png" /><figcaption><a href="https://arxiv.org/pdf/2306.03089">BrainDiVE</a> results validating generation across known ROIs.</figcaption></figure><h4>A technical intuition: how does the brain guide the diffusion model?</h4><p>The subtle part of BrainDiVE is that the brain encoder expects a clean image, but diffusion generation happens through noisy intermediate latents. Early in the denoising process, the current latent (z_t) is not yet a real image. So how can we use the brain encoder to guide the generation?</p><p>BrainDiVE solves this by estimating, at each denoising step, what the final clean image might look like. In a diffusion model, the network predicts the noise in the current latent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*5a4GlRe6vLRv6F2CUXQMUg.png" /></figure><p>Using this prediction, we can estimate the clean latent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*vg984GAhO5yJTf_G6O6bug.png" /></figure><p>This is not the final image, but it is an approximation of the image that the diffusion process is currently moving toward. BrainDiVE decodes this estimated clean latent into an image-like prediction and passes it into the image-to-fMRI encoder.</p><p>The brain encoder predicts voxel-wise activity, and for a target region, BrainDiVE averages the predicted activation of the target voxels. Then it computes the gradient of this score with respect to the current diffusion latent or to the diffusion process parameters. This gradient tells the sampler or the generator how to slightly change the denoising direction so that the predicted image will activate the target region more strongly:</p><p>This is the core idea. The diffusion model still provides the natural-image prior, while the brain encoder adds a guidance signal during sampling. Instead of guiding the generation toward a text prompt or a class label, BrainDiVE guides it toward a predicted brain response.</p><h3>BrainExplore: From Generating Preferred Images to Discovering Brain Representations</h3><p>While BrainDiVE uses a known target to synthesize preferred images, <strong>BrainExplore</strong> takes a hypothesis-free direction, asking: <em>“What interpretable visual patterns exist across the visual cortex, and where are they represented?”</em></p><p>A useful motivation comes from the work <strong>A Highly Selective Response to Food in Human Visual Cortex Revealed by Hypothesis-Free Voxel Decomposition</strong>. Many classic visual neuroscience studies focus on predefined categories, such as faces, places, bodies, and words. In contrast, this work used data-driven voxel decomposition on fMRI responses to natural images. The method recovered known components, such as faces, places, bodies, and words, but also revealed a food-selective component. This is a nice example of discovery neuroscience: instead of only testing categories we already expected, the analysis exposed a meaningful response pattern that emerged from the data.</p><p>BrainExplore scales this idea into a larger automated framework. It starts from the Natural Scenes Dataset, where subjects viewed natural images from COCO while their fMRI activity was measured. To expand the image pool, BrainExplore also uses many additional COCO images that were not shown to the subjects. For these images, an image-to-fMRI encoder predicts the expected brain response. This creates a larger pool of image–fMRI pairs: some measured, some predicted.</p><p>The method can be understood in four stages.</p><p><strong>1. Decompose — </strong>Activity within predefined brain regions is broken down into candidate patterns.</p><p><strong>2. Visualize and explain.</strong><br>The images that most strongly activate each pattern are retrieved, and a vision-language pipeline generates a natural-language explanation of their shared content.</p><p><strong>3. Upscale — </strong>To scale this process, BrainExplore builds a dictionary of candidate hypotheses and automatically tests pattern-hypothesis pairs.</p><p><strong>4. Discover — </strong>High-scoring pattern-concept pairs are projected back onto the cortex, suggesting coherent functional subregions.</p><p>In this sense, BrainExplore moves beyond targeted generation. BrainDiVE uses a known target to synthesize preferred images. BrainExplore searches across many brain patterns to discover what visual concepts are represented, where they appear, and how reliable those interpretations are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7yi5JVn3oZJv8UTP.png" /></figure><p><strong>BrainExplore framework.</strong> The method starts with measured fMRI responses from NSD and expands the image pool using predicted fMRI responses for additional COCO images. It then decomposes activity within each brain region into candidate patterns. For each pattern, BrainExplore retrieves the images that activate it most strongly and uses a vision-language pipeline to explain their shared visual content. High-scoring pattern–concept pairs can then be projected back onto cortex, suggesting candidate functional subregions.</p><h3>Conclusion</h3><p>Encoding models started as prediction tools: given an image, predict the brain response. But once these models are differentiable, they become experimental tools. We can retrieve images, optimize images, guide generative models, and even search for new interpretable patterns across cortex. This changes the role of machine learning in neuroscience: it is no longer only a way to model brain activity, but also a way to design stimuli and generate hypotheses about what the visual brain represents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe9d686f0599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Deployment :) From Localhost to the World Wide Web]]></title>
            <link>https://medium.com/@reutdayan1/my-first-deployment-from-localhost-to-the-world-wide-web-f868ed225ca5?source=rss-f59fb93eab8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f868ed225ca5</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Reut Dayan]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 07:08:43 GMT</pubDate>
            <atom:updated>2026-06-04T07:08:43.702Z</atom:updated>
            <content:encoded><![CDATA[<p>There is nothing quite like the feeling of closing your laptop, pulling out your phone, typing in a real URL, and seeing the app you built staring back at you.</p><p>Recently, I deployed my first full-stack application: a platform that uses AI APIs, such as ChatGPT and Stability AI, to generate personal kids’ books.</p><p>While my app creates books, the architecture behind it is useful for many types of projects. Whether you are building an AI tool, a task manager, a dashboard, or a social app, the same basic pieces appear again and again: frontend, backend, database, file storage, CDN, domain, and deployment pipeline.</p><p>In this post, I’ll walk through the high-level architecture I used to move my React and Node.js app from local development to a live production website.</p><h3>Part 1: The Architecture — The Big Picture</h3><p>Before pushing any code, it helps to understand where each part of the application will live.</p><p>My deployment architecture uses several specialized services:</p><ul><li><strong>Frontend:</strong> React</li><li><strong>Backend:</strong> Node.js</li><li><strong>Database:</strong><a href="https://retool.com/"> Retool Database</a>, based on PostgreSQL</li><li><strong>Artifact Storage:</strong> <a href="https://aws.amazon.com/s3/">AWS S3</a></li><li><strong>CDN:</strong><a href="https://aws.amazon.com/cloudfront/"> AWS CloudFront</a></li><li><strong>Domain &amp; DNS:</strong> <a href="https://www.godaddy.com/">GoDaddy</a> + <a href="https://aws.amazon.com/route53/">AWS Route 53</a></li><li><strong>Hosting &amp; Deployment:</strong> <a href="https://render.com/">Render</a>, connected to GitHub</li></ul><p>The request flow looks roughly like this:</p><p>A user visits the website through the custom domain. The React frontend is served from Render. When the user performs an action, the frontend calls the Node.js backend. The backend handles the application logic, talks to the AI APIs, stores metadata in the database, and saves generated images or PDFs in S3. Those files are then delivered efficiently through CloudFront, using a dedicated CDN subdomain.</p><p>This separation is important. The database stores structured data, such as users, prompts, book titles, and metadata. S3 stores large generated artifacts, such as images and PDFs. CloudFront makes those artifacts faster and cleaner to access. Render runs the actual application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwIonOgeTqS4EuLAI4Ahbw.png" /></figure><h3>Part 2: Storing the Data — Retool DB</h3><p>Every app needs a place to remember users, text, and settings. For this, I used <a href="https://retool.com/">Retool Database</a>. While Retool is mostly known for building internal tools, it also provides a simple managed PostgreSQL database.</p><p>Why it’s useful for beginners: you don’t need to provision a database server yourself or deal with complicated infrastructure. You create the database, copy the connection string, and use it from your backend.</p><p>In my case, the Node.js server communicates directly with Retool DB to read and write the app’s core data.</p><h3>Part 3: Handling Images &amp; Files — AWS S3</h3><p>Databases are great for structured text data, but they are not ideal for storing large files like AI-generated illustrations or PDFs. For this, I used <a href="https://aws.amazon.com/s3/">AWS S3</a>.</p><p>S3 is a cloud storage service where you create a “bucket,” which acts like a dedicated storage container for your files.</p><p>In my app, each generated book has a unique bookId. Inside S3, I store all the images and files for that specific book under a path with the same bookId.</p><p>For example, the S3 structure can look like this:</p><pre>kids-books-prod/<br>  book_12345/<br>    cover.jpg<br>    page-1.jpg<br>    page-2.jpg<br>    page-3.jpg<br>    book.pdf</pre><p>Then, in Retool DB, I store the book metadata together with a reference to that S3 path:</p><pre>bookId: book_12345<br>title: The Magic Forest<br>s3Directory: book_12345/</pre><p>This way, the database does not store the images themselves. It only stores the information needed to find them. When the user opens a specific book, the backend reads the book record from the database, gets the matching bookId, and knows where to load the images from in S3.</p><p>A very important security note: the S3 bucket should stay private. Users should not access the bucket directly. Instead, CloudFront should sit in front of S3 and serve the files publicly in a controlled way.</p><p>To let the backend upload files securely, I created an <a href="https://aws.amazon.com/iam/?nc1=f_m">IAM</a> user with limited permissions for the specific S3 bucket. Then, I stored the AWS access key and secret key as environment variables. You should never use your AWS root account keys inside an application, and you should never commit AWS keys to GitHub.</p><h3>Part 4: Delivering Artifacts Fast — CloudFront, Route 53, and GoDaddy</h3><p>After storing files in S3, the next question is: how should users access them?</p><p>Technically, you can generate S3 URLs, but that is usually not the best production setup. A better approach is to put CloudFront in front of S3.</p><p>CloudFront is a CDN, or Content Delivery Network. It caches and serves files from locations closer to the user, which can make images and PDFs load faster. It also gives you a cleaner and more professional way to serve generated artifacts.</p><p>In my setup, the S3 bucket stores the files privately, and CloudFront is the public layer that delivers them to users.</p><p>I also wanted to use my own domain instead of default service URLs. I bought the domain through GoDaddy, but buying a domain is only the first step. A domain registrar, like GoDaddy, lets you own the domain name. But you still need DNS settings that tell the internet where each part of the domain should point.</p><p>That is where Route 53 comes in.</p><p>Route 53 is AWS’s DNS service. It lets you create records such as:</p><ul><li>kidstorygen.com → points to the main app hosted on Render</li><li>cdn.kidstorygen.com → points to CloudFront for images and PDFs</li></ul><p>For example, an image may be stored internally in S3 under a key like:</p><pre>book_12345/cover.jpg</pre><p>But the user does not need to know anything about S3. Instead, the app can load it through the CDN URL:</p><pre>https://cdn.kidstorygen.com/book_12345/cover.jpg</pre><p>So the database stores the book metadata and the S3 path, S3 stores the actual files, and CloudFront provides the fast public URL used by the frontend.</p><p>To use Route 53 with a domain purchased on GoDaddy, I created a hosted zone in Route 53. AWS gave me a set of nameservers, and I copied those nameservers into the GoDaddy domain settings. This tells GoDaddy: “AWS Route 53 is now responsible for managing the DNS records for this domain.”</p><p>After that, I could manage the domain routing from Route 53.</p><p>This part was one of the most confusing for me at first: GoDaddy is where I bought the domain, but Route 53 is where I manage where the domain actually points.</p><h3>Part 5: The Magic of Deployment — Render, Docker, and GitHub</h3><p>Finally, I needed a place to run the React frontend and Node.js backend. For this, I used Render.</p><p><a href="https://render.com/">Render</a> connects directly to GitHub. Every time I push new code, Render can automatically rebuild and redeploy the app. This gives me a simple CD workflow: every push to GitHub triggers a new deployment. You can extend this into full CI/CD by adding tests and checks before deployment.</p><p>When running the app locally, I know exactly what commands to run in the terminal: how to install dependencies, how to build the project, and how to start the server. But once the app moves to Render, Render also needs these instructions.</p><p>That is where Docker comes in.</p><p>Docker lets me define, in one file, how the app should be prepared and started. Instead of manually telling Render what to do step by step, I describe the environment and commands inside a Dockerfile.</p><p>What is Docker? Imagine packing your app, its dependencies, and its runtime environment into a single standardized container. This helps avoid the classic problem of: “It works on my computer, but not on the server.”</p><h4>The Container Blueprint: Dockerfile</h4><p>The Dockerfile tells Render how to build and run the app.</p><p>Here is the Dockerfile I used:</p><pre># Start with a specific, stable version of Node.js<br>FROM node:18.16.1-bullseye<br># Create and set the main working directory<br>WORKDIR /app<br><br># Copy your specific project folders into the container<br>COPY server ./server<br>COPY client ./client<br># Move into the server directory to run commands<br>WORKDIR /app/server<br># Install dependencies and build the project<br>RUN yarn install<br>RUN yarn build<br># Expose the port your app runs on<br>EXPOSE 4001<br># Start the application<br>CMD [&quot;yarn&quot;, &quot;start&quot;]</pre><h3>Part 6: Security on Render — Environment Variables</h3><p>When developing locally, I used a .env file to store private values such as database connection strings, AI API keys, and AWS credentials.</p><p>But the .env file should never be committed to GitHub.</p><p>To keep secrets safe:</p><ol><li>Add .env to .gitignore.</li><li>Store production secrets directly in Render’s Environment tab.</li><li>Read those values from process.env in the Node.js server.</li><li>Never expose private keys in frontend code.</li></ol><p>This is especially important for AI API keys, database URLs, and AWS credentials. The frontend runs in the user’s browser, so anything bundled into frontend code should be treated as public.</p><p>The backend is the safe place to use private keys.</p><h3>Conclusion</h3><p>Deploying my first full-stack app made the web feel much less mysterious.</p><p>At first, all the pieces — frontend, backend, database, S3, CDN, DNS, Docker, and environment variables — sounded like a lot. But once I understood the role of each service, the architecture started to make sense.</p><p>The biggest thing I learned is that deployment is not one huge step. It is a collection of small connections: connecting the app to a database, connecting file storage to a CDN, connecting a domain to the right service, and connecting GitHub to deployment.</p><p>And honestly, seeing my app move from localhost to a real URL was worth all the debugging along the way :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f868ed225ca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Brain Scans to Encoding Models: A Beginner’s Guide to fMRI for Machine Learning]]></title>
            <link>https://medium.com/@reutdayan1/from-brain-scans-to-encoding-models-a-beginners-guide-to-fmri-for-machine-learning-d73dc484eaae?source=rss-f59fb93eab8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73dc484eaae</guid>
            <category><![CDATA[encoding-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fmri]]></category>
            <dc:creator><![CDATA[Reut Dayan]]></dc:creator>
            <pubDate>Wed, 20 May 2026 12:50:27 GMT</pubDate>
            <atom:updated>2026-05-20T13:03:23.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning researchers are increasingly using fMRI data to study how the brain responds to images, videos, language, and other natural stimuli. But before treating brain activity as a prediction target, it is important to understand what fMRI actually measures, how the data is represented, and what it means to predict a brain response.</p><h3>How the Brain Is Digitized</h3><p>MRI data represent the brain as a three-dimensional grid of small spatial units called <strong>voxels</strong>. A voxel is the 3D equivalent of a pixel: while a pixel corresponds to a small location in a 2D image, a voxel corresponds to a small cube in 3D brain space.</p><p>In practice, an MRI scanner measures the brain slice by slice. Each slice is a 2D image, and stacking these slices together forms a 3D volume. This volume is not a continuous representation of the brain, but a discretized one: each voxel stores one measured value from a small region of brain tissue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L17I542tSb9OhjfnIOWdeA.png" /><figcaption><a href="https://home.csulb.edu/~cwallis/482/fmri/fmri.html">https://home.csulb.edu/~cwallis/482/fmri/fmri.html</a></figcaption></figure><h3>Anatomical MRI: High Spatial Resolution</h3><p>Before talking about brain activity, it is useful to understand anatomical MRI. An anatomical, or structural, MRI scan is designed to capture the physical structure of the brain in high spatial detail.</p><p>Compared to fMRI, anatomical MRI is usually acquired at a much higher spatial resolution. A common structural scan may have voxels of about <strong>1 × 1 × 1 mm a</strong>nd takes<strong> ~5 minutes</strong> for one scan, producing a detailed 3D image of the brain. However, this scan is essentially <strong>static</strong>: it tells us what the brain looks like, not how its activity changes over time.</p><h3>Adding Time: Why fMRI Sacrifices Spatial Resolution</h3><p>Functional MRI extends this voxel-based representation by measuring the brain repeatedly over time. Instead of acquiring one detailed static volume, fMRI acquires a sequence of brain volumes — so we can measure the brain in action.</p><p>The time between two consecutive full-brain measurements is called the <strong>repetition time</strong>, or <strong>TR</strong>. In many fMRI experiments, the TR is around one to two seconds, meaning that we get a new 3D brain volume every few seconds.</p><p>This creates a fundamental tradeoff. To measure activity over time, the scanner must acquire full-brain volumes quickly. As a result, fMRI usually uses larger voxels than anatomical MRI, often around <strong>3 × 3 × 3 mm voxel size</strong>.</p><p>So while anatomical MRI gives us a high-resolution picture of brain structure, fMRI gives us a lower-resolution but dynamic measurement of brain activity.</p><p>This is the basic spatial–temporal tradeoff: <strong>smaller voxels require slower scans, while faster scans usually require larger voxels</strong>. fMRI prioritizes tracking changes over time rather than capturing fine anatomical detail.</p><h3>What Does a Voxel Actually Measure?</h3><p>The brain processes information through the activity of neurons. Neurons communicate using fast electrical signals, often called <strong>spikes</strong>, which occur on the scale of milliseconds. These signals are the basis of neural computation, but they are not what fMRI measures directly.</p><p>fMRI is much slower and much coarser. Each voxel covers a small 3D region of brain tissue, but that region can contain many neurons, blood vessels, glial cells, and other supporting tissue. As a result, the value measured in a voxel is not the activity of a single neuron. It is an aggregate signal from a local population of tissue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*GOPSy61X7vy--LRv0E3rzA.png" /><figcaption>Each fMRI voxel contains many neurons; the measured signal is therefore an aggregate response from a small region of brain tissue, not the activity of a single neuron. Generated using ChatGPT.</figcaption></figure><p>What fMRI actually measures is the <strong>BOLD signal</strong>, short for <strong>Blood-Oxygen-Level Dependent signal</strong>. When neurons in a region become more active, they consume oxygen. In response, the brain sends more oxygenated blood to that area. This changes the local magnetic properties of the tissue, because oxygenated and deoxygenated blood behave differently in a magnetic field. The MRI scanner detects these changes.</p><h3>From Raw fMRI to Model-Ready Responses</h3><p>The BOLD signal does not appear immediately after neural activity. Instead, it follows a delayed response curve called the <strong>Hemodynamic Response Function</strong> (HRF): the signal rises a few seconds after the stimulus, reaches a peak, and then slowly returns to baseline.</p><p>In many fMRI analyses, this delay is modeled using a standard, or <strong>canonical</strong>, HRF. Rather than using the raw BOLD time series directly, researchers often estimate a response strength for each voxel and each stimulus. This estimated response is usually called <strong>beta</strong> (β).</p><p>Practically, these beta values are often the brain-activity values used in machine learning datasets. Many fMRI datasets publish preprocessed beta responses, where each stimulus is paired with a vector of voxel-wise beta values. In image-to-fMRI encoding models, this is usually the value we try to predict: given an image, predict the beta response it evoked in each voxel.</p><p>Before reaching this stage, raw fMRI data must be preprocessed. This usually includes correcting for head motion, aligning functional scans to anatomical MRI, adjusting timing differences between slices, filtering noise, and sometimes normalizing the brain to a common space.</p><p>The result is a cleaner, model-ready representation of brain activity: either voxel-wise time series or, more commonly for stimulus-based encoding models, stimulus-level beta responses.</p><h3>Regions of Interest</h3><p>A full fMRI response can contain tens of thousands, and sometimes more than 100,000, voxel values. For many research questions, however, we are not equally interested in every voxel in the brain. If we study visual perception, for example, we may care mostly about visual cortex. If we study face processing, we may focus on face-selective regions.</p><p>This is where <strong>regions of interest</strong>, or <strong>ROIs</strong>, become useful. An ROI is a subset of voxels that are grouped together because they belong to a meaningful anatomical or functional region. Examples include early visual cortex, face-selective regions, body-selective regions, word-selective regions, and scene-selective regions.</p><p>For machine learning, ROIs are useful for both practical and interpretability reasons. They reduce the dimensionality of the prediction target, improve the signal-to-noise ratio by focusing on relevant voxels, and make the results easier to interpret. Instead of asking whether a model predicts activity across the entire brain, we can ask a more specific question: how well does it predict activity in a region related to faces, places, words, or visual processing?</p><p>In this way, ROIs turn the full voxel space into a more meaningful subspace for analysis.</p><h3>The Natural Scenes Dataset: Image–fMRI Pairs at Scale</h3><p>The <a href="https://naturalscenesdataset.org/"><strong>Natural Scenes Dataset (NSD)</strong> </a>is one of the most important datasets for studying how the human brain responds to natural images. In NSD, participants viewed thousands of color natural scenes while their brain activity was recorded with high-resolution <strong>7T fMRI</strong>. Here, <strong>7T</strong> means <strong>7 Tesla</strong>, referring to the magnetic field strength of the scanner. NSD was acquired with whole-brain 7T fMRI at 1.8 mm resolution and 1.6 s TR.</p><p>The dataset includes <strong>8 participants</strong>, each viewing around <strong>9,000–10,000 distinct natural images</strong> over <strong>30–40 scan sessions</strong>. Across repeated presentations, this corresponds to roughly <strong>22,500–30,000 trials per participant</strong>.</p><p>The useful structure of NSD is that it connects each image to the fMRI response it evoked in a specific subject. After preprocessing, these responses are often represented as voxel-wise beta values: for each image, we get a vector of estimated activity values across voxels. This creates a practical dataset of paired examples: <strong>image → voxel-wise fMRI response</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbGMhZLPC82okhmwMaXxkA.png" /><figcaption>Generated using ChatGPT.</figcaption></figure><p>NSD also provides ROI masks, which allow researchers to focus on specific brain regions instead of using all voxels. These masks may come from anatomical definitions or from functional localizer experiments, where subjects view categories such as faces, bodies, places, or words. Voxels that respond more strongly to a category can be grouped into a corresponding ROI, producing subject-specific masks for meaningful brain regions.</p><h3>Encoding Models</h3><p>An <strong>encoding model</strong> learns to predict brain activity from an external stimulus. In the visual setting, the input is usually an image, and the output is the fMRI response evoked by that image.</p><p>After preprocessing, this response is often represented as a vector of voxel-wise beta values. So the learning problem can be written simply as: <strong>image → predicted voxel responses</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcqfpuLm8c_v5JBMBd3tCQ.png" /><figcaption>Generated using ChatGPT.</figcaption></figure><h3>CLIP2Brain: A Modern Encoding Model</h3><p>A modern example of an image-to-fMRI encoding model is <a href="https://www.nature.com/articles/s42256-023-00753-y"><strong>CLIP2Brain</strong></a>. The main idea is to use representations from a pretrained vision-language model, such as CLIP, as features for predicting brain activity.</p><p>Instead of training an image encoder from scratch, CLIP2Brain passes each image through a pretrained CLIP vision model. This produces a high-level image embedding, which is then mapped to voxel-wise fMRI responses using a simple prediction head, such as a linear layer or a small MLP.</p><p>The pipeline is: <strong>image → CLIP image embedding → prediction head → fMRI response</strong></p><p>In this setup, the CLIP image encoder is kept <strong>frozen</strong> and used only as a feature extractor. The part trained on fMRI data is the prediction head, which learns the mapping from CLIP embeddings to brain responses. The CLIP2Brain paper explores several design choices, including different CLIP backbones, dataset sizes, and prediction-head architectures. A main finding is that CLIP-based visual representations show strong alignment with brain responses, suggesting that features learned by modern vision-language models are useful for predicting activity in the human visual cortex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtyPEDJCkt5-kbfiD63ZPA.png" /><figcaption>Generated using ChatGPT.</figcaption></figure><h3>TRIBE v2: Extending Encoding Models to Video, Audio, and Text</h3><p>While CLIP2Brain focuses on static images, many real-world experiences are dynamic and multimodal. A movie, for example, contains visual motion, sound, spoken language, and temporal context. <a href="https://ai.meta.com/blog/tribe-v2-brain-predictive-foundation-model/"><strong>TRIBE v2</strong> </a>extends the encoding-model idea to this more natural setting by predicting fMRI responses from <strong>video, audio, and text</strong>. The released model combines feature extractors for text, video, and audio into a unified Transformer architecture that maps multimodal representations onto the cortical surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*5g1TSy3WMxh1_RVVzwR6EQ.png" /><figcaption>From <a href="http://medium.com/r?url=https%3A%2F%2Fai.meta.com%2Fblog%2Ftribe-v2-brain-predictive-foundation-model%2F">TribeV2’s paper.</a></figcaption></figure><p>Conceptually, the difference is simple: CLIP2Brain asks how the brain responds to an image, while TRIBE v2 asks how the brain responds to a temporally evolving stimulus. Instead of producing one response per image, TRIBE v2 predicts a sequence of brain responses over time. In the released model, predictions are for an “average” subject and are represented on the fsaverage5 cortical mesh, with around 20k vertices.</p><p>This makes TRIBE v2 especially interesting for studying naturalistic perception. The paper presents TRIBE v2 as a tri-modal foundation model of vision, audition, and language, trained on a unified dataset of over <strong>1,000 hours of fMRI</strong> across <strong>720 subjects</strong>.</p><p>Possible pipeline sentence: <strong>video / audio / text → modality-specific features → temporal Transformer → predicted fMRI response</strong></p><h3>Evaluating Encoding Models</h3><p>After training an encoding model, we need to compare its predicted brain responses with the measured fMRI responses on held-out data. The most common evaluation is done voxel by voxel, or ROI by ROI: for each voxel, we compare the predicted response across test stimuli to the measured response across the same stimuli.</p><p>A common metric is <strong>Pearson correlation</strong>. It measures whether the predicted and measured responses vary together across stimuli. This is useful because it focuses on the shape of the response pattern and is less sensitive to scale differences.</p><p>Another common metric is <strong>R²</strong>, or coefficient of determination. R² measures how much variance in the measured response is explained by the model. Unlike correlation, it is sensitive to scale and bias, so a model can have good correlation but worse R² if its predictions are systematically too large, too small, or shifted.</p><p>One important concept in fMRI evaluation is the <strong>noise ceiling</strong>. fMRI measurements are noisy, and even repeated presentations of the same stimulus do not produce exactly identical responses. Because of this, there is an upper bound on how well any model can predict the measured data. The noise ceiling estimates this upper bound, often using response reliability across repeated trials or subjects.</p><p>This means that a numerically “low” score is not always a bad result. If the model approaches the noise ceiling, it may already be close to the best performance possible given the noise in the data. For this reason, encoding-model performance should be interpreted relative to the reliability of the measured fMRI responses, not only by the raw metric value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SW9kNgcFOnXxXrgw59Oxtw.png" /><figcaption>From <a href="https://www.nature.com/articles/s42256-023-00753-y">Clip2Brain’s paper.</a></figcaption></figure><h3>Conclusion</h3><p>fMRI data gives us a fascinating way to study how the brain responds to natural stimuli, but it is important to remember what this data really represents. It is not a direct recording of individual neurons, but a voxel-wise, indirect, and noisy measurement of brain activity through the BOLD signal. After preprocessing, this signal can be transformed into practical targets for machine learning, such as voxel-wise beta values or ROI-level responses.</p><p>Encoding models build on this representation by learning mappings from stimuli — images, videos, audio, or text — to predicted brain responses. Models such as CLIP2Brain show how pretrained visual representations can be used to predict responses to images, while models such as TRIBE v2 extend this idea to richer, naturalistic, multimodal stimuli.</p><p>This blog is meant to be a <strong>high-level quick start</strong> for ML researchers who want to begin working with fMRI data. Many important details are simplified here, including MRI physics, preprocessing pipelines, statistical modeling, ROI definitions, and evaluation protocols. The goal is not to cover the entire field, but to build the basic mental model needed to understand image-to-fMRI and multimodal encoding models.</p><p>Personally, I am very passionate about this research direction, especially the connection between generative models and brain activity. I am particularly interested in generating stimuli, or optimizing images and videos, to maximize predicted activity in specific brain regions or ROIs. I believe this direction can become a powerful tool for studying what different brain regions represent and how modern machine learning models can help us explore brain function.</p><p>Feel free to reach out:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73dc484eaae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlling Diffusion Models: From Guidance to Customization]]></title>
            <link>https://medium.com/@reutdayan1/controlling-diffusion-models-from-guidance-to-customization-4d4a2ef30b70?source=rss-f59fb93eab8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d4a2ef30b70</guid>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[controlling]]></category>
            <category><![CDATA[guidance]]></category>
            <dc:creator><![CDATA[Reut Dayan]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 20:31:51 GMT</pubDate>
            <atom:updated>2025-06-12T20:31:51.454Z</atom:updated>
            <content:encoded><![CDATA[<p>Diffusion models have quickly become a cornerstone of generative AI. They power some of the most impressive image generation capabilities, producing anything from realistic portraits to imaginative visual concepts. Recently, much of the focus has shifted toward how we can control, personalize, and fine-tune these models to better suit real-world needs..</p><p>In this post, we’ll walk through the evolution of diffusion — from classifier-guided models to guidance-free approaches — and explore the fine-tuning methods that give these models their creative flexibility.</p><h3>What are Diffusion Models?</h3><p>At their core, diffusion models learn to generate data by reversing a gradual noising process.</p><ul><li><strong>Forward process</strong>: Noise is incrementally added to a clean image until it becomes nearly pure noise.<br>At each step <em>t</em>, the model adds a small amount of noise to the original image <em>x_0</em>, producing a noisier version called<em> x_t</em>. This process follows a fixed noise schedule and is described by the equation:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIhCGX2w2MvbpA-JPMUAfQ.png" /><figcaption><strong>Visualizing the Forward Process</strong>: Starting from a clean image, noise is incrementally added over multiple steps until the image becomes indistinguishable from random noise.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*S-PJVe9MdOmLfzYCtE7RIA.png" /><figcaption><strong>Forward Process Equation</strong>: Defines how noise is added at each timestep, gradually transforming the image into pure noise according to a variance schedule α_t.</figcaption></figure><p>Where <strong>αₜ</strong> (alpha) is a variance schedule that controls the amount of noise added at each timestep.<br>It typically <strong>decreases exponentially from 1 to 0</strong>, ensuring that the image gradually transitions into pure noise as time progresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6u9FLg2SjhknjgqsceBbnw.png" /><figcaption><strong>Noise Schedule</strong>: The left plot shows the variance schedule β_t, and the right shows the cumulative image preservation factor αˉt, which decays as noise accumulates over time.</figcaption></figure><ul><li><strong>Reverse process</strong>: To reverse the noising process, we need a model that can accurately <strong>predict the noise</strong> added at each step. In practice, this prediction is performed by a neural network, most commonly, a <strong>U-Net</strong> architecture. This approximation is used to denoise <em>x_t​</em> and gradually reconstruct the original image <em>x_0</em>. The model learns to approximate the added noise at each timestep t using: <em>ϵ_θ(x_t,t) ≈ noise added at step t.</em><br>Below is a typical U-Net structure used in diffusion models, which captures both local details and global context through downsampling and upsampling paths.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/0*u7u7yk-VPKrUsb0G.png" /><figcaption><strong>U-Net Architecture</strong>: A typical UNet structure used in diffusion models, combining convolutional, residual, and attention layers. <a href="https://medium.com/data-science/diffusion-model-from-scratch-in-pytorch-ddpm-9d9760528946">link</a></figcaption></figure><p>The U-Net receives the noisy image<em> x_t​ </em>and the current timestep t as inputs and outputs the estimated noise <em>ϵ_θ</em>, guiding the model backward toward the clean image. Crucially, the architecture includes <strong>self-attention blocks</strong>, where each pixel can attend to all other pixels in the image. This allows the model to capture <strong>long-range dependencies</strong>, ensuring coherence in complex scenes and enabling detailed global understanding during the denoising process.</p><p>To train the U-Net, we use a <strong>reconstruction loss </strong>between the actual noise that was added and the predicted noise<em> ϵ_θ(x_t,t)</em>. This loss encourages the network to learn how to accurately remove the noise during sampling.</p><ul><li><strong>Sampling</strong>: Once trained, the diffusion model can generate new images from pure noise. Starting from a random sample <em>x_T∼N(0,I),</em> the model applies the reverse denoising steps iteratively, each time using <em>ϵ_θ(x_t,t)</em> to remove a small amount of noise. This sequence continues until we obtain a clean image <em>x_0</em> that resembles data from the training distribution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Ojip2zzBSiIrHpjHHX84BQ.png" /><figcaption><strong>Sampling Process</strong>: Starting from noise, the model iteratively denoises using a U-Net to generate the final image x_0. <a href="https://codoraven.com/blog/ai/stable-diffusion-clearly-explained/">link</a></figcaption></figure><h3><strong>From Guided to Guidance-Free: The Evolution of Diffusion</strong></h3><h4>Classifier-Guided Diffusion</h4><p>So far, we’ve seen how diffusion models gradually remove noise to generate images. But how do we steer this process toward generating a specific type of image — say, a cat or a dog?</p><p>One approach is <strong>classifier guidance</strong> (Dhariwal &amp; Nichol, 2021). We take a pretrained image classifier and use it during sampling to nudge the diffusion process toward images that the classifier thinks belong to a desired class.</p><p>This is done by computing the gradient of the classifier’s output with respect to the image, and using that gradient to slightly adjust the noisy image at each step, effectively pulling the sample in the direction of the target class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tz0YUy6ijdVxSfcYxBNB4A.png" /><figcaption><strong>Classifier Guidance</strong>: At each denoising step, the diffusion model prediction is combined with the gradient from a classifier to steer generation toward a target class.</figcaption></figure><p>Instead of removing only the predicted noise, we modify the reverse step to also consider the <strong>gradient of the log-probability</strong> of the desired class y with respect to the noisy image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhyY52yWoCTgWMkOIe-Rhg.png" /></figure><blockquote><em>📝 </em><strong><em>Note</em></strong><em>: The classifier used for guidance must be trained to predict the correct class </em><strong><em>given a noisy image</em></strong><em>, not just a clean one. This ensures it can provide meaningful gradients throughout the entire denoising process.</em></blockquote><h4>Classifier-Free Guidance</h4><p>We’ve seen how we can guide the diffusion process using an external classifier. But this approach has a downside — it requires a separate, pretrained classifier that matches the diffusion model’s data distribution. It also adds complexity and slows things down.</p><p>That leads us to a smarter alternative: <strong>Classifier-Free Guidance</strong> (Ho &amp; Salimans, 2022). Instead of relying on an external classifier, we train the diffusion model itself to handle both <em>conditional</em> (e.g., text-to-image) and <em>unconditional</em> generation, <strong>using the same U-Net</strong>.</p><p><strong>How does it work?</strong></p><p>During training, the model randomly drops the text conditioning in a fraction of the training examples. This way, it learns to denoise both with and without guidance. The conditioning itself is implemented by:</p><ul><li><strong>Encoding the text prompt</strong> (typically using a transformer encoder like CLIP’s text encoder),</li><li>Then, injecting the encoded text into the U-Net using <strong>cross-attention layers</strong>, which are inserted <em>in place of or alongside</em> self-attention blocks in the network.</li></ul><p>In each cross-attention layer, the image features act as <strong>queries</strong>, and the text embedding provides <strong>keys and values</strong>. This allows each spatial location in the image to “attend to” the relevant words in the prompt, helping the model align visual output with the input text.</p><p>This is illustrated in the figure below, where the denoising U-Net uses attention modules to blend image and text information through cross-attention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPNhmhu9I2SIpwYAMOWKUg.png" /><figcaption><strong>Classifier-Free Guidance</strong>: The U-Net uses cross-attention layers to condition the denoising process on text or other inputs.</figcaption></figure><p>At inference time, we generate two versions of the model output: one with the prompt (conditional) and one without (unconditional).</p><p>Then, we <strong>blend</strong> them using a guidance strength parameter w to increase adherence to the prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*n0ZhGQqJgW4tIVcCTjh3Gw.png" /></figure><blockquote><em>📝 </em><strong><em>Note</em></strong><em>: So far, we’ve discussed diffusion as if it’s applied directly on pixel-space images. However, in most modern models — like </em><strong><em>Stable Diffusion</em></strong><em> — the diffusion process doesn’t operate on full-resolution images, but instead on </em><strong><em>compressed latent representations</em></strong><em>. To achive this, a pretrained </em><strong><em>encoder-decoder</em></strong><em> is used. This enables high-quality generation with significantly lower computational cost.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJsC0pgw78XnooTOPQAziA.png" /><figcaption><strong>Latent Diffusion</strong>: Instead of applying diffusion directly to images, the model operates in a compressed latent space.</figcaption></figure><h3><strong>Challenges in Diffusion Generation</strong></h3><p>Even with powerful guidance techniques like <strong>classifier-free guidance</strong>, diffusion models still face challenges when it comes to <strong>precise control</strong>.<br> They’re excellent at capturing style, texture, and overall visual coherence, but they often fall short on tasks that require structure, accuracy, or spatial reasoning.</p><p>For example, if we prompt the model with <em>“three apples on a plate”</em>, we might end up with five. Or if we ask for <em>“a red car next to a tree”</em>, the model could easily jumble the layout, placing the car in front of or even inside the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZpx-hLpBlLf8QpQQUWDrw.png" /><figcaption>Examples of the diffusion process chalnges. Generated using SDXL.</figcaption></figure><p>These limitations highlight the need for <strong>stronger control mechanisms</strong> — methods that go beyond prompt guidance and allow us to directly influence <strong>what</strong> the model generates.</p><p>In the next section, we’ll explore several powerful approaches that tackle this challenge:</p><ul><li><strong>LoRA</strong>: Efficiently fine-tune attention layers for new styles or domains.</li><li><strong>Token Optimization</strong>: Learn new textual tokens that represent visual concepts.</li><li><strong>Test-Time Training</strong>: Adjust the latent image using gradient-based feedback.</li><li><strong>Reinforcement Learning</strong>: Optimize generation using reward signals over time</li></ul><h3><strong>Control Mechanisms</strong></h3><h4>LoRA (Low-Rank Adaptation)</h4><p>One powerful way to control generation is to <strong>fine-tune the diffusion model</strong>, but <strong>full fine-tuning</strong> is often <strong>computationally expensive</strong> and prone to overfitting, especially when working with limited data or resources.</p><p><strong>LoRA (Low-Rank Adaptation)</strong> offers a smarter alternative by <strong>injecting small trainable low-rank matrices</strong> into the model’s <strong>attention layers</strong>, which are the most expressive parts of the network. During training, only these inserted matrices are updated while the original model weights remain <strong>frozen</strong>.</p><p>This makes LoRA particularly effective for <strong>Domain adaptation</strong> (e.g., adapting a model to anime, medical, or satellite imagery) or <strong>Style-specific generation</strong> (e.g., fashion, branding), where fast fine-tuning on a small dataset is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*FZu7Yz74yLNNB2dymtXh0g.png" /><figcaption>Instead of updating the full attention weight matrix W, LoRA learns two much smaller matrices (A, B).</figcaption></figure><h4><strong>Token Optimization</strong></h4><p>Another elegant way to control and personalize diffusion models is through <strong>token optimization</strong>. Instead of fine-tuning the model’s weights, we optimize new <strong>text embeddings</strong> that correspond to new visual concepts, allowing the model to generate custom content using just a new token.</p><p>A prime example of this approach is the method introduced in the paper <a href="https://arxiv.org/pdf/2208.01618"><strong>“An Image is Worth One Word: Personalizing Text-to-Image Generation using Textual Inversion”</strong></a>. The idea is simple yet powerful:<br> You define a new placeholder token — let’s say “S*” — and optimize its embedding so that when used in prompts like <em>“a photo of S*”</em>, the diffusion model generates images of your specific concept.</p><p>Importantly, the <strong>rest of the model remains frozen</strong>. Only the new token embedding​ is trained, using a reconstruction loss that encourages the generated image to match the original concept. The optimization objective is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*PNeseAdMcsU7Nx0c5gwg8Q.png" /></figure><p>The figure below illustrates this process: the input concept is tokenized, with the placeholder “*” replaced by a learnable embedding. This embedding is optimized so that, when used in conjunction with the rest of the prompt, it enables the generator to reconstruct the original visual concept through the denoising process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dh1gH04wKNyxOCB5z1P8vA.png" /><figcaption>The training process of <strong>Textual Inversion</strong>, where we optimize a new token embedding to represent a <strong>specific visual concept.</strong></figcaption></figure><p>The process starts with a small number of input images (e.g., 3–5) of the new concept. These images are passed through the <strong>forward diffusion process</strong>, where Gaussian noise is gradually added over multiple steps until the image becomes fully corrupted. At the same time, a <strong>prompt</strong> is constructed — typically in the format <em>“a photo of S*”</em>, where <em>S*</em> is a <strong>placeholder token</strong> representing the concept we want to learn. This placeholder token is initialized with a random embedding v* and treated as a <strong>learnable parameter</strong>. This prompt is used to guide the denoising U-Net, which tries to predict the noise that was originally added to the clean image. The predicted noise is compared with the actual noise that was added, using a <strong>reconstruction loss</strong>. The <strong>only</strong> trainable parameter is the token embedding <em>v*</em>, which is optimized to minimize this loss.</p><p>By optimizing <em>v*</em> in this way, we effectively teach the model what <em>S*</em> should represent, without modifying the model’s weights. Once trained, this new token can be reused in diverse prompts to generate images of the concept in new compositions and contexts.</p><h4>Test-Time Training</h4><p><strong>Test-Time Training </strong>is referred to as optimization that happens <strong>during inference</strong>. In this setting, the diffusion model remains <strong>frozen</strong>, and instead, we perform on-the-fly updates, usually to the latent image representation, based on a loss computed at test time.</p><p>After each denoising step, where the U-Net predicts the noise and updates the image accordingly, a loss is computed using <strong>external feedback</strong>, such as a classifier score, CLIP similarity, aesthetic metric, or any other differentiable reward.<br> This loss is then <strong>backpropagated</strong>, and a <strong>gradient update</strong> is applied directly to the noisy latent image.</p><p>The goal is to <strong>iteratively refine the generation during sampling</strong>, steering it in real time toward a user-defined objective, especially in cases where the original prompt or model alone may not be sufficient for precise control.</p><h4><strong>Fine-Tuning with RL</strong></h4><p>While most fine-tuning methods rely on supervised signals or reconstruction loss, recent work has shown that <strong>reinforcement learning (RL)</strong> can be used to fine-tune diffusion models based on high-level feedback, such as human preferences or scoring functions that are not differentiable and cannot be backpropagated through directly.</p><p>A prime example of this is the paper <a href="https://arxiv.org/pdf/2302.12192"><strong>“Aligning Text-to-Image Models using Human Feedback”</strong></a>, which proposes a full pipeline to align generative models with human intent:</p><ol><li><strong>Collect human feedback</strong> on model outputs generated from diverse prompts. Annotators assess which images best match the text.</li><li><strong>Train a reward model</strong> on this human-labeled dataset. The reward function learns to predict human preferences given a text prompt and a generated image.</li><li><strong>Fine-tune the diffusion model</strong> by maximizing a <strong>reward-weighted log-likelihood</strong> — that is, prioritizing image generations that receive higher predicted human approval.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7VmaHx3VOUC0qKCLO98BA.png" /><figcaption><strong>Training with Human Feedback</strong>: The model collects user preferences on generated images, trains a reward model to predict this feedback, and fine-tunes the diffusion model using reward-weighted likelihood to align outputs with human intent.</figcaption></figure><blockquote><em>📝 </em><strong><em>Note</em></strong><em>: This approach for training a reward model mirrors what’s used in large language models (LLMs), where </em><strong><em>reinforcement learning from human feedback (RLHF)</em></strong><em> trains a reward model to guide language generation toward preferred or helpful outputs.</em></blockquote><h3>Conclusion</h3><p>Controlling diffusion models is a growing and essential area of research. In this post, we explored just a few of the many emerging methods, ranging from classifier and classifier-free guidance to more advanced techniques like LoRA, token optimization, test-time training, and reinforcement learning.</p><p>These approaches highlight how we can move beyond simple prompts and give users more direct, flexible, and powerful control over what gets generated. Of course, this is far from an exhaustive list — new methods are constantly being developed to improve precision, alignment, and personalization in diffusion-based generation.</p><p>As the field evolves, the challenge isn’t just generating high-quality images — it’s generating the <em>right</em> ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d4a2ef30b70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graph Transformer]]></title>
            <link>https://medium.com/@reutdayan1/graph-transformer-2ede65db4658?source=rss-f59fb93eab8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ede65db4658</guid>
            <category><![CDATA[positional-encoding]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[graph-transformer]]></category>
            <dc:creator><![CDATA[Reut Dayan]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 11:39:24 GMT</pubDate>
            <atom:updated>2024-06-25T12:07:07.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Transformers — a tremendous success in the field of natural language processing (NLP). They are currently the best-performing neural network architectures for handling long-term sequential data.</p><p>Transformers excel at processing sequential data, but can they achieve similar success with graph data? We will explore this idea in this blog post.</p><h3>What is a Transformer?</h3><p>Imagine you’re reading a sentence. Your understanding of each word relies not only on the word itself but also on the context provided by other words in the sentence. Transformers mimic this process by assigning weights to each word in a sequence, emphasizing the words that are most relevant for understanding the context of a given word.</p><p>Another powerful feature of Transformers is their ability to process all words in a sentence simultaneously rather than one at a time. This parallel processing allows Transformers to capture complex dependencies between words more efficiently, significantly speeding up training and inference compared to traditional sequential models.</p><p>In this blog, I’ll delve into two main components of the Transformer architecture: Attention and Positional Encoding. For other reference on transformers read <a href="https://omrikaduri.github.io/2022/10/22/From-N-grams-to-CodeX-Part-2.html">this blog</a> post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*PCPPVL4zVCNd-49NmZ8bZg.png" /><figcaption>The Transformer architecture presented in the paper: <a href="https://arxiv.org/pdf/1706.03762">“Attention is All You Need”</a></figcaption></figure><h4>Attention Mechanism</h4><p>The attention mechanism enables transformers to <strong>capture dependencies between words - </strong>how words in the sequence relate to other words in that sequence, addressing a key limitation of earlier architectures like RNNs, which struggle with long-range dependencies.</p><p><strong>Key, Query, Value in Attention</strong></p><p>In the attention mechanism, each word in a sequence is represented by three vectors: Key, Query, and Value. These vectors help the model determine the relevance of words in the sequence to each other.</p><p>We can think of it like a search system:</p><ul><li><strong>Queries:</strong> The search term you input.</li><li><strong>Keys: </strong>metadata of the documents you have (“documents summary”)</li><li><strong>Values:</strong> The content of the documents.</li></ul><p>Let’s say you’re searching for “pizza recipes”:</p><ul><li><strong>Query:</strong> “Pizza recipes”</li><li><strong>Keys:</strong> Titles of various recipe pages, like “Classic Margherita”, “Tomatoes Salad”, “Smoked Salmon”, “Pepperoni Pizza”, etc.</li><li><strong>Values:</strong> The actual content of these recipe pages.</li></ul><p>The attention mechanism scores each key based on its similarity to the query. So “Classic Margherita” and “Pepperoni Pizza” will get the highest score. This similarity score determines how much focus to place on each value in the sequence.</p><p><strong>Mathematical Explanation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*nHF3YPrGtOUmyIuyi68TYw.png" /></figure><p>In this formula, <strong>𝑄 (Query), 𝐾 (Key), and 𝑉 (Value)</strong> are matrices representing the input data in different forms, used to calculate the attention scores. <strong>Query (Q)</strong>: A matrix of shape (<em>n</em>,<em>dk</em>​), where <em>n</em> is the number of words (or tokens) in the sequence, and <em>dk</em>​ is the dimension of the query and key vectors. 𝑄 is obtained by multiplying the data matrix 𝑋 (of shape (𝑛,𝑑𝑥)) with a learnable weight matrix 𝑊_𝑄​ (of shape (𝑑𝑥,𝑑𝑘)), i.e., 𝑄=𝑋𝑊_𝑄. <strong>Key (K)</strong>: A matrix of shape (<em>n</em>,<em>dk</em>​), where each row corresponds to a key vector for each word in the sequence, similarly computed as 𝐾=𝑋𝑊_𝐾. <strong>Value (V):</strong> A matrix of shape (<em>n</em>,<em>dv</em>​), where <em>dv</em>​ is the dimension of the value vectors, computed as 𝑉=𝑋𝑊_𝑉.</p><p>All these matrices W_<em>Q</em>, W_<em>K</em>, and W_<em>V</em> are learnable parameters, optimized during the training process. The computation involves three main steps:</p><ul><li><strong>Dot Product:</strong> Compute the dot product of the Query vector with each Key vector to measure similarity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*6YUr1n-aVsLRkTb53SU6-A.png" /></figure><p>the dot product between 2 vectors returns the angle between the vectors- such that the dot product between vectors with similar directions will be large, and with orthogonal vectors the dot product will be 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*Myq5SSIB12fcS7C2qsV4Mg.png" /></figure><p>in this example Q is most similar to K2 and a little bit to K3 — so the query will attend most to those keys.</p><ul><li><strong>Scaling: </strong>The dot product is scaled by dk to stabilize the gradients.</li><li><strong>Softmax:</strong> Apply the softmax function to the attention scores to get weights.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*L16AUcZ-RXbB5KvOyXNhug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*Hiu7BxPkQjkuYj9hJ9oEhg.png" /></figure><p>after performing softmax every key gets a normalized score by its relation to the query.</p><ul><li><strong>Weighted Sum:</strong> Multiply the weights with the Value vectors and sum them up to get the final attention output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*BrXKIaVV0ihncFJcgCG-9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiveWxSUEDqmHfg5ybf96Q.png" /></figure><p>This process allows the model to focus on the most relevant parts of the input sequence, capturing dependencies regardless of their distance.</p><p>In this example, I showed attention to one query, but in practice, there are multiple queries, allowing us to “ask” our data several questions.</p><p>Note that the attention mechanism has a quadratic complexity due to the need for each word in a sequence of <em>n</em> words to “attend” to every other word to understand its context. This results in <em>n</em>×<em>n</em> pairwise interactions. This quadratic growth with respect to the sequence length <em>n</em> leads to increased memory usage and processing time, highlighting the computational challenges of using Transformers for long sequences.</p><h4><strong>Positional Encoding</strong></h4><p>In natural language processing (NLP), understanding the order of words is crucial. For example, if a word appears twice in a sequence, it doesn’t necessarily have the same semantic meaning each time. Traditional RNNs and LSTMs inherently handle this through their sequential nature, but Transformers, which process words in parallel, require an additional method to capture positional information. This is where positional encoding comes into play.</p><p>Positional encoding adds a unique vector to each word embedding based on its position in the sentence. These vectors ensure that the model can differentiate between sentences like “dog bites man” and “man bites dog,” even though the individual word embeddings might be similar.</p><p>Transformers use trigonometric functions to encode the position of a word in the sequence, creating continuous binary encodings. By adding these unique vectors to each word embedding based on its position in the sequence, the model can understand the relative distances between words, even in long sequences.</p><p>The encoding for each position is a combination of sine and cosine functions of varying frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*XMb8i5zqnl8XcL82VGXllQ.png" /><figcaption><em>pos</em> is the position of the word in the sequence, <em>i</em> is the dimension index, and <em>d</em> is the dimensionality of the positional encoding.</figcaption></figure><p>This helps the model understand the relative distances between words, even in long sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ygb9S-BcSGVrsqXV0mpvQ.png" /><figcaption>The above image illustrates the process of creating positional encodings using sine and cosine functions of varying frequencies. Each subplot represents a different frequency of the sine or cosine function. The positions that are shown here are from 0–20, where the d is 4. For position 0, the encoding values are [0, 1, 0, 1], highlighted in green. For position 10, the encoding values are [0.17, 0.98, -0.98, 0.17], highlighted in blue. These combined sine and cosine functions of varying frequencies provide the positional encodings for each word, allowing the Transformer model to understand both local and global positional relationships in the sequence. code for this plot can be found <a href="https://colab.research.google.com/drive/11DHhSu0jTW2TZX0SMAXX8ruhy1-YLFO9?usp=sharing">here</a>.</figcaption></figure><p>Each frequency of the sine and cosine functions captures different types of positional relationships:</p><ul><li><strong>Low Frequencies:</strong> Represent long-range positional relationships. They change slowly across positions, encoding more global position information. For example, they capture the relationship between words that are 𝑛<em>n</em> words apart.</li><li><strong>High Frequencies:</strong> Represent short-range positional relationships. They change rapidly across positions, encoding more local position information. For instance, they capture the relationship between words that are 2 words apart or even just 1 word apart.</li></ul><p>By combining these frequencies, the positional encoding provides a rich representation of both local and global positional relationships. This multi-scale approach allows the Transformer to understand both the immediate context and the broader structure of the sequence.</p><h3>Graph Neural Networks</h3><p>Graphs are a powerful tool for modeling complex relationships and interactions within data. They allow us to represent entities as nodes and their interactions as edges, making them invaluable for a wide range of applications. For instance, in social networks, nodes represent individuals, and edges represent their connections. In transportation systems, nodes are locations, and edges are pathways.</p><p>Graph Neural Networks (GNNs) have emerged as a revolutionary approach to harness this potential. By leveraging the intricate structure of graphs, GNNs capture both local and global dependencies, offering a robust framework for various data-driven tasks. These include node classification, graph regression, and graph classification, among others.</p><p>Key Components of GNNs:</p><ul><li><strong>Node Features: </strong>Each node in the graph has associated features that provide contextual information.</li><li><strong>Edge Features:</strong> Edges can also have features that describe the nature of the relationships between nodes.</li></ul><p>The ability of GNNs to process and analyze graph-structured data opens up numerous possibilities. They have been successfully applied in various fields, including biology for predicting protein-protein interactions, chemistry for molecular property prediction, and even in recommendation systems to suggest products or content.</p><p>By capturing the complex dependencies within graph data, GNNs pave the way for innovative solutions to some of the most challenging problems in today’s data-driven world.</p><h3>Graph Transformer</h3><p>Transformers have revolutionized the handling of sequential data, prompting the question: can they also excel with graph data? This transition from sequential to graph data necessitates certain modifications to the transformer architecture. Let’s explore these adjustments and introduce Graph Transformers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*Su2TtCGczrHonbnXhx4hJA.png" /><figcaption>Graph Transformer Architecture from <a href="https://arxiv.org/pdf/2012.09699">A Generalization of Transformer Networks to Graphs paper</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEXwbvnpXMuhOBisQj2pcw.png" /></figure><p>The images above illustrate the architecture of a Graph Transformer, highlighting the key components and the process involved:</p><ol><li><strong>Input Graph</strong>: The model takes an input graph with nodes {x1,x2,x3,x4}and edges representing the relationships between nodes.</li><li><strong>Node Features</strong>: Each node xi​ in the graph is initially represented by a feature vector X=[x1,x2,x3,x4].</li><li><strong>Linear Transformations</strong>: The node feature matrix X is multiplied by three learned weight matrices W_Q,W_K,W_V to produce the Query Q, Key K, and Value V matrices.</li><li><strong>Positional Encoding</strong>: Unlike NLP Transformers, where positional encodings capture the position of words in a sequence, Graph Transformers use positional encodings to capture the structural information of the graph, providing context about the node’s position within the graph.</li><li><strong>Attention Calculation</strong>: The attention scores are computed using the attention formula.</li><li><strong>Output</strong>: The final node representations, can be used for various downstream tasks, such as node classification, graph classification, and graph regression.</li></ol><p>Graph Transformers effectively combine the attention mechanism with graph-structured data. This process differs from NLP Transformers mainly in the way the input data (graphs versus sequences) and positional encodings are handled, adapting the powerful Transformer architecture to the unique structure of graphs.</p><p><strong>Key References</strong></p><ul><li><a href="https://arxiv.org/pdf/2012.09699">Generalization of Transformers to Graphs</a></li><li><a href="https://arxiv.org/pdf/1710.10903">Graph Attention Networks</a></li></ul><h4>Positional Encoding of Nodes Using Laplacian Eigenvectors</h4><p>While many components remain similar, positional encoding requires adaptation for graphs.</p><p>In graph neural networks (GNNs), positional encoding of nodes is essential for capturing the graph’s structure. Spectral graph theory offers a powerful method for this by using the eigenvectors of the Laplacian matrix.</p><p>What are Laplacian Eigenvectors?</p><p>The Laplacian matrix, <em>L</em>, is significant as it encodes the graph’s structure. It is defined as 𝐿=𝐷−𝐴, where <a href="https://en.wikipedia.org/wiki/Degree_matrix"><em>D</em> is the degree matrix</a> and <a href="https://en.wikipedia.org/wiki/Adjacency_matrix">𝐴 is the adjacency matrix</a> of the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*pW6ek3JAZuCwvjx-2CivBw.png" /><figcaption>Graph G</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*HEFVlowLLqADRpwJ" /><figcaption><em>D</em> is the degree matrix and 𝐴 is the adjacency matrix of the graph</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*hnWnpYOAijQnPuUb" /><figcaption>Laplacian matrix of graph G</figcaption></figure><p>The Laplacian matrix is positive semi-definite, meaning all its eigenvalues are non-negative (𝜆≥0).</p><p>The eigenvectors of <em>L</em> are solutions to the equation <em>L</em><strong><em>u</em></strong>=<em>λ</em><strong><em>u</em></strong>, where <strong><em>u</em></strong> is an eigenvector and <em>λ</em> is the corresponding eigenvalue. These eigenvalues provide insights into the graph’s structural properties.</p><h4><strong>Intuition Behind Using Laplacian Eigenvectors</strong></h4><p>The eigenvectors of the Laplacian matrix represent <strong>different frequency components of the graph</strong>. The smallest eigenvalues correspond to smooth, low-frequency components, capturing broad, global structures of the graph. In contrast, larger eigenvalues correspond to high-frequency components, capturing fine, local details.</p><ul><li><strong>Global Relationships:</strong> The eigenvectors associated with smaller eigenvalues vary slowly across the graph, providing a smooth positional encoding that captures global relationships between distant nodes.</li><li><strong>Local Relationships: </strong>The eigenvectors associated with larger eigenvalues vary more rapidly, capturing local relationships and fine-grained details of the graph structure.</li></ul><p>This multi-scale representation allows GNNs to effectively capture both global and local structures in the graph.</p><p>Let’s view the smoothing properties of the eigenvectors depending on their eigenvalues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpL52qpUvxbDQbPRXDsV7Q.png" /><figcaption>The above image illustrates the process of creating positional encodings using the Laplacian eigenvectors. Each subplot represents a different smoothness of the eigenvector. For node 1, the encoding values are [0.38,0.2,-0.5,-0.25], highlighted in red. For node 5, the encoding values are [0.38,-0.6,0.4,0], highlighted in green. These first 4 eigenvectors of varying frequencies provide the positional encodings for each node, allowing the Transformer model to understand both local and global positional relationships in the graph. code for this plot can be found <a href="https://colab.research.google.com/drive/11DHhSu0jTW2TZX0SMAXX8ruhy1-YLFO9?usp=sharing">here</a>.</figcaption></figure><p>For a deeper dive into these concepts, refer to <a href="https://www.youtube.com/watch?v=uTUVhsxdGS8&amp;ab_channel=Ron%26Math">Ron &amp; Math’s explanation on YouTube.</a></p><h4>Comparison to Positional Encoding in NLP</h4><p>We saw that in sequence data, positional encoding is done using sine and cosine functions of different frequencies. These functions provide a continuous and periodic encoding scheme that allows the model to distinguish between different positions in a sequence.</p><ul><li><strong>Sine and Cosine Positional Encoding:</strong> This method encodes positions using fixed, globally smooth functions that allow the model to understand the relative positions of tokens in a sequence.</li><li><strong>Laplacian Eigenvector Positional Encoding:</strong> In graphs, the positional encoding using Laplacian eigenvectors is more flexible and adaptive to the graph’s topology. It inherently captures both global and local positional information, which is particularly useful for irregular and non-Euclidean data structures like graphs.</li></ul><p>Interestingly, if we take a sentence and represent it as a graph where each word is a node connected to the next word, the Laplacian eigenvectors of this graph will yield the same positional encodings as the sine and cosine functions used in NLP Transformers. (<a href="https://youtu.be/DiLSCReBaTg?t=440">reference: Recipe for a General, Powerful, Scalable Graph Transformer</a> )</p><p>So, both NLP and graph transformers can understand the relative positions of nodes (or words) within their respective structures, enabling them to capture complex dependencies and relationships effectively.</p><h3>Limitations of Graph Transformers for Large Graphs</h3><p>While Graph Transformers show great promise, they face significant limitations when applied to large graphs. Let’s discuss these challenges and potential solutions.</p><h4>1. Attention Complexity: 𝑂(𝑛²)</h4><p>The attention mechanism, a cornerstone of the Transformer architecture, has a<a href="https://towardsdatascience.com/scalable-graph-transformers-for-million-nodes-2f0014ceb9d4"> complexity of O(n²)</a>, where n is the number of nodes in the graph. This quadratic complexity arises because attention calculations involve all pairs of nodes, leading to scalability issues for large graphs.</p><p><strong>Suggested Solution: Local Neighborhood Attention</strong></p><p>One effective approach to mitigate this issue is the use of local neighborhood attention, as proposed in the <a href="https://arxiv.org/pdf/1710.10903">Graph Attention Network (GAT)</a> paper. Instead of considering all node pairs, local neighborhood attention restricts attention to a node’s immediate neighbors. This reduces the complexity to O(n|E|) and allows the model to focus on the most relevant connections.</p><p>Local Neighborhood Attention in GAT:</p><ul><li>Mechanism: Each node attends only to its neighbors, significantly reducing the number of attention calculations.</li><li>Efficiency: This localized approach scales better with larger graphs, maintaining the key advantages of the attention mechanism while improving computational efficiency.</li></ul><h4>2. Computation of Eigenvectors for Large Matrices</h4><p>Computing the eigenvectors of the Laplacian matrix, essential for positional encoding in graph transformers, becomes impractical for large graphs. The direct computation of eigenvectors is computationally expensive and often infeasible for large matrices.</p><p>How do we compute the eigenvectors currently?</p><p>np.linalg.eig function in numpy that gets a squared matrix and returns its eigenvalues and eigenvectors, leverages efficient numerical algorithms such as the QR algorithm or the Divide-and-Conquer method to solve the characteristic equation <em>Av</em>=<em>λv</em>. These algorithms are designed to handle various types of matrices and can provide accurate results for both small and moderately large matrices.</p><p>While np.linalg.eig is effective for small matrices, it faces significant challenges with very large matrices due to:</p><ol><li>Computational Complexity: The time complexity for computing eigenvectors is generally 𝑂(𝑛³ ), where 𝑛 is the number of nodes. This becomes impractical for very large graphs.</li><li>Memory Usage: Storing and manipulating large matrices requires substantial memory, which can exceed the capacity of standard computational resources.</li></ol><h4>Current Solutions for Large Graphs</h4><p>The limitations of Graph Transformers in handling large graphs remain significant. These models struggle with scalability and efficiency when dealing with graphs consisting of millions of nodes. Consequently, the challenge of processing large graphs with Graph Transformers persists, and this architecture alone cannot effectively address the problem for large graphs, such as those with 2 million nodes.</p><p>However, recent research has introduced new architectures that offer promising solutions. Two notable examples are <a href="https://arxiv.org/pdf/2206.04910"><strong>NAGphormer</strong></a> and <a href="https://arxiv.org/pdf/2403.16030"><strong>VCR-graphormer</strong></a>. These approaches tackle the scalability issue by creating a sequence for each node and passing that sequence to a transformer. This means that instead of processing the entire graph at once, they consider subgraphs centered around each node.</p><p><strong>NAGphormer</strong> and <strong>VCR-graphormer</strong> effectively break down the large graph into manageable subgraphs. Each node’s neighborhood is represented as a sequence, capturing local structural information. This sequence is then input into a transformer, allowing the model to leverage the attention mechanism within a localized context. By doing so, these architectures can handle large-scale graphs more efficiently while still capturing the necessary dependencies.</p><p>These two papers, <strong>NAGphormer</strong> and <strong>VCR-graphormer</strong>, are very recent, with one published in 2023 and the other just a few months ago. This highlights the fact that this is an active area of research. I am currently working in this field under the supervision of <a href="https://u.cs.biu.ac.il/~shahamu/"><strong>Uri Shaham</strong></a>.</p><p>Though these approaches represent significant advancements, a detailed exploration of NAGphormer and VCR-graphormer will be covered in a subsequent post.</p><h3>Conclusion</h3><p>Graph Transformers represent an exciting frontier in deep learning, bridging the gap between sequential and graph-structured data. By adapting the powerful Transformer architecture to graphs, researchers are opening up new possibilities for analyzing complex data structures. As the field continues to evolve, we can expect to see even more innovative solutions that push the boundaries of what is possible with graph data.</p><p>In summary, while challenges remain, the advancements in Graph Transformers hold significant potential for a wide range of applications. By addressing the limitations and continuing to innovate, we can unlock the full potential of Graph Transformers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ede65db4658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hebbian Learning: Biologically Plausible Alternative to Backpropagation]]></title>
            <link>https://medium.com/@reutdayan1/hebbian-learning-biologically-plausible-alternative-to-backpropagation-6ee0a24deb00?source=rss-f59fb93eab8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ee0a24deb00</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[hebbian-theory]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neuroscience]]></category>
            <dc:creator><![CDATA[Reut Dayan]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 14:47:45 GMT</pubDate>
            <atom:updated>2024-02-18T07:35:34.566Z</atom:updated>
            <content:encoded><![CDATA[<p>Hebbian learning, a principle grounded in the functioning of biological neural networks, poses an intriguing question: Can we use this natural learning rule to train artificial neural networks? In this blog post, we’ll explore this question.</p><h3>Introduction</h3><p>Backpropagation is the most commonly used method to iteratively train an artificial neural network. In essence, it updates the weights of the model by the derivative of the error with respect to the weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*yAZfFrrF--5aTR6_3OLTcg.png" /><figcaption>backpropagation update rule</figcaption></figure><h3>Limitations of Backpropagation</h3><p>While backpropagation allows the training of neural networks with impressive capabilities, it does have its limitations.</p><ul><li><strong>Space Complexity</strong>: Backpropagation demands storing all forward pass activations in memory, which can be computationally expensive. The size of the neural network, the number of layers, and the batch size all impact the amount of memory needed. <br>Large models, with hundreds of millions or even billions of parameters, impose immense memory demands. For example,<a href="https://www.trgdatacenters.com/ai-chatbots-energy-usage-of-2023s-most-popular-chatbots-so-far/#:~:text=OpenAI%20used%20a%20supercomputer%20with,specifically%20for%20OpenAI&#39;s%20training%20needs."> ChatGPT used 10,000 Nvidia GPUs to train the model.</a></li><li><strong>Perfect Knowledge</strong>: Backpropagation relies on perfect knowledge of the forward pass, which isn’t always practical in real-world scenarios. That means that we can&#39;t use functions that we don&#39;t know how to complete their gradient.</li></ul><p>In this blog post, we will take inspiration from the brain learning mechanism to address these limitations.</p><h3>Introduction to Hebbian Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4QTQs64Stu3ppaISViLug.png" /></figure><p>The learning rule in the brain (as we know it today) is the Hebb rule, “Neurons that fire together wire together”. That means that if neuron A fires, and neuron B fires immediately after, the connection between these two neurons will be stronger. In terms of neuroscience translated into machine learning vocabulary, a <strong>synapse </strong>can be likened to the <strong>weight </strong>connecting two neurons, where the <strong>presynaptic neuron </strong>corresponds to the <strong>input layer</strong> in neural networks, and the <strong>postsynaptic neuron</strong> relates to the <strong>output layer.</strong></p><p>Imagine two neurons, A and B, in your brain. Whenever you think about your favorite food (let’s say it’s pizza), neuron A fires. Now, when you think about your favorite drink (maybe it’s cola), neuron B fires. Over time, because you often think about pizza and cola together, the connection between neurons A and B strengthens. This is Hebbian learning in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Al7J0RJsxy2rDJ_Qn-9uXw.png" /></figure><h3>Applying the Hebbian Learning Rule to Neural Networks</h3><p>Now, how can we apply this concept to train artificial neural networks? Let’s use a simple neural network as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*Z2B3kASBye9NEh8L9oBx6g.png" /><figcaption>basic neural network- pre-synaptic neuron- <strong><em>x,</em></strong><em> p</em>ost-synaptic neuron-<em> </em><strong><em>z, </em></strong>synapse- <strong><em>w</em></strong></figcaption></figure><p>Our goal is to strengthen the connection (synapse) between <em>x</em> and <em>z</em> when both <em>x</em> and <em>z</em> “fire”, and to weaken the connection if one fires while the other doesn’t. A neuron is considered to “fire” when its value is greater than zero, and it does not “fire” when its value is less than zero. Here’s the Hebbian learning rule in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*cENhtiKoa_CA6PG1qt52Ew.png" /><figcaption>vanilla Hebbian rule</figcaption></figure><p>We multiply the pre-synaptic neuron value- <em>x</em>, by the post-synaptic neuron value- <em>z</em>, and by a learning rate, to update the weight between these neurons- <em>w</em>.</p><p>Delta w will be positive if x and z are both in the same sign (we will strengthen w), and will be less than zero if the signs of x and z are different.</p><p>We can notice that the<strong> Hebbian learning rule is unsupervised- </strong>doesn&#39;t require any error or feedback to be computed.</p><p>We can see that the vanilla Hebbian learning rule addresses some of the backpropagation limitations shown above. It eliminates the need for computing derivatives of a function, making it compatible with black-box functions. Additionally, it does not necessitate the storage of all forward pass activations; instead, it relies on information from the pre and post-synaptic cells to determine weight updates, reducing the memory overhead.</p><p>However, this update rule has neither achieved high accuracy performance vs. backpropagation nor is the training procedure simple :(</p><h3>HebbNet: Enhancing Hebbian Learning</h3><p><a href="https://oar.a-star.edu.sg/storage/2/2jep0k6mw7/gupta.pdf">HebbNet</a> is a research paper that enhances the Hebbian learning rule to achieve improved performance through an architecture that integrates a layer of Hebbian learning with a layer of backpropagation.</p><p>The first layer employs Hebbian learning, while the second layer uses backpropagation. The model performs the forward pass calculation, followed by updating the second layer weight using the derivative of the loss with respect to these weights (backprop layer), and updates the first layer weights using the Hebbian learning rule, <strong>with no reliance on error signals</strong> (Hebbian layer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*h-Lyj9Q5bJccLSHwd4GpNw.png" /><figcaption>flatten the input image and have 2 fully connected layers with relu activation and softmax. HebbNet architecture, the first layer- The Hebbian layer, and the second layer- the classification layer (backpropagation).</figcaption></figure><p>As previously mentioned, depending solely on the Hebbian rule has not led to high accuracy performance, largely attributed to the weight fluctuations. These weight fluctuations occur due to our method of updating the weights with x*z, leading the weights to become larger (if both x and z are greater than zero). Consequently, in subsequent iterations, the weight ‘w’ contributes to enlarging ‘z’, creating a cycle of continuous increase. To address this issue, a threshold is applied to limit the weight updates, preventing all the weights from being updated and ensuring weight normalization across all iterations.</p><p>The HebbNet paper introduces two specific strategies to improve Hebbian learning.</p><h3>Tricks to Enhance Hebbian Learning</h3><p>HebbNet incorporates two essential tricks:</p><ul><li><strong>Activation Threshold</strong>: The vanilla Hebbian rule can lead to unstable weight changes. HebbNet updates weights only if the current activation significantly differs from past activations, indicating new learning. This stabilizes the learning process. This trick improves the results from the vanilla Hebbian learning update rule by 50%.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*9ny9y2KXKfEhUp_AeN2z2g.png" /><figcaption>t is the iteration index, w will first update with x*z, then will update by x*z minus the average of all past activations, to update the weight only if there was significant learning in the current iteration.</figcaption></figure><ul><li><strong>Gradient Sparsity</strong>: HebbNet updates only the top percentage of the weights, focusing on the most informative connections. By exclusively updating the top percentage of weights, the model prioritizes the most informative connections, essentially emphasizing the crucial relationships within the data. This strategic approach enhances the network’s ability to learn complex patterns. Consequently, this trick improves the results from the vanilla Hebbian learning update rule and the threshold trick by 50%.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*p7MG-GEnzKjG8n04Ah_8vw.png" /><figcaption>m is the value of the top p% of delta w (p is a hyperparameter), update only the neurons that have a significant change (only the top p%)</figcaption></figure><p>Notice the activation threshold represents a <strong>temporal threshold</strong>, updating only when there’s significant learning in the current iteration. On the other hand, gradient sparsity serves as a <strong>threshold within the neuron population</strong>, updates are limited to the neurons that have exhibited the most significant learning.</p><h3>HebbNet vs. Backpropagtion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QTxqi_laypfL_yCEwDKUg.png" /></figure><ul><li>In backpropagation, weights are updated based on the derivative of the loss with respect to the weight after a forward pass.</li><li>In HebbNet, the first layer updates its weights with the Hebbian rule, and the second layer uses backpropagation.</li></ul><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*G-81TsK31MWPGU9x69J0jA.png" /><figcaption>Comparison of HebbNet with various baselines and state-of-the-art algorithms on CIFAR-10</figcaption></figure><p>As we can see the HebbNet algorithm achieves higher accuracy vs. backpropagation when trained on the CIFAR-10 dataset with the same model architecture.</p><h3>Visualizing Hebbian Weights</h3><p>One fascinating aspect of HebbNet is how it robustly learns pattern representations. When trained on the MNIST dataset (handwritten digits), HebbNet’s first layer weights (learned using the Hebbian rule) reveal remarkable pattern recognition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*ZCm9aNRKRuVeK_gMnqeEOA.png" /><figcaption>visualization of the Hebbian layer weights</figcaption></figure><p>As can be seen, the neurons learn a range of different patterns. They learn both full patterns (digit 7 in row 1, column 2) and partial patterns (an arc in row 4, column 7).</p><p>Interestingly, although the paper employs backpropagation for training the Hebb Net, the core representation is acquired through learning in the Hebbian layer.</p><p>This approach <strong>mirrors the way humans learn </strong>— we first acquire representations through experience, without feedback, using the Hebbian rule. Then, we employ feedback for classification.</p><h3>Intuition to combine Hebbian learning + backpropagation</h3><p>We can think about it like a child learning about objects in the world by observing or touching them, these representations are initially non-semantic. The final stage of learning occurs when someone, like a parent, points to an object and provides its name. This is when the child classifies the representation in his brain and associates it with a name.</p><h3>Implementation and Results Comparison</h3><p>Since HebbNet authors haven’t released code for their paper, I decided to implement the HebbNet model based on the principles outlined in the paper and managed to replicate the results documented in the paper. You can access my implementation code <a href="https://github.com/reutdayan/HebbNet">here</a>.</p><h4>Implementation Insights:</h4><ol><li><strong>Limitation in Batch Size</strong>: One significant drawback of HebbNet is <strong>its dependence on a batch size of 1</strong> for the activation threshold to function as intended. This requirement results in considerably slower training, making the model less suitable for training larger networks.</li><li><strong>Complexity in Deepening the Network:</strong> An inherent challenge arises in the complexity encountered when attempting to expand or deepen the HebbNet architecture.</li><li><strong>Hyperparameter Sensitivity:</strong> HebbNet demonstrates a notable sensitivity to hyperparameters. Subtle changes in hyperparameter settings can significantly impact the model’s performance and convergence. This sensitivity poses a challenge in achieving optimal configurations across diverse datasets or architectures.</li><li><strong>Implied Performance Over Backpropagation:</strong> Although the paper seemed to indicate that HebbNet outperformed backpropagation, HebbNet might not outperform backpropagation with fine-tuning hyperparameters to align with backpropagation.</li></ol><h3>In Conclusion</h3><p>In this journey through the world of Hebbian learning and its promising alternative, HebbNet, we’ve uncovered a unique approach to training artificial neural networks inspired by the human brain’s remarkable capabilities. We’ve discussed the limitations of traditional backpropagation and explored how Hebbian learning overcomes some of these challenges.</p><p>From the Activation Threshold to Gradient Sparsity, HebbNet introduces clever techniques that enhance Hebbian learning, improving its efficiency and effectiveness. We’ve seen how HebbNet outperforms backpropagation in certain scenarios, offering exciting possibilities for the future of artificial intelligence. Despite its potential, HebbNet isn’t without its drawbacks, particularly in terms of batch size limitations and the complexity of network deepening.</p><p>Researchers are continuously exploring Hebbian learning as a biologically plausible alternative to backpropagation, aiming to bridge the gap between artificial neural networks and the human brain’s learning mechanisms.</p><p>While challenges remain, Hebbian learning offers exciting possibilities for the future of AI and deep learning.</p><p>If this has sparked your interest, I encourage you to get in touch with me and use my <a href="https://github.com/reutdayan/HebbNet">GitHub implementation of HebbNet</a> to explore this exciting field further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ee0a24deb00" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>