Hi, I am Shayan Amir!

I like building products around problems. Currently interested in AI research for post-training, RL and generative modeling alongside building collaborative AI systems that are tasteful. Reach out if we share similar interests or just want to chat about new ideas!

!Cultural Riddles: A Multicultural Benchmark of Riddles

!Surface Form or Shared Belief? A Behavioral Test of Whether LLM Judge Agreement Is Diversifiable

Experience
  • Research Collaborator @ Cohere Labs, Open Science Community [Jun ’26 - Present]
    • Submitted to TACL·Accepted at MRL Workshop @ EMNLP ’26
  • Y Combinator Startup School, India [April ’26]
  • Research Intern @ Carnegie Mellon University, Pittsburgh, PA [Jun ’25 - Oct ’25]
  • AI Engineering Intern @ ukumi.ai, San Francisco, CA [Jun ’25 - Aug ’25]
Projects
Blog
← Back
Applied Projects
An AI companion that lives beside your cursor and understands what is on your screen in real time. It supports voice and text interactions, answers questions about on-screen content, points to and navigates interfaces, searches the web, and saves sessions as replayable memories.
Computer Use with SLM using GRPO and OpenEnv
Fine-tuning a small language model using reinforcement learning (GRPO) to teach how to click a button. Agent learns inside a browser environment purely through trial and error, receiving binary rewards for successfully completing web tasks. Model is efficiently trained using LoRA and serverless A100 40GB GPU and served with vLLM, all for ~$3 worth of compute. Agent can learn extended tasks like filling a form and booking a flight if given more compute.
Multimodal Product Price Prediction | Submission to Amazon ML Challenge ’25
My team and I ranked 42nd in India out of thousands of participants. We built a multimodal model to predict the prices of 75,000 retail items using both their images and text descriptions. I used CLIP (ViT-Large) to turn both images and catalog text into shared embeddings, then fed them into a custom regression head for the final prediction. The combined approach worked much better than using just text or just images, bringing the SMAPE down to ~42.0 in the test set.
Blueprint.ai | Submission to Nano Banana Hackathon ’25 by Google Deepmind
Lets you turn hand-drawn sketches into professional logos and product mockups within minutes. Using Gemini 2.5 Flash Image, the tool allows you to doodle on a digital canvas and instantly transform those ideas into polished brand assets. You can refine designs by sketching directly over them, add custom text and colors with simple prompts, and automatically place logos onto product images.
Local DeepResearch Agent
Inspired by OpenAI’s DeepResearch, this is a local research assistant powered by Gemma 3 (4B). It uses Tavily and DuckDuckGo APIs to crawl the web, analyze data, and generate structured reports with cited sources. Users can customize search depth and cycles via a 5-point scale for precise control. Runs entirely on local infrastructure, to ensures total data privacy while automating the full research and synthesis workflow.
MoodAlbum
A large-language + text-to-image model based application that generates personalised art based on emotions detected in the user's journal entry. By integrating emotion detection through RoBERTa model and image generation using Stable Diffusion v1-5 model, it translates textual input reflecting the user's mood into unique visual art which is inspired by real art pieces from historic eras. This project aims to enhance human-AI interaction on an emotional level.
Mitochondria Segmentation
Focuses on the segmentation of mitochondria in electron microscopy images in the EPFL CVLAB Electron Microscopy Dataset (sub-volume). It utilises a standard U-Net architecture in two models trained with different loss functions -- binary cross entropy and Jaccard loss.
Chest X-Ray Anomaly Detection
Detecting lung diseases from chest X-ray images using the Japanese Society of Radiological Technology (JSRT) Database. It utilises an Autoencoder architecture and a reconstruction error with 95% threshold for anomaly detection.
NASA Airfoil Sound Pressure Level Prediction
This project predicts the sound pressure levels generated by airfoil blades due to self-noise. The dataset used for training is the Airfoil Self-Noise Dataset from UCI Machine Learning Repository. It utilises classical ML algorithms like linear regression, poly regression, random forest, decision tree, ensemble learning, etc. Along with a neural network optimised by KerasTuner for hyperparameter tuning. Loss function used is mean squared error.
← Back
Research Projects
Just Image Transformers
A PyTorch implementation of the "Back to Basics: Let Denoising Generative Models Denoise" paper. Implements the JiT-B/16 architecture, moving away from latent spaces to predict clean images (x-prediction) directly on raw pixel patches. Contains faithful advanced setup components, including SwiGLU, RoPE, and AdaLN-Zero conditioning. Optimized training for ImageNette dataset on a single NVIDIA T4 GPU.
Tiny Recursive Model
A PyTorch implementation of Samsung's "Less is More: Recursive Reasoning with Tiny Networks" paper. Explores how weight-sharing can make models smaller without losing performance. Instead of stacking dozens of layers, this model reuses a single transformer block to iteratively refine predictions and latent states. Built a dual-loop system that achieves an 18x virtual depth while keeping the parameter count extremely low.
Llama 2
A from-scratch implementation of Meta's Llama 2 Model using PyTorch. Contains all the core architectural features like RMSNorm for stability, SwiGLU activation, and Rotary Positional Embeddings (RoPE) for handling sequence positions. I also added Grouped-Query Attention (GQA) and KV Caching to make inference faster and more memory-efficient.
Flow Straight and Fast
A from-scratch implementation of the "Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow" paper using PyTorch. Trained a neural network that learns an ordinary differential equation to map data points from source to target distributions in (almost)straight paths. Applied reflow as well with 2D and 3D plots to visualise changing of trajectories. This paper was pivotal for models like SD3. This implementation is accompanied by a blog which you can find on my technical-blogs page.
Quantization Techniques
Learning different quantization techniques to understand how to shrink large models so they run faster on cheaper hardware. Implemented Symmetric and Asymmetric Linear Quantization from scratch focusing on the math behind mapping weight to different precisions, as well as Post-Training Quantization (PTQ) on a simple neural network.
Denoising Diffusion Probabilistic Models
A from-scratch implementation of the original DDPM paper using PyTorch. Replicates the forward noising process using paper's specified linear schedule and the reverse generative process is learned via a U-Net model, conditioned on sinusoidal time embeddings. It predicts the added noise at each step, optimized using the simplified MSE loss. This implementation focuses on clearly demonstrating the architecture of foundational diffusion models.
All Attentions You Will Need
A collection of from-scratch implementations of different attention mechanisms while breaking down the math. Each mechanism walks through the entire process : creating a custom vocabulary from a sample sentence, generating input embeddings, and implementing the core tensor logic.
← Back
Technical Blogs
Rectified Flow
Ever wondered how AI models smoothly transform data from one form to another? A deep dive into "Rectified Flow" an elegant technique for distribution transport. See how a simple idea of "straightening" data paths can lead to incredibly efficient and powerful generative models, like Stable Diffusion 3. This blog is based on this paper. You can view the PyTorch code in the paper implementation section of my website.
← Technical Blogs
Sailboats moving across the sea

Rectified Flow

Aug 2025

I want to share my recent deep dive into a paper titled “Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow”. As someone learning about generative models and how they handle different data distributions, this paper offered a surprisingly elegant and effective approach. I've even been playing around with my own implementation, and I'm excited to walk you through the documentation of what I learned.

View the implementation on GitHub ↗

The Challenge of Distribution Transport

In machine learning, we often encounter the problem of “distribution transport.” This involves learning how to transform data from one distribution (let's call it \(\pi_0\)) to another (\(\pi_1\)). This challenge is central to many tasks, including:

  • Generative Modeling: Creating new data samples that resemble a target distribution (e.g., generating realistic images from random noise).
  • Domain Transfer: Translating data from one domain to another (e.g., converting horse images to zebra images).

Traditionally, methods like Generative Adversarial Networks (GANs) and Diffusion Models have been popular. While powerful, they can sometimes face issues like training instability, mode collapse, or high computational costs during inference, especially for continuous-time models that require many steps to simulate.

Rectified Flow offers a fresh perspective by leveraging Ordinary Differential Equation (ODE) models to tackle this problem in a unified and often more efficient way.

What is Rectified Flow? The Idea of “Straightening” Paths

The core idea behind Rectified Flow is beautifully simple: learn an ODE that transports data points from \(\pi_0\) to \(\pi_1\) by following paths that are as straight as possible.

Think of it like this: if you have a starting point and an ending point, the shortest and most direct way to get from one to the other is a straight line. Rectified Flow aims to make the “flow” of data points between distributions mimic these straight-line movements.

Why are straight paths so desirable?

  • Computational Efficiency: Perfectly straight paths can be simulated exactly with just a single step, making inference much faster compared to multi-step ODE/SDE solvers. This bridges the gap between computationally intensive continuous-time models and faster one-step models.
  • Theoretical Soundness: Straight paths are the shortest paths, which has nice implications for transport costs (more on this later!).

The Rectified Flow defines an ODE on time \(t \in [0,1]\):

\[\frac{dZ_t}{dt} = v(Z_t,t)\]

where \(Z_t\) represents a data point at time \(t\), and \(v(Z_t,t)\) is a “velocity field” that dictates the direction and speed of movement. Our goal is to learn this \(v\).

Learning the Velocity Field: A Least Squares Approach

The magic of Rectified Flow lies in how it learns this velocity field \(v\). It's surprisingly straightforward!

First, let's consider a simple linear interpolation between a source point \(X_0 \sim \pi_0\) and a target point \(X_1 \sim \pi_1\):

\[X_t = tX_1 + (1-t)X_0\]

where \(t \in [0,1]\). The derivative of this linear interpolation is simply \((X_1-X_0)\), which represents the straight-line direction from \(X_0\) to \(X_1\).

However, this linear interpolation is “non-causal” because to know \(X_t\), you need to know the final point \(X_1\). The Rectified Flow aims to “causalize” this by learning a velocity field \(v(X_t,t)\) that closely approximates \((X_1-X_0)\). This is achieved by solving a simple least squares regression problem:

\[\min_v \int_0^1 \mathbb{E}\left[\left\|(X_1-X_0)-v(X_t,t)\right\|^2\right]dt\]

In practice, this means we train a neural network to represent \(v\). We feed the network the interpolated point \(X_t\) and the time \(t\), and it tries to predict the “straight” direction \((X_1-X_0)\).

Here's an illustration of the concept:

Illustration of linear interpolation and a learned rectified flow

The Rectification Process: Training and Sampling

The overall procedure for Rectified Flow is outlined in the paper's Algorithm 1:

Rectified Flow training and sampling algorithm

1. Training

Inputs: Draws from a coupling \((X_0,X_1)\) of your source distribution \(\pi_0\) and target distribution \(\pi_1\). Often, we just draw \(X_0 \sim \pi_0\) and \(X_1 \sim \pi_1\) independently.

Objective: Train your velocity model \(v_\theta\) by minimizing the least squares objective mentioned above. This typically involves sampling \(t\) uniformly from \([0,1]\) during training.

\[\hat{\theta}=\arg\min_\theta\mathbb{E}_{X_0,X_1,t\sim U([0,1])} \left[\left\|(X_1-X_0)-v_\theta(tX_1+(1-t)X_0,t)\right\|^2\right]\]

2. Sampling (Inference)

Once the velocity model \(v_{\hat{\theta}}\) is trained, you can use it to generate samples:

  1. Draw a starting point \(Z_0 \sim \pi_0\).
  2. Solve the ODE \(dZ_t=v_{\hat{\theta}}(Z_t,t)dt\) from \(t=0\) to \(t=1\).
  3. The final point \(Z_1\) will then follow the target distribution \(\pi_1\).

For backward sampling (transferring \(\pi_1\) to \(\pi_0\)), you simply solve \(d\tilde{X}_t=-v(\tilde{X}_t,t)dt\) starting from \(\tilde{X}_0 \sim \pi_1\).

Key Properties and Why They Matter

Rectified Flow comes with several attractive properties that make it a powerful tool:

1. Flows Avoid Crossing

A fundamental property of well-defined ODEs is that their trajectories cannot cross each other. While the linear interpolation \(X_t\) can have crossing paths, the rectified flow \(Z_t\) “rewires” these trajectories to avoid intersections while still preserving the overall marginal distributions. This means that the flow maintains a consistent mapping between points from \(\pi_0\) to \(\pi_1\).

2. Reducing Transport Costs

The rectification process is guaranteed to reduce or maintain the transport cost for any convex cost function. In simpler terms, it finds a more “efficient” way to move mass from \(\pi_0\) to \(\pi_1\). For instance, for the common L2 cost, the expected length of the paths \(\|Z_1-Z_0\|\) will be less than or equal to \(\|X_1-X_0\|\).

3. Reflow: Making Paths Even Straighter

This is where things get really interesting! The paper introduces an optional but highly effective procedure called Reflow. This involves recursively applying the rectification process:

  1. You start with your initial data coupling \((X_0,X_1)\).
  2. You learn the first rectified flow, \(Z^1=\operatorname{RectFlow}((X_0,X_1))\).
  3. Then, you use the end points of this first flow, \((Z_0^1,Z_1^1)\), as the new input for the next rectification step to learn \(Z^2=\operatorname{RectFlow}((Z_0^1,Z_1^1))\).

This process can be repeated for \(k\) steps to obtain a \(k\)-rectified flow, \(Z^k\).

The magical effect of this reflow procedure is that it makes the paths of the rectified flows increasingly straight. The straightness of a flow \(Z=\{Z_t\}\) can be measured by:

\[S(Z)=\int_0^1\mathbb{E}\left[\left\|Z_1-Z_0-\dot{Z}_t\right\|^2\right]dt\]

A value of \(S(Z)=0\) indicates perfect straightness. The paper theoretically proves that applying rectification recursively decreases \(S(Z)\) towards zero.

Reflow progressively straightening transport paths

This straightening is incredibly beneficial: a nearly straight flow can be simulated accurately with a very small number of numerical integration steps, even just a single Euler step! This drastically reduces inference time.

4. Distillation (Optional)

After obtaining a highly straight \(k\)-rectified flow, you can further speed up inference by distilling the flow into a one-step neural network that directly maps \(Z_0^k\) to \(Z_1^k\). This is useful for fine-tuning the model for even faster one-step generation.

My Implementation Insights

For my implementation, I focused on a simple 2D toy example to visualize the concepts.

Dataset:

I used two distinct distributions:

  • \(\pi_0\): Two Gaussian blobs (source distribution)
  • \(\pi_1\): Two “square” shapes (target distribution), which are intentionally placed to encourage curved paths in naive interpolation, making the straightening effect more evident.
Source and target toy distributions

The goal was to see how the Rectified Flow learns to smoothly transform points from the Gaussian blobs to the squares.

The training loop iteratively updates the VectorField network based on the least squares objective. After training, I visualized the trajectories generated by simulating the learned ODE.

Here's what I observed, consistent with the paper's findings:

Trajectories for the initial Rectified Flow
Fig. 1: Trajectories for Initial Rectified Flow (perhaps a bit curved)
Straighter trajectories after reflow
Fig. 2: Trajectories for next Rectified Flow (significantly straighter paths after reflow)
Velocity vector trajectories at t equals 0.5
Fig. 3: Visualizing trajectories of velocity vectors at \(t=0.5\)

These visualizations clearly demonstrate the “straightening” effect that Rectified Flow achieves through its training and reflow procedure.

Concluding Thoughts

Rectified Flow presents a really unique way to tackle distribution transport. We can apply these techniques to image and audio data as well. Recent papers like Diff2Flow and Mean Flows hint at a vibrant future for this area. I'm excited to explore its potential further and see where it leads!

Resources

Here’s where I learned it from, for you to explore: