[{"content":"\nSlide 1: Diffusion Model and Its Applications Title: Diffusion Model and its applications Presenter: Jungmook Kang Event: StatLet Seminar Date: 9/4/2026 Slide 2: Reference \u0026amp; Resources MIT EECS 6.S183, 6.S184 Ho et al. (2020), Denoising Diffusion Probabilistic Models Song et al. (2021), Denoising Diffusion Implicit Models Material: mookjsi.github.io/posts/diffusion2 Slide 3: 1. Introduction Section 1 introduces the basic generative modeling perspective behind diffusion models. Slide 4-6: Representing Images and the Goal of Generation Images can be represented as high-dimensional vectors.\nHeight: $H$ Width: $W$ Color channels: 3 channels (RGB) $$ z \\in \\mathbb{R}^{H\\times W\\times 3} $$ Suppose the true data distribution is\n$$ p_{\\text{data}}:\\mathbb{R}^d\\rightarrow\\mathbb{R}_{\\ge 0}, \\qquad z\\mapsto p_{\\text{data}}(z). $$ However, $p_{\\text{data}}$ itself is unknown.\nThe goal of generation is to sample an image from this unknown data distribution:\n$$ z\\sim p_{\\text{data}}. $$ Slide 6 illustrates this idea by showing a sample drawn from $p_{\\text{data}}$ becoming a generated image. Source: MIT EECS 6.S184 Slide 7-8: What Does Successful Generation Mean? Example prompt:\n“A picture of a dog”\nThe slide compares four outputs:\nRandom noise — Useless An unrelated street image — Bad A cat image — Wrong animal A dog image — Great! The central intuition is:\nHow good an image is ≈ How likely it is under the data distribution.\nAnother interpretation:\nHow likely are we to find this picture on the internet?\nA generative model converts samples from a simple initial distribution, such as a Gaussian distribution, into samples resembling the data distribution.\n$$ x\\sim p_{\\text{init}} \\quad \\xrightarrow{\\text{Generative Model}} \\quad z\\sim p_{\\text{data}}. $$ The initial sample is visualized as noise. The final sample is visualized as a realistic dog image. Source: MIT EECS 6.S184 Slide 9-10: Forward and Reverse Diffusion Processes Reference:\nhttps://arxiv.org/abs/2006.11239 The DDPM graphical model illustrates a sequence from clean data $x_0$ toward increasingly noisy states $x_1,\\ldots,x_T$.\n⬅ Forward process adds noise to data ➡ Diffusion models learn the reverse process to recover data from noise Denoising diffusion models estimate a noise vector\n$$ \\epsilon\\in\\mathbb{R}^d $$ from a given noise level\n$$ \\sigma\u003e0 $$ and noisy input\n$$ x_\\sigma\\in\\mathbb{R}^n, $$ such that, for some clean point $x_0$ on the data manifold $\\mathcal K$,\n$$ x_\\sigma \\approx x_0+\\sigma\\epsilon. $$ Source: MIT EECS 6.S184 Slide 11: Learning a Noise Predictor A denoiser is represented as\n$$ \\epsilon_\\theta:\\mathbb{R}^d\\times\\mathbb{R}_+\\rightarrow\\mathbb{R}^d. $$ It is trained by minimizing the expected noise-prediction error:\n$$ L(\\theta) := \\mathbb{E}_{x_0,\\sigma,\\epsilon} \\left[ \\left\\| \\epsilon_\\theta(x_0+\\sigma\\epsilon,\\sigma)-\\epsilon \\right\\|_2^2 \\right]. $$ During training:\n$x_0$ is sampled from the training data. $\\sigma$ is sampled from the training noise schedule. $\\epsilon$ is sampled from a standard Gaussian distribution: $$ \\epsilon\\sim\\mathcal N(0,I_d). $$ The noisy input given to the model is therefore\n$$ x_\\sigma=x_0+\\sigma\\epsilon. $$ Source: MIT EECS 6.S183 Slide 12: 2. Algorithms Section 2 describes concrete training and sampling algorithms for a simple diffusion model. Slide 13: A Toy 2D Diffusion Model The model is demonstrated using a 2D spiral dataset.\nPipeline:\nStart with points on a 2D spiral. Add different amounts of Gaussian noise. Embed the noise level. Feed both the noisy point and noise-level embedding into a fully connected MLP. Predict the noise. The noise-level embedding is two-dimensional and is visualized using sinusoidal functions:\n$$ \\sin\\left(\\frac{\\log(\\sigma_t)}{2}\\right), \\qquad \\cos\\left(\\frac{\\log(\\sigma_t)}{2}\\right). $$ The slide contains the following model implementation:\ndef get_sigma_embeds(sigma): sigma = sigma.unsqueeze(1) return torch.cat([ torch.sin(torch.log(sigma) / 2), torch.cos(torch.log(sigma) / 2) ], dim=1) class TimeInputMLP(nn.Module): def __init__(self, dim, hidden_dims): super().__init__() layers = [] for in_dim, out_dim in pairwise((dim + 2,) + hidden_dims): layers.extend([nn.Linear(in_dim, out_dim), nn.GELU()]) layers.append(nn.Linear(hidden_dims[-1], dim)) self.net = nn.Sequential(*layers) self.input_dims = (dim,) def rand_input(self, batchsize): return torch.randn((batchsize,) + self.input_dims) def forward(self, x, sigma): sigma_embeds = get_sigma_embeds(sigma) # shape: b x 2 nn_input = torch.cat([x, sigma_embeds], dim=1) # shape: b x (dim + 2) return self.net(nn_input) model = TimeInputMLP( dim=2, hidden_dims=(16, 128, 128, 128, 128, 16) ) Source: MIT EECS 6.S183 Slide 14: Training the Noise-Prediction Model The training loop repeatedly generates noisy samples and minimizes mean squared error between predicted and true noise.\ndef training_loop(loader: DataLoader, model: nn.Module, schedule: Schedule, epochs: int = 10000): optimizer = torch.optim.Adam(model.parameters()) for _ in range(epochs): for x0 in loader: optimizer.zero_grad() sigma, eps = generate_train_sample(x0, schedule) eps_hat = model(x0 + sigma * eps, sigma) loss = nn.MSELoss()(eps_hat, eps) optimizer.backward(loss) optimizer.step() The slide shows the training loss over approximately 15,000 epochs, smoothed using a moving average. The loss gradually decreases during training.\nThe learned denoiser\n$$ \\epsilon_\\theta(x,\\sigma) $$ can be visualized as a vector field parameterized by the noise level $\\sigma$.\nThe visualization plots\n$$ x-\\sigma\\epsilon_\\theta(x,\\sigma) $$ for different $x$ and different values of $\\sigma$:\n$\\sigma=0.1$ $\\sigma=0.5$ $\\sigma=1$ The central interpretation is:\nThe model predicts expected $x_0$ given $x$ and $\\sigma$.\nSource: MIT EECS 6.S183 Slide 15: Algorithm 1 — Training a Noise-Prediction Diffusion Model Algorithm 1: Training a Noise-Prediction Diffusion Model\nInitialize neural network $f_\\theta$. While training has not converged: Sample clean data: $$ x_0\\sim p_{\\text{data}}. $$ Sample a noise level $\\sigma$ from the noise schedule. Sample Gaussian noise: $$ \\epsilon\\sim\\mathcal N(0,I). $$ Directly construct a noisy sample: $$ x_\\sigma=x_0+\\sigma\\epsilon. $$ Predict the noise contained in $x_\\sigma$: $$ \\hat{\\epsilon}=f_\\theta(x_\\sigma,\\sigma). $$ Compute the noise-prediction loss: $$ \\mathcal L(\\theta) = \\|\\epsilon-\\hat{\\epsilon}\\|_2^2. $$ Update $\\theta$ using gradient descent on $\\mathcal L(\\theta)$. End while. Source: https://github.com/yuanchenyang/smalldiffusion Slide 16: Algorithm 2 — Iterative Sampling from a Diffusion Model Algorithm 2: Iterative Sampling from a Diffusion Model\nSample an initial point from Gaussian noise: $$ x=\\sigma_{\\max}\\epsilon, \\qquad \\epsilon\\sim\\mathcal N(0,I). $$ For $$ t=N,N-1,\\ldots,1 $$ do:\nSet $$ \\sigma_{\\text{current}}=\\sigma_t, \\qquad \\sigma_{\\text{next}}=\\sigma_{t-1}. $$ Estimate the current noise / denoising direction: $$ \\hat{\\epsilon}_t = f_\\theta(x,\\sigma_{\\text{current}}). $$ Move toward the lower-noise state: $$ x \\leftarrow \\operatorname{SamplerUpdate} \\left( x, \\hat{\\epsilon}_t, \\sigma_{\\text{current}}, \\sigma_{\\text{next}} \\right). $$ End for. Return $x$. Source: https://github.com/yuanchenyang/smalldiffusion Slide 17: 3. Training Details Section 3 examines the mathematical structure of the optimal denoiser learned by the noise-prediction objective. Slide 18: The Ideal Denoiser The ideal denoiser is defined as the minimizer of the training objective:\n$$ \\epsilon^* := \\arg\\min_{\\epsilon_\\theta} \\mathbb{E}_{x_0,\\sigma,\\epsilon} \\left[ \\left\\| \\epsilon_\\theta(x_0+\\sigma\\epsilon,\\sigma)-\\epsilon \\right\\|_2^2 \\right]. $$ For a finite dataset or manifold representation $\\mathcal K$, the optimal predictor has a closed-form solution:\n$$ \\epsilon^*(x_\\sigma,\\sigma) = \\frac{ \\displaystyle \\sum_{x_0\\in\\mathcal K} (x_\\sigma-x_0) \\exp\\left( -\\frac{\\|x_\\sigma-x_0\\|^2}{2\\sigma^2} \\right) }{ \\displaystyle \\sigma \\sum_{x_0\\in\\mathcal K} \\exp\\left( -\\frac{\\|x_\\sigma-x_0\\|^2}{2\\sigma^2} \\right) }. $$ Key points:\nThe ideal denoiser is the minimizer of the training loss.\nIt is a function of both the data distribution $\\mathcal K$ and the noise level $\\sigma$.\nFor finite $\\mathcal K$, there is a closed-form solution.\nSource: MIT EECS 6.S183\nSlide 19: Denoising Vector Fields at Different Noise Levels The slide visualizes the predicted denoising direction for the same underlying $x_0$ using three noise levels:\n$\\sigma=0.1$ $\\sigma=0.5$ $\\sigma=1$ As $\\sigma$ increases:\nThe region being considered becomes larger. The denoising vectors aggregate information over a broader neighborhood of the data manifold. For small $\\sigma$, the denoising direction is much more local. Note: The scales are different (same $x_0$).\nSource: MIT EECS 6.S183 Slide 20-21: Distance to the Data Manifold The distance function\n$$ \\operatorname{dist}_{\\mathcal K}:\\mathbb{R}^n\\rightarrow\\mathbb{R} $$ is defined as\n$$ \\operatorname{dist}_{\\mathcal K}(x) := \\inf \\left\\{ \\|x-x_0\\|:x_0\\in\\mathcal K \\right\\}. $$ The gradient of the squared distance is related to projection onto the data manifold:\n$$ \\nabla \\frac{1}{2} \\operatorname{dist}_{\\mathcal K}(x)^2 = x-\\operatorname{proj}_{\\mathcal K}(x), $$ where\n$$ \\operatorname{proj}_{\\mathcal K}(x) = \\arg\\min_{x_0\\in\\mathcal K} \\|x-x_0\\|. $$ However, this construction causes a problem:\nThe distance function is not differentiable everywhere. $\\nabla\\operatorname{dist}_{\\mathcal K}(x)^2$ is not continuous. The proposed solution is:\nSoft minimum\nSource: MIT EECS 6.S183 Slide 22-23: Gaussian-Smoothed Distance Function Instead of the hard minimum, define a smooth approximation:\n$$ \\operatorname{dist}_{\\mathcal K}(x,\\sigma) := -\\sigma^2 \\log \\sum_{x_i\\in\\mathcal K} \\exp \\left( -\\frac{\\|x-x_i\\|^2}{2\\sigma^2} \\right). $$ Its gradient satisfies\n$$ \\nabla_x \\operatorname{dist}_{\\mathcal K}(x,\\sigma) = \\sigma\\epsilon^*(x,\\sigma). $$ For comparison, the original hard distance was\n$$ \\operatorname{dist}_{\\mathcal K}(x) := \\inf \\left\\{ \\|x-x_0\\|:x_0\\in\\mathcal K \\right\\}, $$ with\n$$ \\nabla \\frac12 \\operatorname{dist}_{\\mathcal K}(x)^2 = x-\\operatorname{proj}_{\\mathcal K}(x). $$ Therefore:\nThe optimal $\\epsilon^*$ has a closed form: it can be obtained via the gradient of a Gaussian-smoothed distance function.\nSource: MIT EECS 6.S183 Slide 24: 4. Sampling Details Section 4 explains how the trained denoiser is used to iteratively move a noisy sample toward the data distribution. Slide 25: From Noise Prediction to a Clean-Data Estimate Given noisy $x_\\sigma$ and noise level $\\sigma$, the learned denoiser predicts\n$$ \\epsilon_\\theta(x_\\sigma,\\sigma). $$ This produces an estimate of the underlying clean sample:\n$$ x_0 \\approx \\hat{x}_0(x_\\sigma,\\sigma) := x_\\sigma-\\sigma\\epsilon_\\theta(x_\\sigma,\\sigma). $$ The diagram visualizes:\nThe current noisy point $x_t$. An estimate $\\hat{x}_0^t$ on or near the data manifold $\\mathcal K$. The next point $x_{t-1}$, obtained by moving along the predicted denoising direction. Repeating this process progressively approaches the manifold. Sampling algorithms construct a sequence of clean-data estimates\n$$ \\hat{x}_0^t := \\hat{x}_0(x_t,\\sigma_t) $$ from a sequence $x_t$ using\n$$ x_{t-1} = x_t + (\\sigma_{t-1}-\\sigma_t) \\epsilon_\\theta(x_t,\\sigma_t). $$ Source: MIT EECS 6.S183 Slide 26: DDIM Sampler The DDIM sampler repeatedly applies the deterministic update\n$$ x_{t-1} \\leftarrow x_t + (\\sigma_{t-1}-\\sigma_t) \\epsilon_\\theta(x_t,\\sigma_t). $$ Algorithm:\nAlgorithm 1 DDIM sampler for t = N, ..., 1 do x_{t-1} ← x_t + (σ_{t-1} - σ_t) ε_θ(x_t, σ_t) return x_0 The slide also contains an implementation of the sampler and a vector-field visualization.\nThe red sampling trajectories start from high-noise regions and iteratively follow the denoising vector field toward the spiral-shaped data manifold.\nSource: MIT EECS 6.S183 Slide 27: Deterministic DDIM vs. Probabilistic DDPM Deterministic DDIM Update $$ x_{t-1} = x_t + (\\sigma_{t-1}-\\sigma_t) \\epsilon_\\theta(x_t,\\sigma_t). $$ Probabilistic DDPM Update $$ x_{t-1} = x_t + (\\sigma_{t'}-\\sigma_t) \\epsilon_\\theta(x_t,\\sigma_t) + \\eta w_t. $$ where\n$$ w_t\\sim\\mathcal N(0,I), $$ $$ \\sigma_{t-1} = \\sigma_t^\\mu \\sigma_{t'}^{\\,1-\\mu}, $$ and\n$$ \\eta = \\sqrt{ \\sigma_{t-1}^2-\\sigma_{t'}^2 }. $$ The noise scale is chosen so that the norm of the stochastic update matches the denoising update in expectation when\n$$ \\mathbb{E}\\|w_t\\|^2 = \\|\\epsilon_\\theta(x_t,\\sigma_t)\\|^2. $$ The slide notes:\n$$ 0\\le\\mu\u003c1, \\qquad \\sigma_{t'}\u003c\\sigma_{t-1}\u003c\\sigma_t. $$ Three visual examples compare sampling trajectories for:\n$\\mu=0.001$ $\\mu=0.01$ $\\mu=0.1$ As $\\mu$ increases, the trajectories become progressively more stochastic.\nFor more details on DDPM, please visit: mookjsi.github.io/posts/diffusion\nSlide 28: 5. Conditional Sampling Section 5 extends unconditional diffusion models to conditional generation. Slide 29: How Can We Sample Conditionally? The main questions are:\nHow can I sample conditionally? How can I incorporate preferences?\nThe slide contrasts:\n$$ p(x) $$ with a conditional distribution such as\n$$ p(x\\mid y=\\text{cat}). $$ The unconditional distribution contains several types of images, including:\nCat Dog Horse Conditioning on $y=\\text{cat}$ restricts generation toward the cat mode.\nNote: $x$ is now a picture, not a pixel.\nSource: MIT EECS 6.S183 Slide 30: Conditional Score Matching The same idea can be applied when labels are available.\nDataset:\n$$ \\mathcal D = \\left\\{ (x_0,c)^{(i)} \\right\\}_{i=1}^{N}. $$ The conditional score-matching objective is\n$$ \\mathcal L_{\\mathrm{CSM}}(\\theta) = \\mathbb E_{ (x_0,c)\\sim p_0,\\; t\\sim\\mathrm{Unif}[0,1],\\; x_t\\sim p_{t|0}(\\cdot|x_0) } \\left[ \\left\\| s_t^\\theta(x_t,c) - \\nabla_x \\log p_{t|0}(x_t|x_0) \\right\\|^2 \\right]. $$ The key takeaway is that instead of learning the unconditional score\n$$ \\nabla_x\\log p_t(x_t), $$ we learn the conditional score\n$$ \\nabla_x\\log p_t(x_t\\mid c). $$ Source: MIT EECS 6.S183 Slide 31: Conditional and Unconditional ODE Flows Unconditional Generation $$ \\dot{x}_t = v(x_t,t), $$ where\n$$ v(x_t,t) = -\\dot{\\sigma}_t \\sigma_t \\nabla\\log p_t(x_t). $$ Conditional Generation $$ \\dot{x}_t = v_c(x_t,t), $$ where\n$$ v_c(x_t,t) = -\\dot{\\sigma}_t \\sigma_t \\nabla\\log p_t(x_t\\mid c). $$ Thus, conditional generation modifies the ODE vector field by replacing the unconditional score with the conditional score.\nSource: MIT EECS 6.S183 Slide 32: 6. Latent Diffusion Models Section 6 introduces latent diffusion, where the diffusion process is performed in a lower-dimensional latent representation rather than directly in image space. Slide 33-34: Latent Diffusion Models — Algorithm The latent diffusion pipeline consists of five steps.\nData\nTake all training data\n$$ x_1,\\ldots,x_N $$ such as images collected from the internet.\nEncoding\nConvert all images into latent representations.\nFor a VAE, simply take the mean prediction. Latent Data\nThis creates a new dataset\n$$ z_1,\\ldots,z_N, $$ whose elements are significantly smaller than the original high-resolution images.\nLatent Diffusion Model\nBuild a diffusion model on the dataset of latent variables.\nThe diffusion model now generates latent vectors instead of full-resolution images. Decoding\nAfter sampling from the diffusion model, map the generated latent representation back into the original data space.\nThe central message of Slide 34 is:\nExactly same as before. Just with a transformed dataset.\nSource: MIT EECS 6.S184 Slide 35: Why Generate in Latent Space? The slide states:\nVirtually all AI-generated images or videos that you see are generated in latent spaces!\nWhy?\nLatent space is key because memory usage would otherwise become prohibitively large. A compressed representation also allows the model to focus on important components of the data. Examples:\nStable Diffusion Original image representation:\n$$ [3,256,256] $$ is compressed to:\n$$ [4,32,32]. $$ FLUX 2.0 Original image representation:\n$$ [3,1024,1024] $$ is compressed to:\n$$ [32,64,64]. $$ The slide includes three examples of AI-generated imagery to illustrate high-resolution generation from latent representations.\nSource: MIT EECS 6.S184 Slide 36: Parameterizing a Vector Field in a Neural Network A diffusion model can parameterize a vector field using a neural network:\n$$ u_t^\\theta(x\\mid y). $$ The network depends on three principal inputs:\nTime Latent image Prompt The network parameters are represented by $\\theta$.\nThe diagram therefore expresses a conditional vector field whose behavior depends jointly on:\nthe current diffusion time,\nthe current image latent,\nand the text condition.\nSource: MIT EECS 6.S184\nSlide 37: Encoding Time Time is only one-dimensional, while the other model variables are high-dimensional.\nTo make the time variable “count” more, it is embedded into a high-dimensional vector using sinusoidal features.\n$$ \\operatorname{TimeEmb}(t) = \\frac{1}{\\sqrt d} \\begin{bmatrix} \\cos(2\\pi w_1t) \u0026 \\cdots \u0026 \\cos(2\\pi w_{d/2}t) \u0026 \\sin(2\\pi w_1t) \u0026 \\cdots \u0026 \\sin(2\\pi w_{d/2}t) \\end{bmatrix}^{T}. $$ The frequencies are geometrically spaced:\n$$ w_i = w_{\\min} \\left( \\frac{w_{\\max}}{w_{\\min}} \\right)^{ \\frac{i-1}{d/2-1} }, \\qquad i=1,\\ldots,d/2. $$ The embedding is normalized:\n$$ \\left\\| \\operatorname{TimeEmb}(t) \\right\\| = 1. $$ Source: MIT EECS 6.S184 Slide 38: Encoding Prompts Example prompt:\n“A dog running on grass in a park at sunshine in an Italian city.”\nMost generative models embed text using pre-trained language or multimodal representations.\nPossible choices include:\nCLIP embeddings Contrastive Language-Image Pre-training T5 embeddings Other pre-trained models LLM embeddings The result is a sequence of $S$ vectors:\n$$ \\operatorname{PromptEmbed}(y_{\\mathrm{raw}}) \\in \\mathbb{R}^{S\\times k}. $$ Here:\n$S$ is the sequence length.\n$k$ is the dimensionality of each token embedding.\nSource: MIT EECS 6.S184\nSlide 39: Patchify — Turn an Image into a Sequence of Vectors Transformers operate naturally on sequences. Therefore, an image can be divided into patches and represented as a sequence.\nThe original image is represented as\n$$ x\\in\\mathbb{R}^{3\\times H\\times W}. $$ Patchification produces\n$$ \\tilde{x} = \\operatorname{Patchify}(x), $$ with\n$$ \\tilde{x} \\in \\mathbb{R}^{L\\times k}. $$ where:\n$L$ is the sequence length. $k$ is the dimensionality of each patch vector. The slide visually shows:\nA cropped image. The image divided into a rectangular patch grid. The patches flattened into a one-dimensional sequence of vectors. Image source shown on the slide:\nhttps://glorivishankar.info/blog/transformers-everywhere-patch-encoding-technique-for-vision-transformers-vit-explained/\nSource: MIT EECS 6.S184\nSlide 40: DALL·E For real images:\nGeneration is performed in a latent space rather than directly in pixel space. Text conditioning is added to control what the model generates. The slide shows two examples of generated images:\nA surreal banana-shaped hammock placed inside a room. A stylized character surrounded by flowers and plants. These examples illustrate text-conditioned image synthesis.\nSource: https://openai.com/index/dall-e-3/ Slide 41: Diffusion Transformer (DiT) Diffusion Transformer (DiT)\nA Transformer model designed for diffusion models. It adapts the Transformer architecture to the specific form required by diffusion models. The slide shows a collection of generated animal images.\nReference shown on the slide:\nPeebles, W., \u0026amp; Xie, S. (2023). Scalable diffusion models with transformers.\nProceedings of the IEEE/CVF International Conference on Computer Vision, pp. 4195–4205.\nSource: MIT EECS 6.S184 Slide 42: MovieGen MovieGen combines several of the previously introduced ideas.\nFlow Matching model Classifier-free guidance Flow Matching is performed in latent space A pre-trained VAE is used. DiT adapted to videos The slide shows examples from MovieGen:\nA generated video of a person running along a beach or rocky coastal environment.\nA video-editing example in which the appearance/content of an object held by a person is modified across frames.\nSource: https://ai.meta.com/research/movie-gen/\nSlide 43: Sora Sora extends the diffusion-model framework to video generation.\nText-conditional diffusion model Videos are compressed into a lower-dimensional latent representation. The latent representation is divided into spacetime patches. This combines three major ideas introduced earlier:\nConditional generation\nText controls the output. Latent diffusion\nGeneration occurs in a compressed representation instead of full pixel space. Patch-based Transformer processing\nVideo latents are divided into spacetime patches that can be processed as tokens. The slide contains two Sora examples:\nA surreal outdoor scene containing a large futuristic or spacecraft-like object.\nA composition consisting of many televisions/screens displaying different visual content.\nSource: https://openai.com/index/sora/\n","permalink":"https://mookjsi.github.io/posts/diffusion2/","summary":"StatLet seminar 09/04","title":"Diffusion Model and Its Applications"},{"content":"1. 서론 (Introduction) 여러분이 춤 동작을 배운다고 상상해 보세요. 기존의 방식(기존 Dynamic 3DGS)은 마치 춤추는 사람의 사진을 한 장씩 따로따로 보고 동작을 유추하는 것과 같습니다. 이 사진과 다음 사진 사이의 연결 고리를 약하게만 파악하죠. 그래서 동작이 너무 빠르거나 조명이 번쩍이면(반사 재질) 3D 모델이 깨지거나 흐릿하게 보입니다.\n이 논문에서 제안하는 TimeFormer는 춤 동작 전체가 담긴 비디오를 한 번에 훑어보는 것과 같습니다. 여러 시간대의 장면(Timestamp)을 동시에 참고하여 \u0026ldquo;아, 이 팔은 이렇게 움직이는 중이구나\u0026quot;라고 전체적인 흐름(Motion Pattern)을 파악합니다. 가장 똑똑한 점은, 연습할 때만 이 \u0026lsquo;비디오 분석 능력\u0026rsquo;을 사용하고, 실제 무대(Inference)에서는 분석 도구를 떼어버려도 몸이 기억해서 똑같이 잘 춘다는 것입니다. 덕분에 속도는 그대로 유지하면서 퀄리티만 높일 수 있습니다.\n2. 기술 설명 (Method) 이 섹션에서는 TimeFormer가 어떻게 시간적 관계를 학습하고 최적화하는지 설명합니다.\n이 그림은 TimeFormer의 핵심 개념을 보여줍니다. 오른쪽 다이어그램처럼 여러 시간대($t_i, t_j, t_k$)의 정보를 Temporal Attention을 통해 서로 참고합니다. 이를 통해 Deformation Field가 전체적인 움직임 패턴을 학습하게 됩니다.\nTimeFormer의 전체 프레임워크입니다.\n위쪽 (Base Stream): 기존의 방식대로 Canonical Space의 3D Gaussian이 Deformation Field를 거쳐 변형됩니다. 아래쪽 (TimeFormer Stream): TimeFormer가 시간적 관계를 분석하여 Deformation Field를 돕습니다. 중요한 건 두 개의 Deformation Field가 가중치(Weight)를 공유한다는 점입니다(점선 화살표). 즉, 아래쪽에서 똑똑하게 학습한 내용을 위쪽 모델도 공유받게 되어, 나중에는 아래쪽 모듈을 제거해도 됩니다.\n2.1 3D Gaussian Splatting 기초 먼저 3D Gaussian Splatting의 기본 수식입니다.\n$$ G(x) = o \\cdot e^{-\\frac{1}{2}(x-\\mu)^T \\Sigma^{-1}(x-\\mu)} $$ 수식 분석: 3D 공간의 위치 $x$에 대한 Gaussian의 영향력을 나타냅니다. $\\mu$는 중심 위치(Mean), $\\Sigma$는 공분산 행렬(Covariance Matrix)로 가우시안의 모양(타원체)을 결정합니다. $o$는 불투명도(Opacity)입니다. 이는 통계적 확률 분포 함수를 3D 렌더링의 기본 입자(Primitive)로 차용한 것으로, 미분 가능한 렌더링 파이프라인을 구축하는 핵심입니다.\n$$ C = \\sum_{i}^{N} c_i \\alpha_i \\prod_{j=1}^{i-1} (1-\\alpha_j) $$ 수식 분석: $\\alpha$-blending 식입니다. $c_i$는 색상, $\\alpha_i$는 밀도입니다. 시선 방향을 따라 정렬된 Gaussian들의 기여도를 누적하여 픽셀 색상 $C$를 결정합니다. NeRF의 Volume Rendering 적분식을 이산적(Discrete)인 Gaussian들의 합으로 근사하여 고속 렌더링을 가능하게 합니다.\n2.2 Deformation Field와 TimeFormer 동적인 장면을 표현하기 위해 Canonical Space(기준 공간)의 가우시안을 시간 $t$에 따라 변형시킵니다.\n$$ (\\Delta\\mu, \\Delta r, \\Delta s) = \\mathcal{D}(\\mu, t) $$ 수식 분석: Deformation Field $\\mathcal{D}$는 기준 위치 $\\mu$와 시간 $t$를 입력받아 위치, 회전, 크기의 변화량($\\Delta$)을 출력합니다. 이는 시공간 $R^4$에서 $R^3$로의 매핑 함수로 볼 수 있습니다.\nCross-Temporal Encoder의 구조입니다. Canonical Gaussian 위치 $\\mu$에 여러 시간대($t_0, \u0026hellip;, t_{B-1}$)를 결합하여 Transformer에 입력하고, 각 시간대에 맞는 위치 오프셋($\\Delta p$)을 출력합니다.\nTimeFormer를 위해 위치 인코딩(Positional Encoding)을 사용합니다.\n$$ \\gamma(p) = (\\sin(2^0 \\pi p), \\cos(2^0 \\pi p), ..., \\sin(2^{L-1} \\pi p), \\cos(2^{L-1} \\pi p)) $$ 수식 분석: 저주파 신호인 좌표값 $p$를 고주파 영역으로 매핑하여 신경망이 고주파수 세부 정보(High-frequency details)를 더 잘 학습하도록 돕습니다. Fourier Feature Mapping의 일종입니다.\nTimeFormer의 출력은 다음과 같이 잔차(Residual) 형태로 더해집니다.\n$$ \\mathcal{O} = MLP(F_{M-1}), \\quad \\mathcal{G}_t = \\mathcal{G}_c + \\mathcal{O} $$ 2.3 Gradient Flow Analysis (핵심 이론) 이 논문의 이론적 기여는 Gradient 분석에 있습니다. 기존 방식의 Gradient는 다음과 같습니다.\n$$ \\frac{\\partial \\Delta\\mu_i}{\\partial \\mu} = \\frac{\\partial \\mathcal{D}(\\mu, t_i)}{\\partial \\mu} $$ 하지만 TimeFormer를 적용하면 Chain Rule에 의해 항이 추가됩니다.\n$$ \\frac{\\partial \\Delta\\mu_i}{\\partial \\mu} = \\frac{\\partial \\mathcal{D}(a, t_i)}{\\partial a} \\cdot (1 + \\frac{\\partial \\mathcal{P}(\\mu, \\mathcal{T}_s)}{\\partial \\mu}) $$ 수식 분석: 여기서 $\\mathcal{P}(\\mu, \\mathcal{T}_s)$는 TimeFormer 모듈입니다. 추가된 항 $\\frac{\\partial \\mathcal{P}}{\\partial \\mu}$는 현재 시간 $t_i$뿐만 아니라 전체 타임 배치 $\\mathcal{T}_s$ (과거 및 미래)의 정보를 포함합니다. 즉, Backpropagation 과정에서 특정 시점의 학습이 다른 모든 시점의 상태를 고려하여 업데이트되도록 유도합니다. 이것이 \u0026lsquo;Global View\u0026rsquo;를 갖게 하는 수학적 원리입니다.\n데이터 흐름의 변화를 보여줍니다. 점선은 TimeFormer에 의해 시간 샘플들($t_0\u0026hellip;t_{B-1}$) 사이에 새로운 정보 흐름이 생겼음을 의미합니다.\nTimeFormer의 구현 코드와 Two-Stream 최적화 전략에 대한 의사 코드(Pseudo-code)입니다. 학습 시에는 두 스트림을 모두 계산하고, 추론 시에는 TimeFormer를 끕니다.\n2.4 Loss Function $$ \\mathcal{L} = \\lambda_c \\mathcal{L}_c + \\lambda_t \\mathcal{L}_t $$ 수식 분석: 전체 손실 함수는 Original Branch의 손실 $\\mathcal{L}_c$와 TimeFormer Branch의 손실 $\\mathcal{L}_t$의 가중 합입니다. $\\lambda_t$를 약간 작게 설정하여 TimeFormer 쪽에 과적합(Overfitting)되는 것을 방지합니다.\n3. 실험 (Experiment) TimeFormer의 성능을 검증하기 위해 다양한 데이터셋에서 실험을 진행했습니다.\nTimeFormer가 적용된 모델(오른쪽)이 더 적은 수의 점(Points)을 사용하면서도 더 높은 FPS(초당 프레임 수)와 품질(PSNR)을 보여줍니다. Canonical Space가 더 효율적으로 구성되었음을 의미합니다.\nN3DV 데이터셋(다시점 비디오)에서의 정량적 비교입니다. TimeFormer를 추가했을 때 4DGS와 STGS 모델 모두에서 PSNR(화질) 수치가 향상되었습니다.\nN3DV 데이터셋의 시각적 비교입니다. 요리 장면에서 흐릿한 부분 없이 선명한 기하학적 구조를 복원했습니다.\n프레임별 PSNR 변화 그래프입니다. TimeFormer(주황색)가 전체적으로 파란색(기본 모델)보다 위에 있으며, 특히 영상의 시작과 끝부분에서도 안정적인 품질을 유지합니다.\n학습 곡선(Convergence Speed)입니다. TimeFormer를 사용하면 Loss가 더 빠르게 감소하여 학습 속도가 빨라집니다. 두 Branch의 Loss가 비슷하게 떨어지는 것은 지식 전이(Knowledge Transfer)가 잘 되고 있음을 보여줍니다.\nHyperNeRF 데이터셋(단안 비디오) 비교입니다. 손가락 사이나 빗자루 같은 복잡한 구조를 더 명확하게 표현합니다.\nNeRF-DS 데이터셋(반사체 포함) 비교입니다. 반짝이는 컵이나 유리병의 표면 반사를 훨씬 깨끗하게 렌더링합니다.\n학습 시간과 FPS, 가우시안 개수 비교입니다. TimeFormer를 쓰면 학습 시간은 조금 늘어나지만, 추론 FPS는 오히려 높아지고 가우시안 개수는 줄어듭니다(효율성 증가).\n이 그림은 매우 흥미롭습니다. 움직임의 변화(Motion Bias)를 히트맵으로 시각화했습니다. 칼이 레몬을 자르는 순간이나 불꽃이 흔들리는 미세한 움직임을 TimeFormer가 정확히 포착하고 있음을 보여줍니다.\nHyperNeRF와 NeRF-DS 데이터셋에 대한 추가적인 정량적 수치 표입니다. 모든 지표(PSNR, SSIM)에서 성능 향상을 확인했습니다.\nAblation Study(소거법 연구) 결과입니다. Transformer 레이어 수(M)나 시간 배치 크기(B)에 크게 민감하지 않으며, \u0026ldquo;Shared Weights(가중치 공유)\u0026rdquo; 전략이 없으면 성능이 크게 떨어짐을 보여줍니다.\nCanonical Space의 가우시안 분포와 FPS를 비교한 추가 자료입니다. TimeFormer가 불필요한 가우시안을 제거하여 더 깔끔한 공간 분포를 만듭니다.\n4. 결론 (Conclusion) 이 논문은 TimeFormer라는 플러그 앤 플레이(Plug-and-play) 모듈을 제안했습니다. 이 모듈은 Global Temporal Attention을 통해 복잡한 움직임과 반사 재질을 효과적으로 학습합니다. 특히 Two-stream Optimization 전략 덕분에, 추론 시에는 추가적인 연산 비용 없이 기존 모델보다 더 빠르고 정확한 렌더링이 가능합니다. 한계점으로는 일부 복잡한 디테일이 너무 부드럽게(Overly smooth) 표현될 수 있다는 점이 있습니다.\n","permalink":"https://mookjsi.github.io/posts/paper-review-timeformer/","summary":"YBIGTA 12/01 DS Session Presentation","title":"TimeFormer: Capturing Temporal Relationships of Deformable 3D Gaussians for Robust Reconstruction"},{"content":"\nSlide 1: Preface Topic: Diffusion Models (In Process) Sources referenced: Deep Generative Modeling, Jacob M. Tomczak, 2022 Denoising Diffusion Probabilistic Models, Ho et al., 2020 Deep Unsupervised Learning using Nonequilibrium Thermodynamics, Sohl-Dickstein et al., 2015 Slide 2: Introduction - Data Representation An example of how we perceive data versus how a machine might process features. Human view: \u0026ldquo;How cute! This adorable little dog has a white soft coat and big eyes with excitement.\u0026rdquo; Visual Data: An image of a white dog. Slide 3: Computer Representation Computer view: The image is represented as a large tensor of pixel values (e.g., RGB arrays like [200, 189, 165]...). Slide 4: Latent Variable Space (1) Concept: Introduction to Latent Variable Space. We want to map the high-dimensional raw pixel data (Real Data, $x$) to a more meaningful, compressed representation. The descriptive features (\u0026ldquo;How cute\u0026rdquo;, \u0026ldquo;white soft coat\u0026rdquo;) represent the abstract information we want to capture. Slide 5: Latent Variable Space (2) $x$ (Real Data): High-dimensional pixel array. Latent Variable: A compressed vector (e.g., [1.23, -0.85, 0.44, ..., 0.03]) that encodes the semantic features of the data. Slide 6: Latent Variable Space (3) Visualizing the relationship: The raw data array corresponds to the latent vector. Slide 7: Mapping Semantics Latent Variable: Represents features like \u0026ldquo;Dog\u0026rdquo;, \u0026ldquo;Cute\u0026rdquo;, \u0026ldquo;White\u0026rdquo;, \u0026ldquo;soft\u0026rdquo;, \u0026ldquo;big eyes\u0026rdquo;, \u0026ldquo;excitement\u0026rdquo;. These abstract concepts are encoded into the numeric vector $z$. Slide 8: The Generative Goal Goal: To establish a two-way mapping. $x \\to z$: Encoding the image into latent features. $z \\to x$: Generating the image from latent features. Slide 9: The Process Make nice $z$: Generate a meaningful latent vector from semantic descriptions or distributions. Reconstruct image: Use $z$ to create $x$. Slide 10: Requirements for a Good Model Make nice $z$: The latent space should be well-structured (e.g., following a standard normal distribution). Reconstruct image well: The generated image should look like the real data. Slide 11: Example - Hierarchical VAE Hierarchical VAE: An extension of standard VAEs. Uses multiple layers of latent variables ($z_1, z_2, \u0026hellip;$) to capture features at different levels of abstraction. Slide 12: Hierarchical VAE Structure Structure: A (Generative/Top-down): $z_2 \\to z_1 \\to x$. B (Inference/Bottom-up): $x \\to z_1 \\to z_2$. Objective: Forces the model to use $z$ to create an Inductive Bias. Slide 13: The Problem - Posterior Collapse Even with hierarchy, Posterior Collapse remains a problem. Issue: The variational posterior has a bottom-up path, but the generative part has a top-down path. Sometimes the model ignores the latent code $z$ and relies solely on the powerful decoder (autoregressive part), making $z$ meaningless. Slide 14: Analyzing Posterior Collapse ELBO Equation: $$ELBO(x) = E_{q(z_1:z_2|x)}[\\ln p(x|z_1)] - KL[q(z_1|x)||p(z_1|z_2)] - KL[q(z_2|z_1)||p(z_2)]$$ Collapse condition: If $q(z_2|z_1) \\approx p(z_2) \\sim \\mathcal{N}(0,1)$, then $q$ doesn\u0026rsquo;t encode any meaningful information about the data. Slide 15: Hierarchical VAE (Top-down Inference) Solution attempt: Make the variational posterior top-down as well. Mechanism: Use residual connections ($r_1, r_2$) and delta parameters ($\\Delta\\mu, \\Delta\\sigma^2$) to guide the generation. Benefit: Forces the model to use $z$. Creates stronger inductive bias. Relieves Posterior Collapse because both Variational Posterior \u0026amp; Generative parts have a top-down path. Note: $q(z_2|z_1) \\approx p(z_2)$ cannot happen easily here. Slide 16: Introduction to Diffusion Based Deep Generative Models Comparing the structures. Diffusion Models: B (Bottom-up): Add Gaussian noise repeatedly. A (Top-down): Denoise \u0026amp; generation. Slide 17: Diffusion Process Visualization Forward (B): Start with image $x$ -\u0026gt; add noise -\u0026gt; $z_1$ -\u0026gt; \u0026hellip; -\u0026gt; $z_5$ (pure noise). Reverse (A): Start with noise $z_5$ -\u0026gt; denoise -\u0026gt; \u0026hellip; -\u0026gt; generate $x$. Slide 18: VAEs vs. DDGMs (Structural Comparison) VAEs: A (Generative): Top-down ($z_2 \\to z_1 \\to x$). B (Inference): Bottom-up ($x \\to z_1 \\to z_2$). Structure has opposite paths. DDGMs (Diffusion): A (Generative): Top-down ($z_2 \\to z_1 \\to x$). B (Inference): Bottom-up ($x \\to z_1 \\to z_2$). Same structure visually, but distinct operational paths. Slide 19: Addressing Posterior Collapse in DDGMs Question: Does Posterior Collapse happen in DDGMs? VAE: Often suffers from $q(z_2|z_1) \\approx p(z_2) \\sim \\mathcal{N}(0,1)$. DDGM: The structure is similar (opposite paths), so we need to check. Slide 20: Top-Down Fix in VAEs Recall slide 15: VAEs fixed collapse by making both paths top-down using ResNet-like connections. Does Diffusion do this? Slide 21: Diffusion\u0026rsquo;s Approach Diffusion models have the standard opposite path structure (Forward vs Reverse). Does Posterior Collapse remain? $q(z_2|z_1) \\approx p(z_2) \\sim \\mathcal{N}(0,1)$? Answer: No. Slide 22: Why No Posterior Collapse? In Diffusion, the forward process (Bottom-up B) is fixed to add noise. It forces the data to become Gaussian noise. It is not a learned parameter that can \u0026ldquo;collapse\u0026rdquo; to zero information; it is a fixed physical process. Slide 23: Paper Introduction Paper: Deep Unsupervised Learning using Nonequilibrium Thermodynamics (ICML 2015). Authors: Jascha Sohl-Dickstein, Eric A. Weiss, Niru Maheswaranathan, Surya Ganguli. Slide 24: Motivation - Nonequilibrium Thermodynamics Physical Analogy: A drop of ink diffusing in water. Equation: $\\frac{\\partial p(x,t)}{\\partial t} = D\\nabla^2 p(x,t)$ Forward Process: $dx_t = -\\frac{1}{2}\\beta x_t dt + \\beta dW_t$ Organized structure (Ink drop) $\\to$ Disorganized structure (Uniform distribution). Slide 25: Our Objective Map the diffusion process to image generation. Sequence: $x \\to z_1 \\to z_2 \\to z_3 \\to z_4 \\to z_5$ (Noise). We want to reverse this. Slide 26: Defining the Target Distribution We want to learn the distribution $p_\\theta(x)$ that generates the cat image. Problem: How can we know the distribution of $x$ from $z$? Slide 27: Formulation Strategy We need to write down $p_\\theta(x)$ with respect to latent variables $z$. Slide 28: Formulation (Top-down) - Marginalization Express $p_\\theta(x)$ by marginalizing over all latent steps: $$p_{\\theta}(x) = \\int p_{\\theta}(x, z_{1:T}) dz_{1:T}$$ Slide 29: Joint Distribution Expansion Expand the joint probability using the chain rule (Markov property): $$p_{\\theta}(x, z_{1:T}) = p_{\\theta}(x|z_1) \\prod_{i=1}^{T-1} p_{\\theta}(z_i|z_{i+1}) p_{\\theta}(z_T)$$ Slide 30: Detailed Expansion Since $p_{\\theta}(x, z_{1:T}) = p_{\\theta}(x|z_{1:T})p_{\\theta}(z_{1:T})$ By Markov property (dependency only on previous step): $$= p_{\\theta}(x|z_1) p_{\\theta}(z_1|z_2) p_{\\theta}(z_2|z_3) \\cdots p_{\\theta}(z_{T-1}|z_T) p_{\\theta}(z_T)$$ $$= p_{\\theta}(x|z_1) \\prod_{i=1}^{T-1} p_{\\theta}(z_i|z_{i+1}) p_{\\theta}(z_T)$$ Slide 31: Top-down Path Formula Top-down Integral: $$p_{\\theta}(x) = \\int p_{\\theta}(x|z_1) \\prod_{i=1}^{T-1} p_{\\theta}(z_i|z_{i+1}) p_{\\theta}(z_T) dz_{1:T}$$ This represents the path from Noise ($z_T$) back to Image ($x$). Slide 32: Formulation (Bottom-up) Now, how do we make $z$ from $x$ (Forward process)? Sequence: $x \\to z_1 \\to z_2 \\dots \\to z_5$. Slide 33: Forward Posterior Define the approximate posterior $Q$: $$Q_{\\phi}(z_{1:T}|x) = q_{\\phi}(z_1|x) \\prod_{i=2}^{T} q_{\\phi}(z_i|z_{i-1})$$ Slide 34: Forward Chain Expansion Breaking down the joint posterior: $$Q_{\\phi}(z_{1:T}|x) = q_{\\phi}(z_1|x) q_{\\phi}(z_2|z_1, x) \\cdots q_{\\phi}(z_T|z_{1:T-1}, x)$$ Utilizing Markov property: $$= q_{\\phi}(z_1|x) \\prod_{i=2}^{T} q_{\\phi}(z_i|z_{i-1})$$ Slide 35: Defining the Transition Kernel The forward step is defined as adding Gaussian noise: $$q_{\\phi}(z_i|z_{i-1}) = \\mathcal{N}(z_i | \\sqrt{1-\\beta_i}z_{i-1}, \\beta_i I)$$ Slide 36: Reparameterization Using the reparameterization trick: $$z_i = \\sqrt{1-\\beta_i}z_{i-1} + \\sqrt{\\beta_i}\\epsilon, \\quad \\epsilon \\sim \\mathcal{N}(0, I)$$ Slide 37: Learning $\\beta$? Question: Do we have to learn the schedule of $\\beta_i$? Slide 38: Fixed Variance Answer: It could be learned, but fixed $\\beta$ also works well! References: Sohl-Dickstein et al., Ho et al. Slide 39: Overall Formulation Summary Bottom-up (Encoder/Forward): $$Q_{\\phi}(z_{1:T}|x) = q_{\\phi}(z_1|x) \\prod_{i=2}^{T} q_{\\phi}(z_i|z_{i-1})$$ $$z_i = \\sqrt{1-\\beta_i}z_{i-1} + \\sqrt{\\beta_i}\\epsilon$$ Top-down (Decoder/Reverse): $$p_{\\theta}(x) = \\int p_{\\theta}(x|z_1) \\prod_{i=1}^{T-1} p_{\\theta}(z_i|z_{i+1}) p_{\\theta}(z_T) dz_{1:T}$$ Slide 40: Where are the Learnable Parameters? Bottom-up: Fixed (Gaussian noise). Top-down: Parameters $\\theta$ exist here! We need to learn the reverse process. Slide 41: Learning Parameters We learn parameters $\\theta$ by maximizing likelihood. Slide 42: Intractability Objective: Maximize $\\ln p_{\\theta}(x)$. $$\\ln p_{\\theta}(x) = \\ln \\int p_{\\theta}(x|z_1) \\prod_{i=1}^{T-1} p_{\\theta}(z_i|z_{i+1}) p_{\\theta}(z_T) dz_{1:T}$$ Problem: Can we calculate this integral? No, it\u0026rsquo;s too expensive (intractable). Slide 43: The Trick However, the forward process $Q_{\\phi}(z_{1:T}|x)$ is \u0026ldquo;easy peasy\u0026rdquo; (just adding noise). We can use this to approximate the objective. Slide 44: Importance Sampling Setup Multiply and divide by $Q$: $$= \\ln \\int Q_{\\phi}(z_{1:T}|x) \\frac{p_{\\theta}(x, z_{1:T})}{Q_{\\phi}(z_{1:T}|x)} dz_{1:T}$$ Slide 45: Expectation Form Convert integral to expectation: $$= \\ln E_{Q_{\\phi}(z_{1:T}|x)} \\left[ \\frac{p_{\\theta}(x, z_{1:T})}{Q_{\\phi}(z_{1:T}|x)} \\right]$$ This is related to Importance Sampling. Slide 46: Jensen\u0026rsquo;s Inequality We use Jensen\u0026rsquo;s Inequality: $f(\\mathbb{E}[X]) \\le \\mathbb{E}[f(X)]$ for convex $f$ (or $\\ge$ for concave like $\\ln$). $$\\ge E_{Q_{\\phi}(z_{1:T}|x)} \\left[ \\ln \\frac{p_{\\theta}(x, z_{1:T})}{Q_{\\phi}(z_{1:T}|x)} \\right]$$ Slide 47: The Lower Bound We now have a lower bound on the log-likelihood: $$\\ln p_{\\theta}(x) \\ge E_{Q_{\\phi}(z_{1:T}|x)} \\left[ \\ln \\frac{p_{\\theta}(x, z_{1:T})}{Q_{\\phi}(z_{1:T}|x)} \\right]$$ Slide 48: Expanding the Terms Substitute the definitions of $p_{\\theta}$ (reverse) and $Q_{\\phi}$ (forward): $$p_{\\theta}(x, z_{1:T}) = p_{\\theta}(x|z_1) \\prod_{i=1}^{T-1} p_{\\theta}(z_i|z_{i+1}) p_{\\theta}(z_T)$$ $$Q_{\\phi}(z_{1:T}|x) = q_{\\phi}(z_1|x) \\prod_{i=2}^{T} q_{\\phi}(z_i|z_{i-1})$$ Slide 49: Log Expansion (1) Expanding the log term inside the expectation: $$E_{Q_{\\phi}} [\\ln p_{\\theta}(x|z_1) + \\sum \\ln p_{\\theta} - \\sum \\ln q_{\\phi} - \\ln q_{\\phi}(z_1|x)]$$ Slide 50: Log Expansion (2) Grouping terms: $$= E_{Q_{\\phi}} [\\ln p_{\\theta}(x|z_1) + \\ln p_{\\theta}(z_1|z_2) + \\sum_{i=2}^{T-1} \\ln p_{\\theta}(z_i|z_{i+1}) + \\ln p_{\\theta}(z_T)$$ $$- \\sum_{i=2}^{T-1} \\ln q_{\\phi}(z_i|z_{i-1}) - \\ln q_{\\phi}(z_T|z_{T-1}) - \\ln q_{\\phi}(z_1|x)]$$ Slide 51: Regrouping for KL Divergence We want to pair matching $p$ and $q$ terms to form KL Divergences. Grouping $(p_{\\theta}(z_i|z_{i+1})$ and $q_{\\phi}(z_i|z_{i-1}))$. Slide 52: KL Divergence Recap Definition: $KL(q||p) = \\mathbb{E}_q [\\ln q - \\ln p]$ We will use this to simplify the expectation terms. Slide 53: Applying KL Definition $E_{Q_{\\phi}} [\\ln p - \\ln q] = - E_{Q_{\\phi}} [\\ln q - \\ln p] = - KL(q||p)$ Slide 54: Identifying Terms (1) Looking at the expanded equation again to match terms. Slide 55: Identifying Terms (2) The sum term becomes a sum of KL divergences: $$\\sum_{i=2}^{T-1} E [\\ln p_{\\theta}(z_i|z_{i+1}) - \\ln q_{\\phi}(z_i|z_{i-1})] = - \\sum_{i=2}^{T-1} KL(q_{\\phi}(z_i|z_{i-1}) || p_{\\theta}(z_i|z_{i+1}))$$ Slide 56: Identifying Terms (3) Placing the summation term back into the equation. Slide 57: Identifying Terms (4) Dealing with the $z_T$ term: $$E [\\ln p_{\\theta}(z_T) - \\ln q_{\\phi}(z_T|z_{T-1})] = - KL(q_{\\phi}(z_T|z_{T-1}) || p_{\\theta}(z_T))$$ Slide 58: Identifying Terms (5) Only the $z_1$ term and reconstruction term remain. Slide 59: Identifying Terms (6) The $z_1$ term: $$E [\\ln p_{\\theta}(z_1|z_2) - \\ln q_{\\phi}(z_1|x)] = - KL(q_{\\phi}(z_1|x) || p_{\\theta}(z_1|z_2))$$ Slide 60: Final Grouping All terms are now converted to Expectations or KL divergences. Slide 61: The ELBO Equation Evidence Lower Bound (ELBO): $$ \\begin{aligned} L_{ELBO} \u0026= \\mathbb{E}_{Q_{\\phi}} [\\ln p_{\\theta}(x|z_1)] \\\\ \u0026\\quad - \\sum_{i=2}^{T-1} KL\\big(q_{\\phi}(z_i \\mid z_{i-1}) \\,\\|\\, p_{\\theta}(z_i \\mid z_{i+1})\\big) \\\\ \u0026\\quad - KL\\big(q_{\\phi}(z_T \\mid z_{T-1}) \\,\\|\\, p_{\\theta}(z_T)\\big) \\\\ \u0026\\quad - KL\\big(q_{\\phi}(z_1 \\mid x) \\,\\|\\, p_{\\theta}(z_1 \\mid z_2)\\big) \\end{aligned} $$ Slide 62: Usefulness of ELBO This gives us a computable lower bound on the true log-likelihood. We maximize this ELBO to learn the parameters. Slide 63: The Reconstruction Term Focus on the first term: $\\mathbb{E}{Q{\\phi}} [\\ln p_{\\theta}(x|z_1)]$ What distribution should we use for $p_{\\theta}(x|z_1)$? Slide 64: Gaussian Reconstruction Assume Gaussian distribution: $p(x|z_1) = \\mathcal{N}(x | \\tanh(NN(z_1)), I)$ The log-likelihood of a Gaussian is proportional to the negative Mean Squared Error (MSE). $\\ln p(x|z_1) = -MSE(x, \\tanh(NN(z_1))) + const$ Slide 65: Final ELBO for Implementation Result: $$L_{ELBO} = E[-MSE] - \\sum KL - KL - KL$$ Now we can implement this in code since it consists of MSE and KL divergence terms, which are differentiable. Slide 66: Revisiting the VAE Comparison Why did we go through all this math? To check stability and Posterior Collapse again. Slide 67: Posterior Collapse in DDGMs? VAE: Collapsed if $q(z|x) \\approx \\mathcal{N}(0,1)$. DDGM: The goal is to make $z$ become Gaussian noise! So \u0026ldquo;collapse\u0026rdquo; in the VAE sense is actually the objective of the forward diffusion process. Slide 68: DDPM Paper Paper: Denoising Diffusion Probabilistic Models (NeurIPS 2020). Authors: Jonathan Ho, Ajay Jain, Pieter Abbeel. This paper simplified the training of diffusion models significantly. Slide 69: Original Model Recap Bottom-up (Forward): Gaussian noise steps. Top-down (Reverse): Learned denoising. Slide 70: Efficiency Problem Do we have to sample iteratively $i=1\u0026hellip;T$ just to get the forward noise $z_T$? $z_i = \\sqrt{1-\\beta_i}z_{i-1} + \\sqrt{\\beta_i}\\epsilon$ Slide 71: Cumulation Trick (1) We can skip steps. $z_2 = \\sqrt{\\alpha_2}z_1 + \\sqrt{1-\\alpha_2}\\epsilon_2$ Substitute $z_1$: $z_2 = \\sqrt{\\alpha_2}(\\sqrt{\\alpha_1}x + \\sqrt{1-\\alpha_1}\\epsilon_1) + \\sqrt{1-\\alpha_2}\\epsilon_2$ (Where $\\alpha_i = 1 - \\beta_i$) Slide 72: Cumulation Trick (2) Combining Gaussians: $z_t = \\sqrt{\\alpha_t}z_{t-1} + \\sqrt{1-\\alpha_t}\\epsilon_t$ By induction, we can express $z_t$ directly from $x$. Slide 73: Cumulation Trick (3) Result: $$z_t = \\sqrt{\\bar{\\alpha}_t}x + \\sqrt{1-\\bar{\\alpha}_t}\\epsilon$$ Where $\\bar{\\alpha}t = \\prod{s=1}^t \\alpha_s$. Mean: $\\sqrt{\\bar{\\alpha}_t}x$ Variance: $(1-\\bar{\\alpha}_t)I$ Slide 74: Closed Form Forward Step We can sample $z_t$ at any timestep $t$ in one go: $$q(z_t|x) = \\mathcal{N}(z_t | \\sqrt{\\bar{\\alpha}_t}x, (1-\\bar{\\alpha}_t)I)$$ Slide 75: New Model Formulation Forward: Directly sample $z_t$ using the cumulation trick. Reverse: Same learned process. Slide 76: DDPM Learning Parameters We revisit the loss function derivation with this new trick in mind. Objective: Maximize $\\ln p_{\\theta}(x)$. Slide 77: Deriving DDPM Loss (1) Using the same variational bound logic: $$= E_Q [\\ln \\frac{p(z_T) \\prod p(z_{t-1}|z_t) p(x|z_1)}{Q(z_T|x) \\prod Q(z_{t-1}|z_t, x)}]$$ Slide 78: Deriving DDPM Loss (2) Grouping terms into KL divergences again. Terminology: $L_T$: KL between $Q(z_T|x)$ and $p(z_T)$ (Prior matching). $L_{t-1}$: KL between $Q(z_{t-1}|z_t, x)$ and $p_{\\theta}(z_{t-1}|z_t)$ (Denoising matching). $L_0$: Reconstruction log likelihood. Slide 79: Loss Terms Definition $L_T = D_{KL}(Q_{\\phi}(z_T|x) || p(z_T))$ $L_{t-1} = D_{KL}(Q_{\\phi}(z_{t-1}|z_t, x) || p_{\\theta}(z_{t-1}|z_t))$ $L_0 = -E_{Q}[ \\ln p_{\\theta}(x|z_1) ]$ Total Loss: Minimize $\\sum L$ terms. Slide 80: The Posterior $q(z_{t-1}|z_t, x_0)$ This term $Q_{\\phi}(z_{t-1}|z_t, x)$ is tractable! It is a Gaussian distribution $\\mathcal{N}(\\tilde{\\mu}_t, \\tilde{\\beta}_t I)$. Mean $\\tilde{\\mu}_t$: A weighted combination of $x_0$ and $z_t$. Variance $\\tilde{\\beta}_t$: Function of $\\beta$ and $\\bar{\\alpha}$. Slide 81: Posterior Derivation Proof involves Gaussian conditioning formulas. Combining the forward equations allows us to solve for the distribution of $z_{t-1}$ given $z_t$ and $x_0$. Slide 82: Loss Summation We sum the expectations of the loss terms. Slide 83: Expectation Simplification $L_T$ relies on $z_T$. $L_{t-1}$ relies on $z_t, z_{t-1}$. By Markov chain property, we calculate expectations appropriately. Slide 84: Minimization Objective Minimize $\\sum_{t=1}^T \\mathbb{E}_{q}[L_t]$. Slide 85: Randomized Time Sampling Instead of summing all $T$ terms every step, we can sample $t \\sim Uniform(1, \\dots, T)$. Minimize $E_{t} [E_{q}[L_t]]$. Slide 86: Gradient Descent We can take the gradient of this expected loss. Slide 87: Efficient Training OOM: Calculating all $T$ steps is memory intensive. Solution: Only calculate one random $t$ per optimization step. Slide 88: Analyzing the Loss Let\u0026rsquo;s look at the full ELBO equation again. Slide 89: Positivity of KL KL divergences are non-negative. Since our models are not perfect approximations, these KL terms will be strictly positive. Slide 90: Accumulation of Error As $T$ grows (many timesteps), there are many KL terms. This makes the ELBO value very small (large negative). Slide 91: Unstable Learning Summing many KL terms can lead to variance issues and unstable learning. Slide 92: Changing the Goal We focus on the specific term: $L_{t-1} = D_{KL}(Q(z_{t-1}|z_t, x) || p_{\\theta}(z_{t-1}|z_t))$. Slide 93: Matching Distributions Our goal is to make the learned reverse process $p_{\\theta}(z_{t-1}|z_t)$ approximate the true posterior $q_{\\phi}(z_{t-1}|z_t, x)$. Slide 94: Gaussian Matching Both distributions are Gaussian. $q \\sim \\mathcal{N}(\\tilde{\\mu}_t, \\tilde{\\beta}_t I)$ $p_{\\theta} \\sim \\mathcal{N}(\\mu_{\\theta}, \\sigma_t^2 I)$ (Usually $\\sigma_t^2$ is fixed to $\\beta_t$ or $\\tilde{\\beta}_t$). Slide 95: KL between Gaussians The KL divergence between two Gaussians with diagonal covariance is proportional to the MSE of their means. Minimize: $$ \\frac{1}{2\\sigma_t^2} \\left\\lVert \\tilde{\\mu}_t - \\mu_{\\theta} \\right\\rVert^2 $$ Slide 96: Parametrization of $\\mu_{\\theta}$ We know $\\tilde{\\mu}_t(z_t, x)$ can be written in terms of $z_t$ and the noise $\\epsilon$ used to generate it. $\\tilde{\\mu}_t = \\frac{1}{\\sqrt{\\alpha_t}} (z_t - \\frac{\\beta_t}{\\sqrt{1-\\bar{\\alpha}_t}}\\epsilon)$ So, we should parameterize $\\mu_{\\theta}$ to predict $\\epsilon$! $$ \\mu_{\\theta} = \\frac{1}{\\sqrt{\\alpha_t}} \\left(z_t - \\frac{\\beta_t}{\\sqrt{1-\\bar{\\alpha}_t}}\\epsilon_{\\theta}(z_t, t)\\right) $$ Slide 97: Derivation Step 1 Recall the definition of $\\tilde{\\mu}_t$ (weighted average of $x_0$ and $z_t$). Slide 98: Derivation Step 2 Substitute $x_0$ with its expression derived from $z_t$ and $\\epsilon$. $x_0 = \\frac{1}{\\sqrt{\\bar{\\alpha}_t}}(z_t - \\sqrt{1-\\bar{\\alpha}_t}\\epsilon)$ Slide 99: Derivation Step 3 Simplify the algebra to get the expression for $\\tilde{\\mu}_t$ solely in terms of $z_t$ and $\\epsilon$. Slide 100: Matching Means $$ \\text{Since }\\tilde{\\mu}_t\\text{ depends on }\\epsilon\\text{, our model }\\mu_{\\theta}\\text{ should approximate it by using a neural network }\\epsilon_{\\theta}(z_t, t)\\text{ to predict that noise.} $$ Slide 101: Comparison $$ \\text{Comparison of the target mean }\\tilde{\\mu}_t\\text{ and the model mean }\\mu_{\\theta}\\text{.} $$ They are identical in form, except one uses true noise $\\epsilon$ and the other uses predicted noise $\\epsilon_{\\theta}$. Slide 102: Difference of Means $$ \\text{Calculating }\\tilde{\\mu}_t - \\mu_{\\theta}\\text{.} $$ Everything cancels out except the noise terms. Difference $\\propto (\\epsilon - \\epsilon_{\\theta})$. Slide 103: Simplified Loss Function The loss becomes weighted MSE between true noise and predicted noise. $$ L_{simple} = \\mathbb{E}_{t, x_0, \\epsilon} \\left[ \\left\\lVert \\epsilon - \\epsilon_{\\theta}\\big(\\sqrt{\\bar{\\alpha}_t}x_0 + \\sqrt{1-\\bar{\\alpha}_t}\\,\\epsilon, t\\big) \\right\\rVert^2 \\right] $$ $\\lambda_t$ is a weighting term derived from the variances. Slide 104: Final Simplification Ho et al. (DDPM) found that ignoring the weighting term $\\lambda_t$ (setting it to 1) works better in practice. It puts more weight on difficult aspects of the denoising task. Slide 105: The \u0026ldquo;Simple\u0026rdquo; Loss $$ L_{simple} = \\mathbb{E}_{t, x_0, \\epsilon} \\left[ \\left\\lVert \\epsilon - \\epsilon_{\\theta}\\big(\\sqrt{\\bar{\\alpha}_t}x_0 + \\sqrt{1-\\bar{\\alpha}_t}\\epsilon, t\\big) \\right\\rVert^2 \\right] $$ We simply train a network to predict the noise added to the image. Slide 106: Algorithms Algorithm 1 (Training): Sample $x_0$. Sample $t$. Sample noise $\\epsilon$. Gradient descent on $|| \\epsilon - \\epsilon_{\\theta}(\\text{noisy input}, t) ||^2$. Algorithm 2 (Sampling): Start from $x_T \\sim \\mathcal{N}(0, I)$. Iteratively denoise: $x_{t-1} = \\frac{1}{\\sqrt{\\alpha_t}}(x_t - \\dots \\epsilon_{\\theta}(x_t, t)) + \\sigma_t z$. Slide 107: Comparison of Training Methods (A) Full ELBO (Sohl-Dickstein): Requires $T$-step gradients, large memory, slow convergence. (B) Simplified Noise-Prediction (Ho et al.): One-step gradient (random $t$), no KL accumulation, efficient, stable training. Slide 108: Conclusion Thank You. ","permalink":"https://mookjsi.github.io/posts/diffusion/","summary":"A presentation I gave at a YBIGTA. Mathematical derivation of DGM","title":"Diffusion Models: From VAEs to DDPM Derivation"},{"content":"개요 엄청난 독서광이라 세상의 모든 책을 읽은 친구(Large Language Model)가 있다고 상상해 보세요. 이 친구는 글은 기가 막히게 잘 쓰지만, 태어나서 한 번도 그림이나 사진을 본 적이 없습니다. 반대로, 그림만 하루 종일 봐서 시각적인 정보는 완벽하게 알지만 말주변이 없는 친구(Vision Encoder)도 있습니다.\nFlamingo는 이 두 친구를 이어주는 \u0026lsquo;마법의 통역사\u0026rsquo; 같은 모델입니다.\n그림 잘 보는 친구가 사진을 보고 \u0026ldquo;이건 털이 복슬복슬한 고양이야\u0026quot;라고 정보를 압축해서 넘겨주면, Flamingo의 특별한 장치(Perceiver Resampler 등)가 이것을 글 잘 쓰는 친구가 이해할 수 있는 언어로 번역해 줍니다.\n가장 대단한 점은 **\u0026lsquo;눈치(Few-Shot Learning)\u0026rsquo;**가 엄청나게 빠르다는 것입니다. 예전에는 인공지능에게 \u0026ldquo;이건 고양이고, 이건 강아지야\u0026quot;라고 수만 번 가르쳐야(Fine-tuning) 겨우 알아들었습니다. 하지만 Flamingo는 마치 똑똑한 고등학생처럼, 시험 문제집에서 예시 문제 한두 개만 쓱 보여주면(Few-Shot), 바로 원리를 깨닫고 처음 보는 문제도 척척 풀어냅니다. 사진과 글이 섞여 있는(Interleaved) 복잡한 블로그 게시물 같은 것도 순서대로 이해하고 대화할 수 있는 능력을 갖췄습니다.\n1. 서론 (Introduction) 이 논문은 비전(Vision)과 언어(Language)를 결합한 멀티모달 모델인 Flamingo를 소개합니다. 기존 모델들은 새로운 작업을 수행하기 위해 수천 개의 데이터로 모델을 미세 조정(Fine-tuning)해야 했습니다. 하지만 Flamingo는 사전 학습된 강력한 Vision Encoder와 Large Language Model(LLM)을 결합하여, 단 몇 개의 예시(Few-Shot)만으로도 이미지 및 비디오 이해 작업에서 최고 성능(SOTA)을 달성합니다.\n이 그림은 Flamingo가 이미지와 텍스트가 섞인 입력을 받아, 동물 분류, 도시 이름 맞추기, 수학 문제 풀이 등 다양한 작업을 수행하는 것을 보여줍니다. 특히 몇 개의 예시만 주어지면(Few-shot prompting) 새로운 태스크에 빠르게 적응하는 것을 확인할 수 있습니다.\n왼쪽은 Flamingo가 별도의 Fine-tuning 없이도, 수천 배의 데이터를 사용해 학습한 기존 모델들(SOTA)보다 16개 중 6개 태스크에서 더 뛰어난 성능을 보임을 나타냅니다. 오른쪽은 모델의 크기(Parameters)와 샷(Shot) 수가 늘어날수록 성능이 향상됨을 보여줍니다.\n2. 기술적 설명 (Technical Description) Flamingo의 핵심은 이미 잘 학습된 Vision Encoder와 LLM을 \u0026lsquo;얼리지(Frozen)\u0026rsquo; 않은 상태로 두고, 둘 사이를 연결하는 새로운 레이어만 학습시키는 것입니다. 이를 통해 기존 모델들이 가진 방대한 지식을 잊어버리지 않으면서(Catastrophic Forgetting 방지) 시각 정보를 통합합니다.\n2.1 아키텍처 (Architecture) 입력된 시각 데이터(이미지/비디오)는 Vision Encoder를 거쳐 Perceiver Resampler로 들어갑니다. 여기서 고정된 개수의 Visual Token으로 변환된 후, LLM 층 사이에 삽입된 GATED XATTN-DENSE 레이어를 통해 언어 모델에 시각 정보가 주입됩니다. 파란색 부분은 학습되지 않는 Frozen 상태, 보라색 부분만 학습되는 파라미터입니다.\n2.2 Visual Processing \u0026amp; Perceiver Resampler Vision Encoder(NFNet)는 시각적 특징을 추출합니다. 하지만 이미지나 비디오의 해상도나 길이에 따라 특징맵의 크기가 달라질 수 있습니다. 이를 해결하기 위해 Perceiver Resampler를 도입했습니다.\n이 모듈은 가변적인 크기의 시각적 특징(Visual features)을 입력받아, 고정된 개수(예: 64개)의 Visual Token으로 변환합니다. 이는 Transformer 기반 구조로, 학습 가능한 Latent Query를 사용하여 시각 정보에서 중요한 부분만 추출합니다. 이를 통해 계산 복잡도를 줄이고 LLM이 시각 정보를 효율적으로 처리하게 합니다.\n2.3 GATED XATTN-DENSE \u0026amp; Conditioning 추출된 시각 정보는 LLM이 다음 토큰을 예측할 때 활용됩니다. 이를 위해 기존 LLM 레이어 사이에 새로운 Cross-Attention 레이어를 삽입합니다.\n기존 LLM 블록 앞에 Cross-Attention(시각 정보 참조)과 Feed-Forward 레이어를 추가했습니다. 중요한 점은 Tanh Gating 기법을 사용했다는 것입니다.\n초기에 Tanh 게이트 값은 0으로 설정됩니다. 이는 학습 초기에는 시각 정보를 무시하고 오로지 언어 모델의 원래 성능 그대로 작동하게 하여 학습 안정성을 높입니다. 학습이 진행될수록 게이트 값이 커지며 시각 정보를 받아들입니다.\n수식 설명 (Likelihood Modeling):\n이 모델은 인터리브 된(섞인) 이미지와 비디오 $x$가 주어졌을 때 텍스트 $y$의 확률을 다음과 같이 모델링합니다.\n$$ p(y|x) = \\prod_{l=1}^{L} p(y_l \\mid y_{\u0026lt;l}, x_{\\leq l}) $$\n이 수식은 조건부 확률의 연쇄 법칙(Chain Rule)을 나타냅니다.\n$y_l$: 현재 예측하려는 $l$번째 언어 토큰입니다. $y_{\u0026lt;l}$: 이전에 생성된 모든 텍스트 토큰들입니다. $x_{\\le l}$: 현재 텍스트 토큰 $y_l$보다 시퀀스상 이전에 등장한 이미지/비디오들의 집합입니다. 의미: Flamingo는 텍스트를 생성할 때, 텍스트의 문맥($y_{\u0026lt;l}$)뿐만 아니라, 현재 시점 이전에 나왔던 모든 시각 정보($x_{\\le l}$)를 조건(Condition)으로 하여 다음 단어를 예측합니다. 이는 자기회귀(Autoregressive) 생성 방식입니다.\n2.4 Multi-visual Input \u0026amp; Data Flamingo는 텍스트와 이미지가 섞인 데이터를 처리하기 위해 특별한 마스킹 기법을 사용합니다.\n모델은 텍스트 토큰을 예측할 때, 해당 텍스트 직전에 나온 이미지에만 Cross-Attention을 수행하도록 마스킹 처리(진한 파란색) 됩니다. 하지만 Self-Attention(텍스트끼리의 관계)을 통해 전체 문맥은 유지됩니다.\n지원 예제(Support examples) 이미지와 텍스트를 나열하고, 마지막에 쿼리(Query) 이미지를 붙여 모델이 답을 생성하게 유도하는 구조를 보여줍니다.\nM3W: 웹페이지에서 수집한 이미지-텍스트가 섞인 데이터 (Few-shot 능력의 핵심). Image-Text Pairs (ALIGN, LTIP): 이미지와 캡션 쌍. Video-Text Pairs (VTP): 비디오와 캡션 쌍. 3. 실험 (Experiments) 실험은 Flamingo가 얼마나 적은 데이터로 새로운 태스크에 적응하는지, 그리고 SOTA 모델들과 비교해 어떤 성능을 내는지를 중점적으로 다룹니다.\n3.1 Few-Shot Learning 성능 Flamingo는 단 4개의 Shot만으로도 이전의 Zero/Few-shot SOTA를 압도합니다. 특히 6개의 태스크에서는 수천~수십만 개의 데이터로 Fine-tuning 된 모델들보다 32-shot Flamingo가 더 높은 성능을 기록했습니다. 이는 데이터 효율성 측면에서 혁신적인 결과입니다.\n3.2 Fine-tuning \u0026amp; Classification 데이터를 충분히 주고 학습시키면 VQAv2, VATEX 등 5개 태스크에서 새로운 SOTA를 달성함을 보여줍니다.\nContrastive 모델보다는 다소 성능이 떨어지지만, RICES(유사한 예시를 검색해서 프롬프트에 넣는 방법)를 사용하면 성능이 크게 향상됨을 보여줍니다.\n3.3 Ablation Studies (소거 연구) M3W(인터리브 데이터)가 없으면 성능이 17% 하락합니다. Tanh gating이 없으면 학습이 불안정하고 성능이 떨어집니다. Perceiver Resampler가 MLP나 바닐라 Transformer보다 효율적이고 성능이 좋습니다. Resampler의 크기, Multi-image attention 방식, LM 사전 학습 데이터(C4 vs MassiveText) 등의 영향을 분석합니다.\n데이터의 양보다 질(LTIP 데이터셋)이 중요하며, 여러 데이터셋을 합칠 때 단순 병합보다 Gradient Accumulation 방식이 더 효과적임을 보여줍니다.\n성별이나 피부색에 따른 성능 차이가 통계적으로 유의미하지 않음(p-value \u0026gt; 0.05)을 보여줍니다.\n4. 결론 (Conclusion) Flamingo는 거대 언어 모델(LLM)과 시각 모델을 효과적으로 연결하여, 최소한의 학습 데이터(Few-shot)만으로 다양한 멀티모달 태스크를 수행할 수 있는 범용 모델입니다.\n핵심 기여: Perceiver Resampler와 GATED XATTN-DENSE를 도입하여 시각-언어 간의 간극을 줄였고, M3W 데이터셋을 통해 인터리브 데이터 처리 능력을 확보했습니다. 의의: 별도의 파인 튜닝 없이도 프롬프트만으로 시각적 질문 응답, 캡션 생성, 대화 등이 가능함을 입증하여, 범용 인공지능(AGI)으로 가는 중요한 발판을 마련했습니다. ","permalink":"https://mookjsi.github.io/posts/paper-review-flamingo/","summary":"YBIGTA DS Session 11/25 Presentation","title":"Flamingo: a Visual Language Model for Few-Shot Learning"},{"content":"\n**\u0026lsquo;위조지폐범(G)\u0026rsquo;**과 **\u0026lsquo;경찰(D)\u0026rsquo;**이 있다고 상상해 보세요.\n위조지폐범 (Generator, G): 이 친구의 목표는 진짜 같은 위조지폐를 만드는 것입니다. 처음에는 아주 서툴러서 종이에 그림을 그린 수준의 가짜 돈을 만듭니다. 경찰 (Discriminator, D): 이 경찰의 임무는 진짜 돈과 위조지폐범이 만든 가짜 돈을 구별하는 것입니다. 처음에는 위조지폐가 너무 가짜 같아서 구별하기 아주 쉽습니다. 이제 이 둘이 서로 **경쟁(adversarial)**을 시작합니다.\n**경찰(D)**은 진짜 돈 수백만 장과 위조지폐범(G)이 만든 가짜 돈 수백만 장을 보면서 진짜와 가짜를 구별하는 능력을 훈련합니다. 점점 똑똑해져서 웬만한 가짜는 다 잡아냅니다. **위조지폐범(G)**은 자기가 만든 돈이 경찰(D)에게 계속 걸리자, 어떻게 하면 경찰을 속일 수 있을지 연구합니다. \u0026ldquo;아, 홀로그램이 없어서 걸렸구나\u0026rdquo;, \u0026ldquo;종이 질감이 달라서 걸렸구나\u0026rdquo; 등등 경찰(D)이 무엇을 보고 가짜로 판단하는지, 그 피드백을 받아서(이것이 backpropagation입니다) 점점 더 정교한 위조지폐를 만듭니다. 이제 위조지폐범(G)이 만든 가짜 돈이 너무 정교해져서 경찰(D)이 헷갈리기 시작합니다. 그럼 **경찰(D)**은 더 열심히 훈련해서, 아주 미세한 차이점(예: 잉크 냄새)까지 구별해내려고 노력합니다. 이 경쟁은 계속됩니다. 이 게임의 최종 목표는 위조지폐범(G)이 너무 완벽한 위조지폐를 만들어서, 경찰(D)이 이게 진짜인지 가짜인지 구별할 확률이 **정확히 50% (즉, 찍는 수준)**가 되는 것입니다. 이 순간, 위조지폐범(G)은 \u0026lsquo;진짜 돈의 분포(distribution)\u0026lsquo;를 완벽하게 학습했다고 말할 수 있습니다.\n이 논문은 이 아이디어를 컴퓨터 모델, 특히 multilayer perceptrons (신경망)에 적용한 것입니다. $G$는 가짜 이미지(데이터)를 만들고, $D$는 진짜 이미지(데이터)와 $G$가 만든 가짜 이미지를 구별하도록 훈련합니다.\nI. 서론 (Introduction) 이 논문은 generative models (생성 모델)을 학습하기 위한 새로운 프레임워크인 **Generative Adversarial Nets (GAN)**을 제안합니다.\n기존의 deep generative models (심층 생성 모델)들은 maximum likelihood estimation (최대우도추정) 같은 전략을 사용했는데, 이 과정에서 매우 복잡하고 다루기 힘든 확률적 계산 (intractable probabilistic computations)이 많이 필요했습니다. 이 때문에 Markov chains (MCMC) 같은 근사적인 방법을 사용해야 했고, 이는 학습을 어렵고 느리게 만들었습니다.\n이 논문은 이런 어려움을 피하는 새로운 방법을 제시합니다. 바로 **adversarial process (적대적 과정)**을 이용하는 것입니다. 두 개의 모델, 즉 데이터 분포를 포착하는 **generative model ($G$)**과 샘플이 $G$가 아닌 실제 학습 데이터에서 왔을 확률을 추정하는 **discriminative model ($D$)**을 동시에 학습시킵니다.\n$G$의 학습 절차는 $D$가 실수할 확률을 최대화하는 것입니다. 이 프레임워크는 minimax two-player game에 해당합니다. 이 논문은 $G$와 $D$가 충분한 용량(capacity)을 가질 때, $G$가 학습 데이터의 분포를 완벽히 복구하고 $D$는 모든 곳에서 $\\frac{1}{2}$를 출력하는 유일한 해가 존재함을 이론적으로 보입니다.\n가장 큰 장점은 $G$와 $D$가 multilayer perceptrons (다층 퍼셉트론)으로 정의될 때, 전체 시스템이 **backpropagation (역전파)**만으로 학습될 수 있다는 것입니다. 학습이나 샘플 생성 과정에서 Markov chains나 approximate inference (근사 추론) 네트워크가 전혀 필요하지 않습니다.\nII. 기술 설명 (Technology Description) Adversarial nets 프레임워크는 두 모델이 모두 multilayer perceptrons일 때 가장 간단하게 적용됩니다.\nGenerator ($G$): $G$는 입력 노이즈 변수에 대한 prior $p_z(z)$ (예: 랜덤 노이즈)를 입력받아, 데이터 공간으로의 매핑 $G(z; \\theta_g)$을 수행합니다. $G$는 파라미터 $\\theta_g$를 갖는 미분 가능한 함수(신경망)입니다. Discriminator ($D$): $D$는 데이터 $x$를 입력받아 $D(x; \\theta_d)$라는 단일 스칼라 값을 출력합니다. 이 값은 $x$가 $G$가 생성한 $p_g$가 아닌, 실제 데이터 $p_{data}$로부터 왔을 확률을 나타냅니다. $D$는 파라미터 $\\theta_d$를 갖는 신경망입니다. $D$는 실제 데이터($x$)와 $G$가 만든 가짜 데이터($G(z)$) 모두에 대해 정답 레이블을 맞힐 확률을 최대화하도록 학습됩니다. 동시에 $G$는 $\\log(1 - D(G(z)))$를 최소화하도록, 즉 $D$가 속아서 $D(G(z))$를 1에 가깝게 만들도록 학습됩니다.\n이것이 바로 minimax game의 핵심입니다.\nEquation (1): 이 게임의 가치 함수(Value function) $V(G, D)$는 다음과 같습니다. $$ \\min_{G} \\max_{D} V(D, G) = \\mathbb{E}_{x \\sim p_{data}(x)}[\\log D(x)] + \\mathbb{E}_{z \\sim p_z(z)}[\\log(1 - D(G(z)))] $$ $\\max_{D} V(D, G)$: $D$의 관점입니다. $D$는 $V$를 최대화하려 합니다. $\\mathbb{E}_{x \\sim p_{data}(x)}[\\log D(x)]$ : 실제 데이터 $x$ 가 주어졌을 때, $D(x)$ (진짜라고 판단할 확률)가 1에 가까워지도록 합니다. $\\log(1)$ 은 0으로 최대값입니다. $\\mathbb{E}_{z \\sim p_z(z)}[\\log(1 - D(G(z)))]$: 가짜 데이터 $G(z)$가 주어졌을 때, $D(G(z))$ (진짜라고 판단할 확률)가 0에 가까워지도록 합니다. $\\log(1-0)$은 0으로 최대값입니다. 즉, $D$는 진짜는 진짜로(1), 가짜는 가짜로(0) 완벽하게 분류하도록 학습됩니다. $\\min_{G} V(D, G)$: $G$의 관점입니다. $G$는 $V$를 최소화하려 합니다. $G$ 는 첫 번째 항( $\\mathbb{E}_{x \\sim p_{data}(x)}[\\log D(x)]$ )에 영향을 줄 수 없습니다. $G$는 두 번째 항($\\mathbb{E}_{z \\sim p_z(z)}[\\log(1 - D(G(z)))]$)만 제어할 수 있습니다. $G$는 $D$가 $G(z)$를 진짜라고 속게(즉, $D(G(z))$가 1이 되게) 만들어야 합니다. $D(G(z))$가 1에 가까워지면 $\\log(1 - 1)$은 $-\\infty$에 가까워지며, 이는 $V$를 최소화하는 방향입니다. 이 그림은 이 적대적 학습 과정을 시각적으로 보여줍니다. $p_{data}$ (검은 점선, 실제 데이터)와 $p_g$ (녹색 실선, $G$가 생성)가 있고, $D$ (파란 파선)가 이 둘을 구별하려 합니다. (b)에서 $D$가 두 분포를 구별하도록 업데이트되고, (c)에서 $G$가 $D$를 속이는 방향(즉, $D$가 \u0026lsquo;진짜\u0026rsquo;라고 판단하는 높은 영역)으로 $p_g$를 이동시키도록 업데이트됩니다. (d)는 $p_g = p_{data}$가 되어 $G$와 $D$가 더 이상 개선될 수 없는 평형 상태($D(x) = \\frac{1}{2}$)에 도달한 것을 보여줍니다.\nAlgorithm 1은 이 과정을 학습하는 구체적인 알고리즘을 보여줍니다. minibatch stochastic gradient descent (미니배치 확률적 경사 하강법)을 사용합니다. 학습 루프 안에서:\n$D$를 $k$ 스텝 동안 최적화합니다. (실험에서는 $k=1$을 사용)\n노이즈 샘플 $z$와 실제 데이터 샘플 $x$를 미니배치로 뽑습니다. $D$의 stochastic gradient (확률적 경사)를 상승 (ascending)시킵니다. $D$ Gradient Update: $$ \\nabla_{\\theta_d}\\frac{1}{m}\\sum_{i=1}^{m}[\\log D(x^{(i)}) + \\log(1 - D(G(z^{(i)})))] $$ $G$를 1 스텝 최적화합니다.\n새로운 노이즈 샘플 $z$를 미니배치로 뽑습니다. $G$의 stochastic gradient (확률적 경사)를 하강 (descending)시킵니다. $G$ Gradient Update: $$ \\nabla_{\\theta_g}\\frac{1}{m}\\sum_{i=1}^{m}\\log(1 - D(G(z^{(i)})))] $$ 이 논문은 $G$를 학습시킬 때 $\\log(1 - D(G(z)))$를 최소화하는 것보다 $\\log D(G(z))$를 최대화하는 것이 초기에 더 강력한 gradient를 제공한다고 지적합니다.\nProposition 1: 주어진 $G$에 대해, 최적의 판별자 $D$는 다음과 같습니다. $$ D_G^*(x) = \\frac{p_{data}(x)}{p_{data}(x) + p_g(x)} $$ 증명:\n목표: $G$가 고정되어 있을 때, $D$는 $V(G, D)$를 최대화하려고 합니다. $V(G, D)$는 다음과 같습니다 : $$ V(G, D) = \\int_x p_{data}(x) \\log(D(x)) dx + \\int_z p_z(z) \\log(1 - D(G(z))) dz $$ $$ = \\int_x \\left[ p_{data}(x) \\log(D(x)) + p_g(x) \\log(1 - D(x)) \\right] dx $$ ($z$에 대한 적분을 $x$에 대한 적분으로 변환. $p_g(x)$는 $G(z)$ 샘플들의 분포)\n$V(G, D)$는 모든 $x$에 대한 적분입니다. 이 적분값을 최대화하려면, 적분 안의 함수, 즉 $f(y) = a \\log(y) + b \\log(1-y)$ 형태의 값을 모든 $x$ 지점에서 개별적으로 최대화하면 됩니다. 여기서 $y = D(x)$, $a = p_{data}(x)$, $b = p_g(x)$입니다.\n이 함수의 최댓값을 찾기 위해 $y$에 대해 미분하여 0으로 설정합니다: $$ \\frac{d}{dy} f(y) = \\frac{a}{y} + \\frac{b(-1)}{1-y} = \\frac{a}{y} - \\frac{b}{1-y} $$ $$ \\frac{a}{y} - \\frac{b}{1-y} = 0 \\Rightarrow \\frac{a}{y} = \\frac{b}{1-y} \\Rightarrow a(1-y) = b(y) $$ $$ a - ay = by \\Rightarrow a = (a+b)y \\Rightarrow y = \\frac{a}{a+b} $$ 결론: $y = D(x)$, $a = p_{data}(x)$, $b = p_g(x)$를 다시 대입하면, $V(G, D)$를 최대화하는 최적의 $D(x)$는 정확히 다음과 같습니다. $$ D_G^*(x) = \\frac{p_{data}(x)}{p_{data}(x) + p_g(x)} $$ Theorem 1: $C(G)$ 의 전역 최소값은 $p_g = p_{data}$ 일 때만 달성되며, 그 값은 $-\\log 4$ 이다.\n증명:\n$C(G)$ 정의: $C(G)$ 는 $G$ 가 얼마나 못하고 있는지를 나타내는 $G$ 의 \u0026lsquo;비용 함수\u0026rsquo;입니다. $D$ 가 항상 최적의 $D_G^*(x)$ 라고 가정할 때의 $V(G, D)$ 값입니다. $$ C(G) = \\max_D V(G, D) = V(G, D_G^*) $$ 논문은 $D_G^*(x)$ 를 $V(G, D)$ 에 다시 대입하면 : $$ C(G) = \\mathbb{E}_{x \\sim p_{data}}\\left[\\log\\frac{p_{data}(x)}{p_{data}(x)+p_{g}(x)}\\right] + \\mathbb{E}_{x \\sim p_{g}}\\left[\\log\\frac{p_{g}(x)}{p_{data}(x)+p_{g}(x)}\\right] $$ 최적 지점 ( $p_g = p_{data}$ ): 만약 $p_g = p_{data}$ 라면, Proposition 1의 식에 대입하면 $D_G^*(x) = \\frac{p_{data}(x)}{p_{data}(x) + p_{data}(x)} = \\frac{1}{2}$ 이 됩니다. $$ C(G) = \\mathbb{E}_{x \\sim p_{data}}[\\log(\\frac{1}{2})] + \\mathbb{E}_{x \\sim p_g}[\\log(\\frac{1}{2})] = \\log(\\frac{1}{2}) + \\log(\\frac{1}{2}) = -2\\log 2 = -\\log 4 $$ 이는 $p_g = p_{data}$ 일 때 $C(G)$ 의 값이 $-\\log 4$ 임을 보입니다.\n이것이 유일한 최소값인가?: 논문은 $C(G)$ 와 $-\\log 4$ 의 차이를 분석합니다. $-\\log 4$ 는 다음과 같이 쓸 수 있습니다: $$ -\\log 4 = -2\\log 2 = \\mathbb{E}_{x \\sim p_{data}}[-\\log 2] + \\mathbb{E}_{x \\sim p_g}[-\\log 2] $$ $C(G) - (-\\log 4)$를 계산합니다: $$ C(G) - (-\\log 4) = \\left( \\mathbb{E}_{x \\sim p_{data}}\\left[\\log\\frac{p_{data}}{p_{data}+p_{g}}\\right] + \\mathbb{E}_{x \\sim p_{g}}\\left[\\log\\frac{p_{g}}{p_{data}+p_{g}}\\right] \\right) - \\left( \\mathbb{E}_{x \\sim p_{data}}[-\\log 2] + \\mathbb{E}_{x \\sim p_g}[-\\log 2] \\right) $$ 기댓값( $\\mathbb{E}$ )을 하나로 묶고 로그의 성질($\\log A - \\log B = \\log(A/B)$)을 이용합니다: $$ = \\mathbb{E}_{x \\sim p_{data}}\\left[\\log\\frac{p_{data}}{p_{data}+p_{g}} - (-\\log 2)\\right] + \\mathbb{E}_{x \\sim p_{g}}\\left[\\log\\frac{p_{g}}{p_{data}+p_{g}} - (-\\log 2)\\right] $$ $$ = \\mathbb{E}_{x \\sim p_{data}}\\left[\\log\\frac{p_{data}}{(p_{data}+p_{g})/2}\\right] + \\mathbb{E}_{x \\sim p_{g}}\\left[\\log\\frac{p_{g}}{(p_{data}+p_{g})/2}\\right] $$ 이것이 바로 Kullback-Leibler (KL) 발산의 정의입니다. $KL(P || Q) = \\mathbb{E}_{x \\sim P}[\\log \\frac{P(x)}{Q(x)}]$. $$ = KL\\left(p_{data} \\left|\\right| \\frac{p_{data}+p_{g}}{2}\\right) + KL\\left(p_{g} \\left|\\right| \\frac{p_{data}+p_{g}}{2}\\right) $$ 따라서, $C(G) = -\\log 4 + KL(\\dots) + KL(\\dots)$입니다. 이 두 KL 항의 합은 **Jensen-Shannon Divergence (JSD)**의 $2$배와 같습니다. $$ C(G) = -\\log(4) + 2 \\cdot JSD(p_{data} || p_g) $$ 최종 결론: JSD는 두 분포 간의 \u0026lsquo;거리\u0026rsquo;를 측정하는 지표이며, 항상 0보다 크거나 같습니다 ($JSD \\ge 0$). JSD가 0이 되는 유일한 경우는 두 분포가 정확히 같을 때입니다 ($p_{data} = p_g$). 따라서 $C(G)$는 $C(G) = -\\log 4 + (\\text{항상 0 이상인 값})$ 입니다. $C(G)$의 전역 최소값($C^*$)은 $JSD=0$일 때 달성되며, 그 값은 $-\\log 4$입니다.\n$JSD=0$은 $p_g = p_{data}$를 의미하므로, $G$의 학습 목표($C(G)$ 최소화)가 $p_g$를 $p_{data}$와 같게 만드는 것과 동일함이 수학적으로 증명되었습니다.\nAlgorithm 1의 수렴성 (Convergence) Proposition 2: $G$ 와 $D$ 가 충분한 용량을 갖고, $D$ 가 $G$ 에 대해 항상 최적에 도달할 수 있으며, $p_g$ 가 기준을 개선하도록 업데이트된다면, $p_g$ 는 $p_{data}$ 로 수렴합니다.\n목표: $G$ 에 대한 비용 함수 $C(G) = \\sup_D V(G, D) = \\sup_D U(p_g, D)$ 를 최소화하는 gradient (기울기) 업데이트가 $p_g \\rightarrow p_{data}$ 로 이끄는가? (참고: $V(G,D)$ 를 $p_g$ 의 함수로 보기 위해 $U(p_g, D)$ 로 표기했습니다.)\n핵심 1 (Convexity): $U(p_g, D)$ 는 $p_g$ 에 대해 convex (볼록) 함수입니다.\n이유: $U(p_g, D) = \\int [ p_{data} \\log D + p_g \\log(1-D) ] dx$ 입니다. 이는 $p_g$ 에 대한 $A + \\int p_g \\cdot B(x) dx$ 형태의 선형(linear) 함수이며, 선형 함수는 convex입니다. 핵심 2 (Supremum): $C(G)$ 는 convex 함수( $U$ )들의 supremum (상한, 여기서는 $\\max$ )입니다. convex 함수들의 supremum 역시 convex 함수입니다.\n따라서 $G$ 의 비용 함수 $C(G)$ 는 $p_g$ 에 대해 convex합니다. 핵심 3 (Gradient): $C(G) = \\sup_D U(p_g, D)$ 와 같은 함수의 subderivative를 어떻게 계산하는가?\nDanskin\u0026rsquo;s Theorem에 따르면, $\\sup_D U(p_g, D)$ 의 $p_g$ 에 대한 gradient는, $U(p_g, D)$ 를 최대화하는 $D$ (즉, $D_G^*$ ) 를 찾은 다음, 그 $D_G^*$ 를 고정한 채 $U(p_g, D_G^*)$ 를 $p_g$ 에 대해 미분한 값과 같습니다. 알고리즘 1은 정확히 이 작업을 근사적으로 수행합니다. (1) $D$ 를 최적화합니다 ( $D_G^*$ 를 근사). (2) $G$ 를 업데이트합니다 ( $U(p_g, D_G^*)$ 의 gradient descent를 수행). 결론: $C(G)$ 는 $p_g$ 에 대해 convex 함수이며, Theorem 1에서 $p_g = p_{data}$ 라는 유일한 전역 최적해를 가짐을 보였습니다.\nConvex 함수를 gradient descent (경사 하강법)로 최적화하면 (충분히 작은 업데이트 스텝으로), 그 유일한 전역 최적해( $p_g = p_{data}$ )로 수렴하는 것이 보장됩니다.\n한계점 논문은 마지막에 중요한 현실적 문제를 언급합니다. 위의 모든 증명은 우리가 $p_g$라는 확률 분포 자체를 직접 최적화할 수 있다고 가정한 비모수적(non-parametric) 환경에서 이루어졌습니다.\n실제: 우리는 $p_g$ 자체를 최적화하는 것이 아니라, $G(z; \\theta_g)$라는 multilayer perceptron (신경망)의 **파라미터 $\\theta_g$**를 최적화합니다.\n문제: $C(G)$가 $p_g$에 대해서는 convex할지라도, $G$의 파라미터 $\\theta_g$에 대해서는 전혀 convex하지 않습니다. $\\theta_g$ 공간은 critical points (임계점, 즉 local minima 나 saddle point)가 많습니다.\n결론: 따라서 실제 학습(Algorithm 1)이 이론적인 전역 최적해($p_g = p_{data}$)에 도달한다는 이론적 보장은 없습니다.\n그럼에도 불구하고, 논문은 multilayer perceptron이 실험에서 훌륭한 성능을 보여주기 때문에, 이 이론적 보장의 부재에도 불구하고 합리적인 모델이라고 주장합니다. (🤔??)\nIII. 실험 (Experiments) Adversarial nets는 MNIST, Toronto Face Database (TFD), CIFAR-10 데이터셋에서 훈련되었습니다.\n생성 모델의 성능 평가는 생성된 샘플의 log-likelihood를 직접 계산하기 어려워 까다롭습니다. 이 논문은 Gaussian Parzen window (가우시안 파젠 창) 기법을 사용하여 테스트셋 데이터의 확률을 추정했습니다.\nTable 1은 이 Parzen window 기반 log-likelihood 추정 결과를 보여줍니다. MNIST와 TFD 데이터셋에 대해 Adversarial nets의 결과를 DBN, Stacked CAE (Stacked Contractive Auto-encoders), Deep GSN 등 다른 모델들과 비교합니다. 이 표는 Adversarial nets가 기존의 우수한 생성 모델들과 \u0026ldquo;최소한 경쟁력 있는(at least competitive)\u0026rdquo; 성능을 보임을 나타냅니다.\nFigure 2는 훈련된 generator 넷에서 추출한 샘플들을 시각화합니다. MNIST (숫자), TFD (얼굴), CIFAR-10 (물체)에 대해 생성된 이미지들을 보여줍니다. 이 그림에서 중요한 점은 각 이미지 그리드의 가장 오른쪽 열입니다. 이 열은 바로 왼쪽의 생성된 샘플과 가장 가까운 실제 훈련 데이터를 보여줍니다. 이는 모델이 훈련 데이터를 단순히 **\u0026ldquo;암기(memorized)\u0026rdquo;**한 것이 아니라 새로운 샘플을 생성하고 있음을 보여주기 위한 것입니다. 이 샘플들은 Markov chain에 의존하지 않기 때문에 서로 상관관계가 없습니다.\nFigure 3은 $z$ 공간(노이즈 입력 공간)의 좌표 사이를 linearly interpolating (선형 보간)하여 얻은 숫자 이미지들을 보여줍니다. 예를 들어 \u0026lsquo;1\u0026rsquo;을 생성하는 $z$ 벡터와 \u0026lsquo;5\u0026rsquo;를 생성하는 $z$ 벡터 사이의 중간 지점들을 $G$에 입력하면, \u0026lsquo;1\u0026rsquo;이 \u0026lsquo;5\u0026rsquo;로 부드럽게 변해가는 중간 형태의 숫자 이미지들이 생성됩니다. 이는 $G$가 의미 있는 representation (표현)을 학습했음을 시사합니다.\nIV. 결론 (Advantages and disadvantages) 이 새로운 프레임워크는 장점과 단점을 모두 가집니다.\nTable 2는 generative modeling (생성 모델링)의 여러 접근법들이 겪는 어려움들을 요약합니다. Adversarial models를 Deep directed graphical models, Deep undirected graphical models, Generative autoencoders와 비교합니다.\n장점:\nMarkov chains가 전혀 필요 없습니다. 샘플링은 $G$를 통한 단 한 번의 forward propagation (순전파)입니다. 학습 중 inference (추론)가 필요 없습니다. gradient (기울기)를 얻기 위해 backpropagation (역전파)만 사용합니다. 매우 날카롭거나 degenerate (퇴화된) 분포(즉, 한 점에 모인 분포)도 표현할 수 있습니다. (반면 MCMC 기반 방법들은 분포가 어느 정도 \u0026ldquo;흐릿해야(blurry)\u0026rdquo; 믹싱이 잘 됩니다). 단점:\n$p_g(x)$ (생성된 데이터의 확률)에 대한 명시적인 표현이 없습니다. $D$와 $G$가 학습 중에 잘 **\u0026ldquo;동기화(synchronized)\u0026rdquo;**되어야 합니다. 만약 $G$가 $D$의 업데이트 없이 너무 많이 학습되면, $G$가 $p_{data}$를 모델링하기에 충분한 다양성을 갖지 못하고 특정 $x$ 값으로 **collapse (붕괴)**하는 \u0026ldquo;Helvetica 시나리오\u0026rdquo; (여러 $z$가 똑같은 $x$로 매핑되는 현상)에 빠질 수 있습니다. ","permalink":"https://mookjsi.github.io/posts/paper-review-gan/","summary":"YBIGTA DS Session 11/11 Presentation","title":"Generative Adversarial Nets (GAN) 논문 리뷰"},{"content":"이 논문은 사람이 일일이 사진에 \u0026ldquo;이건 고양이야\u0026rdquo;, \u0026ldquo;저건 강아지야\u0026quot;라고 알려주지 않아도, 컴퓨터가 스스로 이미지의 특징을 학습하는 방법에 대한 연구입니다. 특히 아주 간단하면서도 효과적인 방법을 제시하여 큰 주목을 받았습니다.\n컴퓨터에게 사진을 주고 이게 뭔지 맞혀보라고 시키는 걸 **지도 학습(Supervised Learning)**이라 합니다. 정답을 알려주면서 공부시키는 거죠. 하지만 세상에는 정답이 없는 사진이 훨씬 많습니다. 이 정답 없는 사진들로 컴퓨터를 똑똑하게 만들 순 없을까요? 이게 바로 **\u0026lsquo;자기 지도 학습(Self-Supervised Learning)\u0026rsquo;**의 목표입니다.\nSimCLR이 사용하는 방법은 **\u0026lsquo;대조 학습(Contrastive Learning)\u0026rsquo;**이라는 건데요, 아주 간단한 아이디어에서 출발합니다.\n예시: 강아지 사진이 한 장 있다고 상상해 봅시다.\n이 사진을 가지고 약간 다른 버전의 사진 두 장을 만듭니다. 예를 들어, 한 장은 강아지 얼굴만 확대(crop)하고, 다른 한 장은 색감을 살짝 바꾸는(color distortion) 거죠. 컴퓨터에게 이 두 사진은 \u0026lsquo;같은 강아지\u0026rsquo;에서 나온 긍정적 쌍(positive pair) 이라고 알려줍니다. 그리고 동시에, 전혀 다른 사진들(예: 고양이, 자동차, 나무 사진)을 보여주면서, 이것들은 방금 본 강아지 사진과 다른 부정적 쌍(negative pair) 이라고 알려줍니다. 이 과정을 수많은 사진으로 반복하면, 컴퓨터는 점차 \u0026lsquo;어떤 특징\u0026rsquo;이 같은 대상을 나타내고, \u0026lsquo;어떤 특징\u0026rsquo;이 다른 대상을 나타내는지 스스로 배우게 됩니다. 즉, \u0026lsquo;강아지다움\u0026rsquo;이 무엇인지 그 본질적인 **표현(representation)**을 학습하게 되는 거죠. SimCLR은 이 간단한 원리를 매우 효과적으로 구현한 프레임워크입니다.\n참고: Stochastic Optimization Review (표현 학습 관련 발표 자료) 1. 서론 (Introduction) 연구의 시작은 \u0026ldquo;사람의 정답 없이 어떻게 컴퓨터가 **시각적 표현(visual representation)**을 배울 수 있을까?\u0026ldquo;라는 오랜 질문에서 출발합니다. 기존의 방법들은 복잡한 구조를 필요로 하거나, 대량의 이전 데이터를 저장해두는 메모리 뱅크(memory bank) 같은 부가적인 장치가 필요했습니다.\nFigure 1은 SimCLR이 나오기 전까지의 여러 자기 지도 학습 모델들의 성능을 보여주는 그래프입니다. 가로축은 모델의 크기(Number of Parameters), 세로축은 이미지 분류 정확도(ImageNet Top-1 Accuracy)를 나타냅니다. 이 그래프에서 **SimCLR(별 모양 ★)**은 다른 모델들(점 모양 •)에 비해 훨씬 적은 파라미터로 더 높은 정확도를 달성하며, 심지어 사람이 정답을 알려주고 학습시킨 **지도 학습 모델(Supervised, 회색 십자가)**의 성능과 맞먹는 것을 보여줍니다. 이는 매우 간단한 프레임워크가 기존의 복잡한 방법들을 뛰어넘을 수 있음을 시사합니다.\n이 논문은 SimCLR의 성공 비결이 다음 세 가지 핵심 요소의 조합에 있음을 체계적인 실험을 통해 보여줍니다.\n데이터 증강 기법의 조합이 효과적인 표현을 학습하는 데 매우 중요하다. 모델의 최종 표현(representation)과 손실 함수(loss function) 사이에 **비선형 변환(nonlinear transformation)**을 추가하는 것이 성능을 크게 향상시킨다. 대조 학습은 지도 학습보다 더 큰 **배치 크기(batch size)**와 더 긴 학습 시간으로부터 더 큰 이득을 얻는다. 2. 기술 설명 (Technical Description) SimCLR 프레임워크는 네 가지 주요 구성 요소로 이루어져 있습니다.\nFigure 2는 이 전체 과정을 아주 잘 보여주는 그림입니다. 하나의 이미지 $x$에서 시작해서, 두 개의 서로 다른 데이터 증강(augmentation) $t$와 $t\u0026rsquo;$를 적용하여 두 개의 새로운 이미지 $\\tilde{x}_i$와 $\\tilde{x}_j$를 만듭니다. 이 둘은 서로 연관된 **\u0026lsquo;긍정적 쌍\u0026rsquo;**이 됩니다. 이 두 이미지는 동일한 인코더 네트워크(encoder network) $f(\\cdot)$를 통과하여 각각의 표현 벡터(representation vector) $h_i$와 $h_j$로 변환됩니다. 그 후, 이 표현 벡터들은 또 다른 작은 신경망인 투영 헤드(projection head) $g(\\cdot)$를 거쳐 최종적으로 $z_i$와 $z_j$라는 벡터로 변환됩니다. 학습의 목표는 이 $z_i$와 $z_j$ 사이의 **유사도(agreement)**를 최대화하는 것입니다. 학습이 끝나면 투영 헤드 $g(\\cdot)$는 버리고, 표현 벡터 $h$를 다른 작업(예: 이미지 분류)에 사용합니다.\n데이터 증강 (Data Augmentation): 하나의 이미지로부터 두 개의 연관된 뷰(view)를 생성하는 과정입니다. 이 논문에서는 무작위 자르기 후 원래 크기로 복원(random cropping and resize), 색상 왜곡(color distortion), **가우시안 블러(Gaussian blur)**를 순차적으로 적용합니다. 어떤 증강 기법을 어떻게 조합하는지가 모델 성능의 핵심입니다.\n기본 인코더 (Base Encoder): 증강된 이미지로부터 표현 벡터 $h_i$를 추출하는 신경망입니다. 이 논문에서는 주로 ResNet 구조를 사용하며, 특별한 구조적 제약이 없어 어떤 신경망이든 사용할 수 있습니다. $h_i = f(\\tilde{x}_i)$ 입니다.\n투영 헤드 (Projection Head): 인코더에서 나온 표현 벡터 $h$를 **대조 손실(contrastive loss)**을 계산하는 공간으로 매핑하는 작은 신경망 $g(\\cdot)$입니다. 이 논문에서는 하나의 **은닉층(hidden layer)**을 가진 **MLP(Multi-Layer Perceptron)**를 사용합니다. $z_i = g(h_i)$ 이며, $h_i$가 아닌 $z_i$에 손실 함수를 적용하는 것이 성능 향상에 큰 도움이 된다는 것을 발견했습니다.\n대조 손실 함수 (Contrastive Loss Function): 주어진 \u0026lsquo;긍정적 쌍\u0026rsquo;($z_i$, $z_j$)의 유사도는 높이고, 나머지 모든 \u0026lsquo;부정적 쌍\u0026rsquo;과의 유사도는 낮추도록 학습시키는 함수입니다. 이 논문에서는 NT-Xent (Normalized Temperature-scaled Cross Entropy) 손실을 사용합니다.\nAlgorithm 1은 이 SimCLR 학습 과정을 단계별로 요약한 것입니다. N개의 이미지를 배치로 가져와 각 이미지마다 두 개의 증강된 뷰를 만들고, 인코더와 투영 헤드를 통과시켜 2N개의 $z$ 벡터를 얻습니다. 그런 다음 모든 벡터 쌍 간의 유사도($s_{i,j}$)를 계산하고, 이를 바탕으로 손실($l(i,j)$)을 계산하여 네트워크 $f$와 $g$를 업데이트합니다.\n수식에 대해 좀 더 깊이 들어가 보겠습니다. NT-Xent 손실 함수는 다음과 같이 정의됩니다. $$ l_{ij} = -\\log \\frac{\\exp(\\text{sim}(z_i, z_j)/\\tau)}{\\sum_{k=1}^{2N} \\mathbb{I}_{[k \\neq i]} \\exp(\\text{sim}(z_i, z_k)/\\tau)} $$ $z_i$와 $z_j$는 각각 증강된 이미지 $\\tilde{x}_i$와 $\\tilde{x}_j$로부터 추출된 $l_2$ 정규화된(normalized) 표현 벡터입니다. 이 둘은 \u0026lsquo;긍정적 쌍\u0026rsquo;입니다. $\\text{sim}(u, v) = u^T v / (||u|| ||v||)$는 두 벡터 간의 **코사인 유사도(cosine similarity)**를 계산합니다. $\\tau$ (타우)는 온도(temperature) 하이퍼파라미터로, 유사도 분포를 얼마나 뾰족하게 만들지 조절합니다. $\\tau$가 작을수록 모델은 어려운 부정적 예시(hard negatives, 즉 긍정적 예시와 유사도가 높은 부정적 예시)에 더 집중하게 됩니다. 이는 손실 함수의 기울기(gradient)에서 부정적 예시들에 대한 가중치를 조절하는 효과를 낳습니다. 분자 $\\exp(\\text{sim}(z_i, z_j)/\\tau)$는 긍정적 쌍 간의 유사도를 지수적으로 증폭시킨 값입니다. 분모 $\\sum_{k=1}^{2N} \\mathbb{I}_{[k \\neq i]} \\exp(\\text{sim}(z_i, z_k)/\\tau)$는 $z_i$를 기준으로, 자기 자신을 제외한 배치 내의 모든 $2N-1$개의 다른 벡터(긍정적 쌍인 $z_j$ 1개와 부정적 쌍 $2N-2$개 포함)와의 유사도를 지수적으로 증폭시켜 합한 값입니다. 결론적으로 이 수식은 Softmax 함수의 형태를 띠며, 2N개의 벡터 중에서 $z_i$의 짝인 $z_j$를 올바르게 분류하는 다중 클래스 분류 문제로 볼 수 있습니다. 로그를 취하고 음수를 붙여, 정답(긍정적 쌍)의 확률을 최대화(손실을 최소화)하도록 합니다. 이것이 바로 Cross-Entropy 손실의 기본 원리입니다.\n3. 실험 (Experiments) SimCLR의 각 설계 요소가 성능에 어떤 영향을 미치는지 검증하기 위해 방대한 실험을 수행했습니다.\n데이터 증강의 효과 Figure 3은 **무작위 자르기(random cropping)**만으로도 이미지의 전체적인 모습을 보는 \u0026lsquo;global view\u0026rsquo;와 특정 부분을 보는 \u0026rsquo;local view\u0026rsquo; (B → A), 또는 인접한 부분을 보는 \u0026lsquo;adjacent view\u0026rsquo; (D → C)를 예측하는 다양한 대조 학습 과제를 만들 수 있음을 보여줍니다.\nFigure 4는 실험에 사용된 다양한 데이터 증강 기법들을 시각적으로 보여줍니다. (a) 원본 이미지부터 시작해 자르기, 색상 왜곡, 회전, 노이즈, 블러 등 다양한 변환을 적용한 모습을 확인할 수 있습니다.\nFigure 5는 이 증강 기법들의 조합 효과를 분석한 히트맵입니다. 대각선은 단일 변환의 성능, 비대각선은 두 변환 조합의 성능을 나타냅니다. 이 표에서 어떤 단일 변환도 좋은 성능을 내지 못하지만, 두 가지 변환을 조합했을 때(특히 \u0026lsquo;Crop\u0026rsquo;과 \u0026lsquo;Color\u0026rsquo;의 조합) 성능이 극적으로 향상됨을 알 수 있습니다.\nFigure 6은 왜 색상 왜곡이 중요한지 설명합니다. 색상 왜곡이 없으면(a), 같은 이미지에서 잘라낸 조각들은 비슷한 색상 분포(히스토그램)를 가집니다. 모델이 이 \u0026lsquo;쉬운 길\u0026rsquo;을 택해 색상만으로 정답을 맞히는 꼼수를 부릴 수 있습니다. 색상 왜곡을 추가하면(b), 이런 꼼수가 불가능해져 모델이 더 일반화 가능한 특징을 배우게 됩니다.\nTable 1은 색상 증강의 강도에 따른 성능 변화를 보여줍니다. 자기 지도 학습(SimCLR)에서는 색상 증강을 강하게 할수록 성능이 향상되지만, 지도 학습에서는 오히려 성능이 저하되기도 합니다. 이는 자기 지도 학습이 지도 학습보다 더 강한 데이터 증강을 필요로 함을 의미합니다.\n아키텍처의 영향 Figure 7은 모델의 깊이와 너비가 커질수록 성능이 향상됨을 보여줍니다. 흥미로운 점은 모델이 커질수록, 자기 지도 학습 모델(파란 점, 빨간 별)과 지도 학습 모델(녹색 십자가) 간의 성능 격차가 줄어든다는 것입니다. 이는 자기 지도 학습이 큰 모델로부터 더 많은 혜택을 본다는 것을 시사합니다.\nFigure 8은 **투영 헤드 $g(\\cdot)$**의 구조에 따른 성능을 비교합니다. 비선형 MLP 헤드(\u0026lsquo;Non-linear\u0026rsquo;)가 선형 헤드(\u0026lsquo;Linear\u0026rsquo;)나 헤드가 없는 경우(\u0026lsquo;None\u0026rsquo;)보다 월등히 좋은 성능을 보입니다.\n$h$와 $g(h)$가 어떤 증강(색상, 회전 등)이 적용되었는지 예측하는 실험을 했을 때, $h$가 훨씬 더 많은 정보를 담고 있는 것으로 나타났습니다. 즉, $g(h)$는 대조 학습 과제에 불필요한 정보(예: 색상, 방향)를 제거하는 역할을 하며, 이로 인해 그 이전 단계인 $h$에는 더 풍부한 정보가 보존되는 것입니다.\n손실 함수와 배치 크기 Table 2는 NT-Xent 손실 함수를 다른 대조 손실 함수들(NT-Logistic, Margin Triplet)과 수식 및 기울기 측면에서 비교합니다. NT-Xent는 온도 $\\tau$와 $l_2$ 정규화를 통해 어려운 부정적 예시에 가중치를 두는 반면, 다른 손실 함수들은 그렇지 않다는 차이가 있습니다.\nTable 4는 실제 성능 비교 결과로, NT-Xent가 다른 손실 함수들보다 훨씬 우수한 성능을 보임을 확인시켜 줍니다.\nTable 5는 $l_2$ 정규화와 온도 $\\tau$의 중요성을 보여줍니다. 정규화를 사용하지 않거나, 적절한 온도를 설정하지 않으면 성능이 크게 저하됩니다.\nFigure 9는 배치 크기와 학습 에포크(epoch) 수에 따른 성능 변화를 보여줍니다. 학습 초기에는 배치 크기가 클수록 성능이 좋지만, 학습을 오래 진행할수록 그 차이가 줄어듭니다. 대조 학습에서는 큰 배치가 더 많은 부정적 예시를 제공하므로 수렴을 돕는 효과가 있습니다.\n최신 기술과의 비교 (SOTA) Table 6은 ImageNet 데이터셋에서의 선형 평가(linear evaluation) 결과를 다른 자기 지도 학습 모델들과 비교한 표입니다. SimCLR은 ResNet-50 (4x) 모델을 사용하여 76.5%의 Top-1 정확도를 달성, 이전 최고 성능을 크게 뛰어넘었으며 지도 학습 모델의 성능과 동등한 수준에 도달했습니다.\nTable 7은 레이블이 적은 데이터(1% 또는 10%)로 모델을 **미세 조정(fine-tuning)**하는 준지도 학습(semi-supervised learning) 성능을 비교합니다. 여기서도 SimCLR은 다른 방법들을 큰 차이로 능가했습니다.\nTable 8은 다른 12개의 다양한 이미지 데이터셋으로의 전이 학습(transfer learning) 성능을 보여줍니다. SimCLR로 사전 학습된 모델은 많은 데이터셋에서 지도 학습으로 사전 학습된 모델과 대등하거나 더 나은 성능을 보였습니다.\n4. 결론 (Conclusion) 이 논문은 SimCLR이라는 매우 간단하면서도 강력한 대조 학습 프레임워크를 제시했습니다. SimCLR의 성공은 어느 하나의 새로운 발견이 아닌, 기존에 알려진 요소들을 체계적으로 연구하고 최적으로 조합한 결과입니다.\n핵심적인 발견은 다음과 같습니다.\n데이터 증강 기법의 강력한 조합(특히 무작위 자르기와 색상 왜곡)은 효과적인 표현 학습에 필수적이다. 인코더 뒤에 비선형 투영 헤드를 추가하고, 헤드를 통과하기 전의 표현을 사용하는 것이 성능을 크게 향상시킨다. **정규화된 Cross Entropy 손실 함수(NT-Xent)**와 적절한 온도 파라미터, 그리고 매우 큰 배치 크기에서의 학습이 매우 효과적이다. SimCLR은 복잡한 구조나 메모리 뱅크 없이도 최첨단 성능을 달성함으로써, 자기 지도 학습의 잠재력이 여전히 과소평가되고 있음을 보여주었습니다. 이 연구는 이후의 수많은 자기 지도 학습 연구에 큰 영감을 주었습니다.\n","permalink":"https://mookjsi.github.io/posts/paper-review-simclr/","summary":"YBIGTA 10/28 DS Session Presentation","title":"SimCLR 논문 리뷰"},{"content":"이 논문은 이미지 분할(Image Segmentation) 분야에 \u0026lsquo;파운데이션 모델(Foundation Model)\u0026rsquo; 이라는 새로운 패러다임을 제시하는 \u0026ldquo;Segment Anything (SA)\u0026ldquo;를 소개합니다. 이미지 분할이란, 이미지 속 각 픽셀이 어떤 객체에 속하는지 구분하여 영역을 나누는 기술입니다. 예를 들어, 고양이 사진에서 픽셀 단위로 \u0026lsquo;여기는 고양이\u0026rsquo;, \u0026lsquo;여기는 배경\u0026rsquo;이라고 알려주는 것과 같습니다.\n최근 자연어 처리(NLP) 분야에서는 GPT와 같이 웹 규모의 방대한 데이터로 사전 훈련된 **\u0026lsquo;파운데이션 모델\u0026rsquo;**이 등장하여, 특정 작업에 대한 추가 훈련(fine-tuning) 없이도 \u0026lsquo;프롬프트(prompt)\u0026lsquo;만으로 다양한 작업을 놀랍도록 잘 수행해내고 있습니다. 이 논문의 저자들은 이러한 성공에 영감을 받아, 이미지 분할 분야에도 적용할 수 있는 범용 모델을 만들고자 했습니다.\n이를 위해 저자들은 다음 세 가지 핵심 요소를 새롭게 정의하고 개발했습니다.\n새로운 과업(Task): 프롬프트 기반 분할 (Promptable Segmentation) 새로운 모델(Model): Segment Anything Model (SAM) 새로운 데이터셋(Data): Segment Anything 1-Billion (SA-1B) 이 세 가지는 서로 맞물려 돌아가는 톱니바퀴처럼 작용합니다. 좋은 모델(SAM)을 만들기 위해 방대한 데이터(SA-1B)가 필요하고, 이 데이터를 효율적으로 구축하기 위해 좋은 모델(SAM)을 \u0026lsquo;데이터 엔진\u0026rsquo;으로 활용했으며, 이 모든 것을 가능하게 하는 것이 바로 프롬프트 기반 분할입니다.\n(a) 과업: 이 그림은 \u0026lsquo;프롬프트 기반 분할\u0026rsquo;이라는 새로운 task를 보여줍니다. 사용자가 이미지 위에 점을 찍거나(points), 네모 박스를 그리거나(box), 심지어 \u0026ldquo;검은 귀를 가진 고양이\u0026quot;처럼 텍스트(text)로 프롬프트를 주면, 모델이 그에 해당하는 객체의 마스크(mask)를 출력합니다.\n(b) 모델: 이것이 바로 SAM(Segment Anything Model)의 구조입니다. 이미지를 분석하는 무거운 \u0026lsquo;이미지 인코더\u0026rsquo;, 사용자의 프롬프트를 이해하는 \u0026lsquo;프롬프트 인코더\u0026rsquo;, 그리고 이 둘을 합쳐 최종 마스크를 빠르게 만들어내는 가벼운 \u0026lsquo;마스크 디코더\u0026rsquo;로 구성됩니다.\n(c) 데이터: 거대한 SA-1B 데이터셋을 구축하기 위한 \u0026lsquo;데이터 엔진\u0026rsquo;을 보여줍니다. 모델을 이용해 데이터 주석 작업을 돕고(annotate), 그 데이터로 모델을 다시 학습시키는(train) 과정을 반복하여 11억 개가 넘는 마스크 데이터를 구축했습니다.\n기술 설명 1. 과업: 프롬프트 기반 분할 (Promptable Segmentation) 기존의 분할 모델들은 \u0026lsquo;고양이만 찾아내라\u0026rsquo; 또는 \u0026lsquo;사람과 자동차만 구분해라\u0026rsquo;와 같이 정해진 종류의 객체만 분할할 수 있었습니다. 하지만 이 논문에서 제안하는 프롬프트 기반 분할은 \u0026ldquo;어떤 프롬프트가 주어지든 그에 해당하는 유효한 분할 마스크를 반환\u0026quot;하는 것을 목표로 합니다.\n여기서 \u0026lsquo;유효한(valid)\u0026rsquo; 마스크라는 점이 중요합니다. 예를 들어, 파란 셔츠를 입은 사람의 사진에서 셔츠 부분에 점 하나를 프롬프트로 찍었다고 가정해봅시다. 이 점은 \u0026lsquo;파란 셔츠\u0026rsquo;를 의미할 수도 있고, \u0026lsquo;셔츠를 입고 있는 사람 전체\u0026rsquo;를 의미할 수도 있습니다. 이렇게 프롬프트가 모호할 경우, 모델은 셔츠 마스크와 사람 마스크 둘 중 하나 이상의 합리적인 마스크를 출력해야 합니다.\n이 그림은 SAM이 어떻게 모호성을 처리하는지 잘 보여줍니다. 각 열은 하나의 이미지에 대한 결과입니다. 초록색 점(green circle)이라는 단 하나의 모호한 프롬프트가 주어졌을 때, SAM은 세 개의 서로 다른 유효한 마스크를 생성합니다. 예를 들어 첫 번째 열의 타조 이미지에서 목 부분에 점을 찍자, SAM은 타조의 머리, 목, 그리고 몸 전체에 해당하는 세 가지 마스크를 모두 제시합니다. 이를 통해 사용자는 자신이 원하는 결과를 선택할 수 있습니다.\n2. 모델: SAM (Segment Anything Model) SAM은 프롬프트 기반 분할 테스크를 실시간으로 수행하기 위해 매우 효율적인 구조로 설계되었습니다.\n이미지 인코더 (Image Encoder): 무거운 Vision Transformer(ViT) 기반의 인코더로, 입력된 이미지 전체를 한 번만 처리하여 고차원의 \u0026lsquo;이미지 임베딩(image embedding)\u0026lsquo;을 생성합니다. 이 과정은 계산량이 많지만, 이미지당 한 번만 수행하면 되므로 여러 프롬프트를 처리할 때 비용을 절약할 수 있습니다.\n프롬프트 인코더 (Prompt Encoder): 점, 상자, 텍스트, 마스크 등 다양한 형태의 프롬프트를 이미지 임베딩과 결합할 수 있는 벡터 형태로 변환합니다. 예를 들어, 점이나 상자는 위치 정보를 담은 인코딩을 사용하고, 텍스트는 CLIP과 같은 언어 모델의 인코더를 활용합니다.\n마스크 디코더 (Mask Decoder): 이미지 임베딩과 프롬프트 임베딩을 입력받아 최종 마스크를 출력하는 가볍고 빠른 모듈입니다. 이 디코더는 웹 브라우저에서도 약 50ms 만에 작동할 정도로 매우 효율적이어서, 사용자가 프롬프트를 바꾸는 대로 실시간으로 결과를 보여주는 상호작용이 가능합니다. 또한, 모호한 프롬프트에 대응하기 위해 3개의 마스크와 각 마스크의 신뢰도 점수(예상 IoU)를 함께 출력합니다.\n모델 학습에는 Focal Loss와 Dice Loss를 결합한 손실 함수가 사용되었습니다.\n이 논문에서 사용된 손실 함수는 $L = \\alpha L_{focal} + \\beta L_{dice}$ 형태로 표현할 수 있습니다.\nFocal Loss ($L_{focal}$): 주로 객체 탐지에서 클래스 불균형 문제를 해결하기 위해 제안된 손실 함수입니다. 일반적인 Cross-Entropy 손실 함수에 $(1-p_t)^\\gamma$ 항을 추가하여, 모델이 이미 잘 맞추는 쉬운 샘플(예: 배경 픽셀)에는 적은 가중치를 부여하고, 맞추기 어려운 어려운 샘플(예: 객체의 경계 픽셀)에 집중하도록 만듭니다. 이를 통해 경계가 명확한 마스크를 학습하는 데 도움을 줍니다.\nDice Loss ($L_{dice}$): 예측 마스크와 실제 마스크 간의 겹치는 영역(Intersection over Union, IoU)을 직접적으로 최대화하도록 설계된 손실 함수입니다. Dice 계수 $D = \\frac{2|A \\cap B|}{|A| + |B|}$를 기반으로 하며, 손실 함수는 $L_{dice} = 1 - D$로 정의됩니다. 이 손실 함수는 분할 영역의 크기에 덜 민감하고, 심한 불균형 상황에서도 안정적인 학습을 돕습니다.\n이 두 손실 함수를 결합함으로써, 픽셀 단위의 정확성(Focal Loss)과 영역 단위의 유사성(Dice Loss)을 모두 고려하여 고품질의 마스크를 생성하도록 모델을 훈련시킵니다.\n3. 데이터 엔진 및 SA-1B 데이터셋 고품질의 파운데이션 모델을 훈련시키기 위해서는 방대하고 다양한 데이터가 필수적이지만, 이미지 분할 분야에는 웹에서 바로 수집할 수 있는 대규모 데이터가 존재하지 않았습니다. 이 문제를 해결하기 위해 저자들은 \u0026lsquo;데이터 엔진(Data Engine)\u0026rsquo; 이라는 독창적인 방법을 고안했습니다.\n데이터 엔진은 3단계로 진행되었습니다.\n보조-수동 단계 (Assisted-manual): 초기 SAM 모델을 이용해 전문 작업자가 대화형으로 마스크를 생성합니다. 모델이 대략적인 마스크를 제안하면, 작업자는 클릭 몇 번으로 수정하여 빠르고 정확하게 데이터를 만듭니다. 반자동 단계 (Semi-automatic): 모델이 발전함에 따라, 이제 모델이 이미지에서 확실한 객체들을 먼저 자동으로 찾아냅니다. 작업자는 모델이 놓친, 더 작거나 까다로운 객체들에 집중하여 마스크를 추가함으로써 데이터의 다양성을 높입니다. 완전 자동 단계 (Fully automatic): 최종 단계에서는 모델이 충분히 똑똑해져서 사람의 개입 없이도 고품질의 마스크를 대량으로 생성할 수 있게 됩니다. 저자들은 이미지에 $32 \\times 32$ 격자 형태의 점 프롬프트를 자동으로 입력하고, 모호성 처리 기능을 활용하여 이미지 당 평균 100여 개의 마스크를 자동으로 생성했습니다. 이제부터 각 데이터 엔진 단계별로 실제 예시 상황과 과정을 구체적으로 살펴보겠습니다.\n1. 보조-수동 단계 (Assisted-manual) 이 단계는 똑똑한 보조 도구를 활용해 사람이 수동으로 데이터를 만드는 과정입니다.\n예시 상황: 전문 작업자에게 공원에 있는 강아지 사진 한 장이 주어졌습니다. 작업 방식: 작업자는 수작업으로 강아지 외곽선을 그리는 대신, 강아지 몸통 중앙에 점(point) 하나를 클릭합니다. 초기 SAM 모델이 즉시 그 점을 기반으로 \u0026ldquo;이것이 강아지인 것 같다\u0026quot;고 추측하며 대략적인 강아지 마스크를 생성해 보여줍니다. 이 마스크는 꼬리가 잘려있고, 배경의 풀 일부가 포함되어 있을 수 있습니다. 작업자는 모델의 예측을 수정하기 위해 잘린 꼬리 부분에 점을 하나 더 클릭하고(여기도 포함해줘!), 잘못 포함된 풀 부분에 점을 클릭합니다(여기는 빼줘!). 클릭할 때마다 SAM은 실시간으로 마스크를 업데이트하고, 몇 번의 클릭만으로 픽셀 수준까지 정확한 강아지 마스크가 완성됩니다. 결과: 이 방식을 통해 처음부터 손으로 그리는 것보다 6.5배 빠르게 고품질 마스크 데이터를 수집할 수 있었습니다. 이 단계에서 수집된 데이터로 SAM 모델을 반복적으로 재학습시켜 성능을 점차 향상시켰습니다. 2. 반자동 단계 (Semi-automatic) 1단계를 거쳐 똑똑해진 모델이 먼저 쉬운 작업을 처리하고, 사람은 더 어려운 작업에 집중하는 협업 단계입니다.\n예시 상황: 작업자에게 다양한 물건이 있는 책상 사진이 주어졌습니다. 작업 방식: 작업자가 이미지를 열면, 1단계 데이터로 학습되어 더 강력해진 SAM이 이미지를 먼저 분석합니다. 모델은 자신이 90% 이상 확신하는 명확한 객체(예: 모니터, 키보드, 마우스)들의 마스크를 미리 자동으로 생성해 놓습니다. 🤖 작업자는 이미 생성된 마스크들을 검토하고, 모델이 놓친 더 작거나 복잡하고 애매한 객체(예: 엉켜있는 케이블, 펜, 책상 뒤편의 작은 화분)에만 집중하여 마스크를 추가합니다. 결과: 이 단계의 목표는 데이터의 다양성을 높이는 것입니다. 모델이 쉬운 것만 학습하지 않도록, 사람이 까다로운 객체 데이터를 보충해 줌으로써 모델이 \u0026ldquo;어떤 것이든(Anything)\u0026rdquo; 분할할 수 있는 능력을 키우게 됩니다. 3. 완전 자동 단계 (Fully automatic) 최종 단계에서는 사람의 개입 없이, 가장 강력해진 SAM 모델이 스스로 모든 데이터를 생성합니다.\n예시 상황: 모델에게 수많은 과일이 진열된 시장 사진이 주어졌습니다. 작업 방식: 시스템이 이미지 전체에 32x32 간격의 촘촘한 격자(grid) 점 프롬프트를 자동으로 입력합니다. SAM은 각 점에 대해 모호성 처리 기능을 최대한 활용합니다. 예를 들어, 포도송이의 포도알 하나에 점이 찍혔다면, 모델은 다음과 같이 여러 개의 유효한 마스크를 동시에 생성합니다. 마스크 1: 포도알 하나 마스크 2: 포도알이 속한 포도송이 전체 마스크 3: 포도송이가 놓인 과일 상자 전체 이렇게 생성된 수많은 마스크들 중에서, 모델이 스스로 예측한 신뢰도 점수(IoU)가 높고 안정적인 마스크만 남기고 나머지는 필터링합니다. 결과: 이 자동화된 과정을 통해 이미지 한 장당 평균 100여 개의 고품질 마스크를 사람의 도움 없이 대량으로 얻을 수 있었고, 최종적으로 11억 개 이상의 마스크로 구성된 SA-1B 데이터셋을 구축할 수 있었습니다. 이 과정을 통해 탄생한 것이 바로 SA-1B 데이터셋입니다. 이 데이터셋은 1100만 개의 고해상도 이미지와 총 11억 개가 넘는 분할 마스크로 구성되어 있으며, 이는 기존에 가장 컸던 분할 데이터셋보다 마스크 수 기준으로 400배 이상 많은 규모입니다.\n이 그림은 SA-1B 데이터셋에 포함된 다양한 이미지와 그 위에 오버레이된 마스크들을 보여줍니다. 위쪽으로 갈수록 이미지 당 마스크 수가 적고(\u0026lt;50개), 아래로 갈수록 마스크 수가 많은(\u0026gt;500개) 이미지들입니다. 이를 통해 데이터셋이 단순한 이미지부터 매우 복잡하고 객체가 많은 이미지까지 폭넓게 포함하고 있음을 알 수 있습니다.\nFigure 6은 SA-1B 데이터셋의 마스크 특성을 다른 주요 데이터셋(LVIS, COCO 등)과 비교합니다. SA-1B는 이미지당 마스크 수가 압도적으로 많고(왼쪽 그래프), 이로 인해 상대적으로 작거나 중간 크기의 마스크 비율이 높습니다(중간 그래프).\nFigure 7은 데이터셋에 포함된 이미지들의 추정된 지리적 분포를 보여줍니다. 기존 데이터셋들이 북미나 특정 지역에 편중된 경향이 있었던 반면, SA-1B는 아시아, 유럽 등 훨씬 더 다양한 국가의 이미지를 포함하여 지리적 다양성을 확보했습니다.\n실험 (Experiments) 저자들은 SAM이 훈련 데이터에서 보지 못한 새로운 종류의 이미지나 작업에 대해서도 얼마나 잘 작동하는지, 즉 제로샷 전이(Zero-shot Transfer) 성능을 평가하기 위해 다양한 실험을 진행했습니다.\n1. 단일 점 기반 마스크 생성 평가 가장 핵심적인 실험으로, 이미지에 단 하나의 점을 프롬프트로 주었을 때 얼마나 유효한 마스크를 생성하는지 평가했습니다.\n(a) 자동 평가(mIoU): 23개의 다양한 데이터셋에서 기존 최강의 대화형 분할 모델인 RITM과 성능을 비교했습니다. SAM은 23개 중 16개 데이터셋에서 더 높은 성능(IoU)을 보였습니다. 특히 \u0026lsquo;SAM (oracle)\u0026lsquo;은 SAM이 출력한 3개의 마스크 중 정답과 가장 가까운 것을 선택했을 때의 성능인데, 이 경우 모든 데이터셋에서 RITM을 압도했습니다. 이는 단일 점 프롬프트가 모호하기 때문에, 자동 평가 지표만으로는 모델의 실제 성능을 제대로 측정하기 어렵다는 것을 보여줍니다.\n(b) 사람 평가: 전문 작업자가 직접 마스크의 품질을 1~10점으로 평가한 결과입니다. 모든 데이터셋에서 사람들은 SAM이 생성한 마스크의 품질이 RITM보다 월등히 높다고 평가했습니다. 이는 SAM이 IoU 점수로는 측정되지 않는, 시각적으로 더 자연스럽고 정확한 마스크를 생성한다는 것을 의미합니다.\n2. 제로샷 엣지 검출, 객체 제안 및 인스턴스 분할 SAM은 분할 모델이지만, 그 능력을 응용하여 다른 컴퓨터 비전 작업에도 제로샷으로 적용했습니다.\nSAM이 생성한 여러 마스크들의 경계를 종합하여 엣지 맵을 만들었습니다. 그 결과, 엣지 검출을 위해 전혀 훈련되지 않았음에도 불구하고, Figure 10에서 보듯이 매우 합리적인 엣지 맵을 생성했습니다. Table 3의 정량 평가에서는 최신 전문 모델보다는 성능이 낮았지만, 초기의 딥러닝 기반 엣지 검출 모델(HED)과 비슷한 수준의 성능을 보여주며 SAM의 범용성을 입증했습니다.\n이미지 내에 객체가 있을 만한 영역을 제안하는 작업에서, LVIS 데이터셋으로 훈련된 강력한 탐지 모델(ViTDet-H)과 성능을 비교했습니다. 놀랍게도 SAM은 중간 크기, 큰 크기, 그리고 희귀한 객체에 대해서는 전문 모델보다 더 높은 재현율(Average Recall)을 기록했습니다.\n객체 탐지기가 찾아낸 박스를 프롬프트로 주어 객체를 분할하는 실험입니다. Table 5의 자동 평가 점수(AP)는 전문 모델인 ViTDet-H보다 낮았지만, Figure 11의 사람 평가에서는 SAM의 마스크 품질이 더 높게 평가되었습니다. 이는 ViTDet-H가 COCO나 LVIS 데이터셋의 고유한 주석 편향(예: 마스크에 구멍이 없는 등)까지 학습하여 점수를 높인 반면, SAM은 그런 편향 없이 더 보편적으로 고품질의 마스크를 생성하기 때문으로 분석됩니다.\n3. 제로샷 텍스트-마스크 변환 개념 증명 단계의 실험으로, 텍스트 프롬프트를 사용해 객체를 분할하는 가능성을 보여주었습니다.\nSAM은 \u0026ldquo;a wheel(바퀴)\u0026rdquo; 같은 간단한 텍스트뿐만 아니라, \u0026ldquo;beaver tooth grille(비버 이빨 그릴)\u0026ldquo;과 같은 구체적이고 미묘한 표현까지 이해하고 해당 객체를 정확하게 분할해냈습니다. 텍스트만으로 실패할 경우, 점 프롬프트를 추가하여 정확도를 높일 수도 있습니다.\n","permalink":"https://mookjsi.github.io/posts/paper-review-sam/","summary":"YBIGTA DS Session 09/10 Presentation","title":"Segment Anything 논문 리뷰"},{"content":"1. 서론 객체 탐지란 이미지 속에서 우리가 관심 있는 물체(객체)가 무엇인지(분류, classification) 그리고 어디에 있는지(위치 파악, localization)를 알아내는 기술입니다. 예를 들어, 자율주행 자동차가 도로 위의 사람, 다른 자동차, 신호등을 정확히 인식하는 데 이 기술이 사용됩니다.\n기존의 객체 탐지 모델들은 이 문제를 약간 간접적인 방식으로 풀어왔습니다. 이미지 위에 수많은 가상의 사각형(앵커 박스, anchor box)이나 **후보 영역(proposal)**을 미리 뿌려놓고, 이 중에서 어떤 사각형이 실제 물체를 잘 감싸고 있는지, 그리고 그 물체는 무엇인지를 맞추는 방식이었습니다. 이 방법은 꽤 성공적이었지만 몇 가지 번거로운 과정이 필요했습니다.\n수작업 설계 (Hand-designed components): 앵커 박스의 크기나 비율을 미리 정해야 하는 등 사람이 직접 설정해야 하는 부분이 많았습니다. 후처리 (Post-processing): 모델이 하나의 물체에 대해 여러 개의 겹치는 박스를 예측하는 경우가 많아서, 이 중 가장 정확한 박스 하나만 남기는 **\u0026lsquo;비최대 억제(Non-Maximum Suppression, NMS)\u0026rsquo;**라는 복잡한 후처리 과정이 필수적이었습니다. 이 논문에서 제안하는 DETR (DEtection TRansformer) 은 이러한 복잡한 과정들을 모두 없애고, 객체 탐지를 \u0026ldquo;정답 집합을 한 번에 예측하는 문제\u0026quot;로 재정의했습니다. 마치 사람이 이미지를 한 번 쓱 보고 \u0026ldquo;여기엔 고양이 한 마리, 저기엔 강아지 두 마리가 있네\u0026quot;라고 말하는 것처럼, 모델이 직접 최종 예측 결과의 **\u0026lsquo;집합(set)\u0026rsquo;**을 출력하도록 만든 것입니다.\n이러한 혁신은 두 가지 핵심 요소 덕분에 가능했습니다.\n이분 매칭 손실 (Bipartite Matching Loss): 모델의 예측 결과와 실제 정답을 일대일로 짝지어주는 손실 함수입니다. 이를 통해 중복된 예측을 자연스럽게 방지합니다. 트랜스포머 (Transformer) 구조: 원래 번역 분야에서 뛰어난 성능을 보인 아키텍처로, 이미지 전체의 맥락을 종합적으로 이해하는 데 탁월한 능력을 보입니다. 위 그림은 DETR의 전체적인 흐름을 보여줍니다.\n먼저, 일반적인 CNN을 사용해 이미지의 특징(feature)을 추출합니다. 이는 이미지의 중요한 시각적 정보를 압축하는 과정입니다. 이 특징 정보를 트랜스포머 인코더-디코더에 입력합니다. 트랜스포머는 이미지 전체의 관계를 파악하여 고정된 개수의 예측 상자(box prediction) 집합을 출력합니다. 학습 과정에서는 **이분 매칭 손실(bipartite matching loss)**을 사용해 모델이 예측한 상자들과 실제 정답 상자들을 가장 효율적으로 일대일 매칭시킵니다. 매칭되지 못한 예측 상자는 **\u0026ldquo;물체 없음(no object)\u0026rdquo;**으로 학습됩니다. 2. 기술 설명 (The DETR model) 위 그림은 DETR의 상세한 구조를 보여줍니다.\n백본 (Backbone) ResNet과 같은 표준 CNN 모델을 사용하여 이미지에서 저해상도의 특징 맵(feature map)을 추출합니다. 예를 들어, 2048개의 채널을 가진 특징 맵을 만들어냅니다.\n트랜스포머 인코더 (Transformer Encoder) CNN이 만든 특징 맵은 2D 형태인데, 트랜스포머에 넣기 위해 1D 시퀀스(순서가 있는 데이터) 형태로 길게 펼칩니다. 각 특징의 위치 정보를 알려주기 위해 **공간적 위치 인코딩(spatial positional encoding)**을 더해줍니다. 트랜스포머는 본래 순서 개념이 없기 때문에, \u0026ldquo;이 특징은 이미지의 왼쪽 위에 있다\u0026quot;와 같은 위치 정보를 인위적으로 주입해야 합니다. 인코더는 셀프 어텐션(self-attention) 메커니즘을 통해 이미지의 모든 픽셀 영역들이 서로 어떻게 연관되어 있는지를 학습합니다. 예를 들어, 이미지에 얼룩말 두 마리가 있다면, 인코더는 얼룩말 무늬를 가진 픽셀들이 서로 강하게 연관되어 있음을 파악하고, 각 얼룩말을 별개의 개체로 분리해내는 역할을 합니다. 트랜스포머 디코더 (Transformer Decoder) 객체 쿼리란? - 100명의 전문 탐정단\nDETR의 **객체 쿼리(object queries)**를 가장 쉽게 이해하는 방법은, 이미지를 \u0026lsquo;사건 현장\u0026rsquo;이라고 보고 100명의 전문 탐정단이 각자 빈 수첩(=객체 쿼리)을 들고 파견된다고 상상하는 것입니다.\n이 탐정들은 처음에는 아무 정보도 없는 상태(빈 수첩)로 시작하지만, 학습을 거치며 각자 자신만의 전문 분야(특정 위치, 크기, 형태 등)를 갖게 됩니다. 각 탐정(객체 쿼리)은 이미지 전체(인코더의 출력)를 샅샅이 살피며, 자신이 맡을 단서(객체)를 찾으려고 합니다. 탐정들끼리도 계속 정보를 공유(셀프 어텐션)하여, 한 명이 하나의 단서만 맡도록 역할을 분담합니다. 이 덕분에 하나의 물체에 여러 박스가 중복 예측되는 문제가 자연스럽게 해결됩니다(NMS 불필요). 디코더에서의 객체 쿼리 역할:\n디코더는 이미지 특징을 직접 받는 대신, **객체 쿼리(object queries)**라는 고정된 개수(N=100)의 학습 가능한 임베딩을 입력으로 받습니다. 이 객체 쿼리는 \u0026ldquo;이미지에서 찾을 N개의 물체 슬롯\u0026quot;이자, \u0026lsquo;사건 현장에 파견된 100명의 탐정\u0026rsquo;에 해당합니다. 처음에는 빈 슬롯(빈 수첩)이지만, 학습을 통해 각각 특정 위치나 크기의 물체를 찾는 데 특화됩니다. 디코더는 이 객체 쿼리들과 인코더의 출력(이미지 전체의 문맥 정보)을 함께 사용하여 \u0026ldquo;물체가 어디에 있는지\u0026quot;를 추론합니다. 디코더의 셀프 어텐션은 N개의 예측 간의 관계를 모델링하여, 예를 들어 하나의 물체에 대해 여러 슬롯이 중복으로 예측하는 것을 억제하는 역할을 합니다(탐정들끼리 역할 분담). 하나의 중요한 특징은 이 N개의 객체를 병렬적으로(in parallel), 즉 한 번에 디코딩한다는 점입니다. 기존 트랜스포머가 단어를 하나씩 순서대로 생성하는 것과 대조적입니다. 예측 헤드 (Prediction Heads, FFNs) 디코더에서 나온 N개의 출력 임베딩은 각각 동일한 구조를 공유하는 작은 신경망(FFN)으로 전달됩니다. 이 FFN은 최종적으로 각 슬롯에 대해 물체의 **클래스(class)**와 바운딩 박스(bounding box) 좌표를 예측합니다. 만약 해당 슬롯이 찾은 물체가 없다면, **\u0026ldquo;물체 없음(no object)\u0026rdquo;**이라는 특별한 클래스를 예측하게 됩니다. 손실 함수 (Loss Function): 객체 탐지를 위한 집합 예측 DETR의 핵심 아이디어는 예측과 정답을 \u0026lsquo;집합 대 집합\u0026rsquo;으로 보고, 둘 사이의 최적의 짝을 찾아 손실을 계산하는 것입니다.\n이분 매칭 (Bipartite Matching) 모델이 100개의 예측(집합 $\\hat{y}$)을 내놓고, 실제 이미지에는 5개의 물체(정답 집합 y)가 있다고 가정해 봅시다. 100개의 예측 중 어떤 것이 5개의 정답 각각에 해당하는지를 결정해야 합니다. 이때 **헝가리안 알고리즘(Hungarian Algorithm)**을 사용하여 전체 매칭 비용이 최소가 되는 최적의 일대일 짝(optimal assignment)을 찾습니다.\n이 매칭 비용 $\\mathcal{L}_{match}$는 두 가지를 고려합니다: (1) 예측한 클래스가 정답 클래스와 일치할 확률, (2) 예측한 박스가 정답 박스와 얼마나 비슷한지.\n수식 1: 최적 할당 (Optimal Assignment) $$ \\hat{\\sigma} = \\underset{\\sigma \\in \\mathfrak{S}_N}{\\arg\\min} \\sum_{i}^{N} \\mathcal{L}_{\\text{match}}(y_i, \\hat{y}_{\\sigma(i)}) $$ 최적의 순열(permutation) $\\hat{\\sigma}$ 를 찾는 과정을 나타냅니다. 여기서 $\\mathfrak{S}_{N}$ 은 N개 원소의 모든 가능한 순열 집합을 의미합니다. $y_{i}$ 는 i번째 실제 정답 객체(클래스 $c_i$ , 박스 $b_i$ )이고, $\\hat{y}_{\\sigma(i)}$ 는 순열 $\\sigma$ 에 의해 재배열된 예측 중 i번째 위치에 온 예측입니다. 이 수식의 목표는 모든 N개의 쌍에 대한 매칭 비용( $\\mathcal{L}_{\\text{match}}$ )의 총합을 최소화하는 순열 $\\hat{\\sigma}$ 를 찾는 것입니다. 이는 전형적인 할당 문제(assignment problem)이며, 헝가리안 알고리즘을 통해 다항 시간 내에 효율적으로 해결할 수 있습니다. 이 과정을 통해 각 정답 객체에 대해 가장 적절한 예측이 단 하나만 할당되도록 보장하여, 중복 탐지를 원천적으로 방지합니다.\n수식 2: 헝가리안 손실 (Hungarian Loss) $$ \\mathcal{L}_{\\text{Hungarian}}(y, \\hat{y}) = \\sum_{i=1}^{N} \\left[ -\\log\\hat{p}_{\\hat{\\sigma}(i)}(c_i) + \\mathbf{1}_{c_i \\ne \\emptyset} \\mathcal{L}_{\\text{box}}(b_i, \\hat{b}_{\\hat{\\sigma}(i)}) \\right] $$ 위에서 찾은 최적의 짝 $\\hat{\\sigma}$을 바탕으로 최종 손실을 계산합니다. 이 손실은 모든 N개의 매칭된 쌍에 대한 손실의 합입니다.\n클래스 예측 손실: $-\\log\\hat{p}_{\\hat{\\sigma}(i)}(c_{i})$ 는 표준적인 교차 엔트로피(cross-entropy) 손실입니다. 즉, 최적의 짝으로 매칭된 예측이 정답 클래스 $c_i$ 를 얼마나 정확하게 예측했는지를 측정합니다. 박스 손실: $\\mathbf{1}_{{c_{i}\\ne\\emptyset}}\\mathcal{L}_{\\text{box}}(...)$ 는 바운딩 박스에 대한 손실입니다. $\\mathbf{1}_{{c_{i}\\ne\\emptyset}}$ 는 정답이 \u0026lsquo;물체 없음\u0026rsquo;이 아닐 경우에만 박스 손실을 계산하라는 의미의 지시 함수(indicator function)입니다. $\\mathcal{L}_{\\text{box}}$ 는 아래에서 설명할 L1 손실과 GIoU 손실의 조합으로 이루어집니다. 바운딩 박스 손실 ($\\mathcal{L}_{box}$) 기존의 L1 손실(좌표 차이의 절댓값 합)은 박스가 클 때 손실 값도 커지는 문제가 있어, 박스 크기에 따라 손실의 스케일이 달라집니다. 이를 해결하기 위해 DETR은 두 가지 손실을 조합합니다. $$ \\mathcal{L}_{\\text{box}}(b_i, \\hat{b}_{\\sigma(i)}) = \\lambda_{\\text{iou}}\\mathcal{L}_{\\text{iou}}(b_i, \\hat{b}_{\\sigma(i)}) + \\lambda_{L1}||b_i - \\hat{b}_{\\sigma(i)}||_1 $$ L1 손실: 예측 박스와 정답 박스의 중심점 좌표, 너비, 높이 간의 차이를 계산합니다. 일반화된 IoU (GIoU) 손실: 두 박스가 얼마나 겹치는지를 나타내는 IoU(Intersection over Union)를 일반화한 것으로, 박스 크기에 무관하게(scale-invariant) 손실을 측정할 수 있어 작은 물체와 큰 물체를 공평하게 학습할 수 있습니다. 수식 예시로 이해하기: \u0026ldquo;고양이와 강아지 찾기\u0026quot;로 풀어보는 DETR의 집합 예측 지금까지 소개한 수식들을 실제 객체 탐지 상황에 대입해, 처음부터 끝까지 하나의 흐름으로 예시를 들어 설명해보겠습니다.\n상황 예시: 이미지 속 고양이와 강아지 입력 이미지: 왼쪽에는 고양이 한 마리, 오른쪽에는 강아지 한 마리가 있는 사진 DETR 모델: 최대 4개( $N=4$ )의 객체를 예측하도록 설정 1. 정답(Ground Truth)과 모델의 예측 정답 집합 (y):\nGT1: {클래스: \u0026lsquo;고양이\u0026rsquo;, 박스: b_cat} GT2: {클래스: \u0026lsquo;강아지\u0026rsquo;, 박스: b_dog} GT3: {클래스: \u0026lsquo;없음 ∅\u0026rsquo;} GT4: {클래스: \u0026lsquo;없음 ∅\u0026rsquo;} 모델의 예측 집합 (ŷ):\nP1: {\u0026lsquo;고양이\u0026rsquo; 확률 0.9, 박스: b_p1} (고양이와 매우 비슷하게 예측) P2: {\u0026lsquo;강아지\u0026rsquo; 확률 0.8, 박스: b_p2} (강아지와 매우 비슷하게 예측) P3: {\u0026lsquo;고양이\u0026rsquo; 확률 0.7, 박스: b_p3} (P1과 중복된, 덜 정확한 고양이 예측) P4: {\u0026lsquo;없음 ∅\u0026rsquo; 확률 0.85, 박스: b_p4} (스스로 \u0026lsquo;없음\u0026rsquo;이라고 예측) 2. 수식 1: 최적의 짝 찾기 (Optimal Assignment) $\\hat{\\sigma} = \\underset{\\sigma \\in \\mathfrak{S}_N}{\\arg\\min} \\sum_{i}^{N} \\mathcal{L}_{\\text{match}}(y_i, \\hat{y}_{\\sigma(i)})$ 이 단계에서는 4개의 정답과 4개의 예측 사이에서 가장 합리적인 일대일 짝을 찾습니다.\n비용( $\\mathcal{L}_{match}$ )은 (1) 클래스 확률, (2) 박스 유사도를 모두 고려합니다.\n컴퓨터는 아래와 같은 비용 행렬을 만듭니다(실제 값은 예시):\n예측 P1 (고양이 0.9) 예측 P2 (강아지 0.8) 예측 P3 (고양이 0.7) 예측 P4 (없음 0.85) GT1 (고양이) 비용 낮음 비용 높음 비용 중간 비용 높음 GT2 (강아지) 비용 높음 비용 낮음 비용 높음 비용 높음 GT3 (없음 ∅) 비용 중간 비용 중간 비용 중간 비용 중간 GT4 (없음 ∅) 비용 중간 비용 중간 비용 중간 비용 중간 헝가리안 알고리즘이 이 표를 분석해 전체 비용이 최소가 되는 조합을 찾습니다.\n결과적으로 다음과 같은 짝( $\\hat{\\sigma}$ )이 만들어집니다.\nGT1 (\u0026lsquo;고양이\u0026rsquo;) ↔️ P1 (가장 정확한 고양이 예측) GT2 (\u0026lsquo;강아지\u0026rsquo;) ↔️ P2 (가장 정확한 강아지 예측) GT3 (\u0026lsquo;없음 ∅\u0026rsquo;) ↔️ P3 (중복된 고양이 예측은 \u0026lsquo;없음\u0026rsquo; 처리) GT4 (\u0026lsquo;없음 ∅\u0026rsquo;) ↔️ P4 (쓸모없는 예측은 \u0026lsquo;없음\u0026rsquo; 처리) 3. 수식 2: 최종 손실 계산 (Hungarian Loss) $\\mathcal{L}_{\\text{Hungarian}}(y, \\hat{y}) = \\sum_{i=1}^{N} \\left[ -\\log\\hat{p}_{\\hat{\\sigma}(i)}(c_i) + \\mathbf{1}_{c_i \\ne \\emptyset} \\mathcal{L}_{\\text{box}}(b_i, \\hat{b}_{\\hat{\\sigma}(i)}) \\right]$ 위에서 찾은 짝을 바탕으로, 각 쌍에 대해 손실을 계산합니다.\n[GT1↔P1] 클래스 손실: 고양이 확률 0.9 → $-\\log(0.9)$ (낮은 손실) 박스 손실: 실제 고양이 박스와 예측 박스의 차이( $\\mathcal{L}_{box}$ ) [GT2↔P2] 클래스 손실: 강아지 확률 0.8 → $-\\log(0.8)$ (낮은 손실) 박스 손실: 실제 강아지 박스와 예측 박스의 차이( $\\mathcal{L}_{box}$ ) [GT3↔P3] 클래스 손실: 정답은 \u0026lsquo;없음\u0026rsquo;, 예측이 \u0026lsquo;없음\u0026rsquo;일 확률이 10%라면 $-\\log(0.1)$ (매우 큰 손실) 박스 손실: 정답이 \u0026lsquo;없음\u0026rsquo;이므로 계산하지 않음(0점) [GT4↔P4] 클래스 손실: 정답은 \u0026lsquo;없음\u0026rsquo;, 예측이 \u0026lsquo;없음\u0026rsquo;일 확률이 85%라면 $-\\log(0.85)$ (낮은 손실) 박스 손실: 정답이 \u0026lsquo;없음\u0026rsquo;이므로 계산하지 않음(0점) 이렇게 네 쌍의 손실을 모두 더한 값이 최종 손실이 되어, 모델이 더 똑똑해지도록 학습에 사용됩니다.\n4. 바운딩 박스 손실( $\\mathcal{L}_{box}$ )의 실제 의미 $\\mathcal{L}_{\\text{box}} = \\lambda_{\\text{iou}}\\mathcal{L}_{\\text{iou}} + \\lambda_{L1}||\\cdot||_1$ L1 손실: 예측 박스와 실제 박스의 좌표(x, y, w, h) 차이의 절댓값 합\n예) 고양이 박스와 예측 박스가 각각 (10,10,50,50), (12,11,48,52)라면, L1 손실은 $|10-12|+|10-11|+|50-48|+|50-52|=2+1+2+2=7$ 단점: 큰 물체와 작은 물체에 동일한 픽셀 오차가 들어가면 불공평함 GIoU 손실: 두 박스가 얼마나 겹치는지(Intersection over Union, IoU)를 일반화한 값\n예) 고양이 박스와 예측 박스가 거의 겹치면 GIoU 손실이 매우 작음(정확) 장점: 박스 크기에 상관없이 공평하게 평가 최종 조합: GIoU 손실로 전체적인 위치와 크기 일치도를, L1 손실로 미세한 위치 조정을 동시에 학습\n이처럼 DETR의 집합 예측 손실은\n중복 예측을 방지하고, 박스 크기에 상관없이 공평하게 평가하며, 후처리(NMS) 없이도 정확한 객체 탐지가 가능하도록 설계되어 있습니다. 3. 실험 (Experiments) DETR의 성능을 검증하기 위해 가장 널리 사용되는 COCO 데이터셋으로 다양한 실험을 진행했습니다.\n이 표는 DETR과 기존의 강력한 모델인 Faster R-CNN의 성능을 비교합니다.\n결론적으로, DETR은 매우 잘 최적화된 Faster R-CNN과 **비교할 만한 성능(AP 42.0 vs 42.0)**을 달성했습니다. 특히 주목할 점은, DETR이 **큰 물체에 대해서는 훨씬 뛰어난 성능($AP_L$ 61.1 vs 53.4)**을 보인다는 것입니다. 이는 트랜스포머 인코더가 이미지 전체의 넓은 문맥을 보기 때문에 가능한 것으로 분석됩니다. 반면, 작은 물체에 대해서는 성능이 다소 낮게($AP_S$ 20.5 vs 26.6) 나타났습니다.\n주요 구성 요소 분석 (Ablation Studies) DETR의 어떤 부분이 성능에 얼마나 기여하는지 알아보기 위해 여러 실험을 진행했습니다.\n인코더의 중요성 (Table 2, Figure 3): 인코더 층을 제거하자 전체 성능(AP)이 약 3.9점 하락했으며, 특히 큰 물체에 대한 성능이 6.0점이나 떨어졌습니다. 이는 이미지 전체의 맥락을 이해하는 인코더가 객체들을 서로 분리하는 데 중요한 역할을 함을 시사합니다.\nFigure 3은 인코더의 셀프 어텐션이 어떻게 동작하는지 시각화한 것입니다. 그림 중앙의 소 이미지 위에 찍힌 빨간 점이 특정 위치를 의미하고, 주변의 작은 이미지들은 해당 위치가 이미지의 다른 어떤 부분에 주목(attention)하는지를 보여줍니다. 각기 다른 소들이 서로 다른 영역으로 분리되어 주목받는 것을 볼 수 있는데, 이는 인코더가 이미 개별 인스턴스들을 분리하고 있음을 보여줍니다.\n디코더의 중요성 (Figure 4): 이 그래프는 디코더 층이 깊어질수록 성능(AP)이 꾸준히 향상되는 것을 보여줍니다. 첫 번째 디코더 층의 결과와 마지막 층의 결과를 비교하면 AP가 8점 이상 크게 향상되었습니다.\n흥미로운 점은, 첫 번째 디코더 층에서는 NMS 후처리를 적용하면 성능이 오르지만, 층이 깊어질수록 NMS의 효과가 줄어들고 마지막에는 오히려 성능을 약간 해친다는 것입니다. 이는 디코더의 셀프 어텐션이 스스로 중복 예측을 억제하는 법을 학습하기 때문에, DETR은 설계적으로 NMS가 필요 없다는 것을 실험적으로 증명합니다.\n그 외 요소들 (Table 3, 4): 위치 인코딩 (Table 3): 공간적 위치 인코딩을 제거하자 성능이 7.8 AP나 하락하여, 이 요소가 매우 중요함을 확인했습니다. 손실 함수 (Table 4): L1 손실과 GIoU 손실 중 GIoU 손실이 성능에 거의 절대적인 기여를 하며, L1 손실은 보조적인 역할만 한다는 것을 발견했습니다. Figure 6은 디코더가 각 물체를 예측할 때 이미지의 어느 부분을 주목하는지 보여줍니다. 코끼리나 얼룩말을 탐지할 때, 주로 머리, 다리 등 물체의 **윤곽을 결정하는 극단적인 부분(extremities)**에 주목하는 경향을 보입니다. 이는 인코더가 이미 \u0026ldquo;여기에 얼룩말이 있다\u0026quot;고 알려주면, 디코더는 그 경계만 정확히 그리는 데 집중한다는 가설을 뒷받침합니다.\nFigure 7은 100개의 객체 쿼리(슬롯)가 각각 어떤 종류의 박스를 예측하도록 학습되는지 보여줍니다. 각 슬롯은 특정 **위치(area)와 크기(box size)**를 전담하도록 특화되는 경향을 보입니다. 예를 들어 어떤 슬롯은 이미지 중앙의 큰 물체를, 다른 슬롯은 왼쪽 하단의 작은 물체를 주로 찾도록 학습됩니다.\n학습 데이터에는 기린이 13마리 이상 있는 이미지가 없었습니다. 이 모델이 학습 데이터에 없는 상황에서도 잘 동작하는지 알아보기 위해, 인공적으로 기린 24마리가 있는 이미지를 만들어 테스트했습니다.\nFigure 5에서 볼 수 있듯이, DETR은 놀랍게도 24마리의 기린을 모두 정확하게 찾아냈습니다. 이는 100개의 객체 쿼리가 특정 클래스(예: \u0026lsquo;기린 전용 쿼리\u0026rsquo;)에 과적합되지 않고, 일반적인 물체를 찾는 능력을 학습했음을 보여줍니다.\nPanoptic Segmentation으로의 확장 Panoptic Segmentation은 이미지의 모든 픽셀을 \u0026ldquo;어떤 물체에 속하는지(things)\u0026rdquo; 또는 \u0026ldquo;어떤 배경에 속하는지(stuff)\u0026ldquo;로 구분하는 더 복잡한 작업입니다.\nFigure 8은 DETR에 간단한 **마스크 헤드(mask head)**를 추가하여 이 작업을 수행하는 방법을 보여줍니다. 디코더의 출력 각각에 대해 해당 물체의 마스크를 예측하고, 이를 합쳐 최종 결과를 만듭니다.\nTable 5는 DETR이 PanopticFPN과 같은 기존의 강력한 모델들을 능가하는 성능을 보였음을 나타냅니다. 특히 배경(stuff) 클래스에서 강점을 보이는데, 이는 이미지 전체를 보는 인코더의 힘 덕분일 가능성이 높습니다.\nFigure 9는 DETR이 생성한 Panoptic Segmentation의 예시 이미지로, 물체와 배경 모두에 대해 깔끔한 결과를 보여줍니다.\n4. 결론 (Conclusion) 이 논문은 트랜스포머와 이분 매칭 손실을 기반으로 객체 탐지를 **\u0026lsquo;직접적인 집합 예측 문제\u0026rsquo;**로 풀어내는 새로운 패러다임인 DETR을 제시했습니다. DETR은 기존의 복잡한 파이프라인(앵커, NMS 등)을 제거하면서도, 고도로 최적화된 Faster R-CNN과 대등한 성능을 달성했습니다.\n또한, DETR의 구조는 매우 간단하고 유연하여 Panoptic Segmentation과 같은 더 복잡한 문제로도 쉽게 확장될 수 있음을 보여주었습니다. 특히 이미지의 전역적인 정보를 활용하는 능력 덕분에 큰 객체 탐지에서 뛰어난 성능을 보였습니다.\n","permalink":"https://mookjsi.github.io/posts/paper-review-detr/","summary":"YBIGTA DS 09/23 Session Presentation","title":"DETR: End-to-End Object Detection with Transformers"},{"content":"CVPR 2016에서 발표되어 딥러닝 역사에 한 획을 그은 논문, Deep Residual Learning for Image Recognition에 대한 리뷰를 공유합니다.\n이 논문은 당시 딥러닝 모델의 큰 난제였던 \u0026lsquo;네트워크가 깊어질수록 오히려 성능이 저하되는\u0026rsquo; 문제를 해결했습니다. 저자들의 해법인 **ResNet (Residual Network)**은 \u0026lsquo;잔차 학습\u0026rsquo;이라는 혁신적인 구조를 도입하여 이전에는 불가능했던 100층 이상의 초심층 신경망 훈련을 가능하게 했습니다.\n서론 컴퓨터가 이미지를 인식하는 기술, 예를 들어 사진 속의 고양이를 알아보는 인공지능(AI)은 \u0026lsquo;심층 신경망(Deep Neural Network)\u0026lsquo;이라는 기술을 사용합니다. 이 신경망은 인간의 뇌가 정보를 처리하는 방식을 모방한 것으로, 여러 개의 층(layer)으로 이루어져 있습니다. 이론적으로는 이 층을 많이 쌓을수록, 즉 네트워크가 \u0026lsquo;깊어질수록\u0026rsquo; 더 똑똑해져야 합니다. 마치 우리가 여러 단계의 사고를 거쳐 복잡한 문제를 해결하는 것과 같죠.\n하지만 실제로는 무작정 층을 깊게 쌓기만 하면 오히려 성능이 떨어지는 성능 저하 (Degradation) 문제가 발생했습니다. 신기하게도 이는 단순히 계산이 너무 복잡해져서 생기는 과적합(overfitting) 문제도 아니었습니다. 더 깊은 모델이 그보다 얕은 모델보다 훈련 데이터에 대한 오류율(training error)이 더 높게 나타나는 이상한 현상이었습니다.\n위 그림은 이 문제를 명확히 보여줍니다. CIFAR-10이라는 이미지 데이터셋으로 20층 네트워크와 56층 네트워크를 학습시킨 결과입니다. 왼쪽 그래프(training error)를 보면, 더 깊은 56층 네트워크(붉은색 선)가 20층 네트워크(노란색 선)보다 훈련 오류가 더 높습니다. 당연히 오른쪽 그래프(test error)에서도 56층 네트워크의 테스트 오류가 더 높게 나타납니다. 상식적으로 더 깊은 네트워크가 최소한 얕은 네트워크만큼의 성능은 내야 하는데, 실제로는 그렇지 못했던 것입니다.\n이 논문은 바로 이 \u0026lsquo;성능 저하\u0026rsquo; 문제를 해결하기 위해 **깊은 잔차 학습 (Deep Residual Learning)**이라는 새로운 프레임워크를 제안합니다. 간단히 말해, 네트워크가 처음부터 정답을 완벽하게 맞추려고 애쓰는 대신, 이미 알고 있는 정보(입력값)를 바탕으로 \u0026lsquo;차이(residual)\u0026lsquo;만을 학습하도록 구조를 바꾼 것입니다. 이 혁신적인 방법으로 저자들은 이전에 불가능하다고 여겨졌던 152층 깊이의 네트워크를 성공적으로 훈련시켰고, 당시 이미지 인식 대회인 ILSVRC 2015에서 1위를 차지하는 쾌거를 이루었습니다.\n기술 설명 ResNet의 핵심 아이디어는 어떻게 \u0026lsquo;차이\u0026rsquo;만을 학습하게 만드는 것일까요? 바로 **지름길 연결 (Shortcut Connection)**이라는 구조를 통해 구현됩니다.\n기존의 신경망은 입력값 x가 여러 층을 순서대로 통과하며 복잡한 함수 H(x)를 학습하려고 했습니다. 예를 들어, 고양이 사진(x)을 보고 \u0026lsquo;고양이\u0026rsquo;라는 정답(H(x))을 바로 찾아내려는 방식이었죠.\n하지만 ResNet은 생각을 바꿨습니다. \u0026lsquo;어차피 입력값 x가 있는데, 굳이 H(x) 전체를 새로 배울 필요가 있을까? 그냥 x에다가 약간의 정보만 더해서 정답을 만들면 되지 않을까?\u0026rsquo; 라는 접근입니다. 그래서 네트워크가 학습해야 할 목표를 H(x)에서 F(x) = H(x) - x로 바꿉니다. 여기서 F(x)가 바로 입력값과 정답 사이의 \u0026lsquo;차이\u0026rsquo;, 즉 **잔차 (residual)**입니다. 네트워크는 이 잔차 F(x)를 학습한 뒤, 원래 입력값 x를 더해 최종 결과(F(x) + x)를 만들어냅니다.\n위 그림은 이 \u0026lsquo;잔차 학습\u0026rsquo;의 기본 단위를 보여줍니다.\n입력값 x가 두 갈래로 나뉩니다. 한쪽은 기존처럼 가중치 층(weight layer)을 통과하며 복잡한 변환, 즉 F(x)를 학습합니다. 다른 한쪽은 아무런 변환 없이 그대로 건너뛰는 \u0026lsquo;지름길(shortcut)\u0026lsquo;을 따라갑니다. 이를 **항등 매핑 (identity mapping)**이라고 부릅니다. 마지막에 두 결과(F(x)와 x)가 더해져 최종 출력(F(x) + x)이 됩니다. 이 구조가 왜 효과적일까요? 만약 어떤 층에서 아무것도 학습할 필요 없이 입력값을 그대로 전달하는 것이 최선인 상황이라면, 기존 네트워크는 여러 층을 거치며 입력과 출력이 똑같아지는 복잡한 변환을 학습해야만 했습니다. 이는 매우 어려운 일이었죠. 하지만 ResNet 구조에서는 네트워크가 잔차 F(x)를 그냥 \u0026lsquo;0\u0026rsquo;으로 만들기만 하면 됩니다. 즉, 가중치를 0으로 만들어 아무것도 바꾸지 않으면, 자연스럽게 입력 x가 그대로 출력으로 나가게 됩니다. 훨씬 쉬운 방법으로 최적의 해를 찾을 수 있는 것입니다.\n다음은 실제 네트워크 구조입니다.\nVGG-19 (왼쪽): 당시 표준으로 여겨지던 깊은 네트워크 구조입니다. 34-layer plain (중간): VGG-19의 모델을 따라 단순히 층을 깊게 쌓은 일반적인 네트워크입니다. 이 구조에서 성능 저하 문제가 발생합니다. 34-layer residual (오른쪽): 중간의 \u0026lsquo;plain\u0026rsquo; 네트워크와 똑같은 구조에 \u0026lsquo;지름길 연결(shortcut connection)\u0026lsquo;만 추가한 ResNet 구조입니다. 굽은 화살표들이 바로 이 지름길을 나타냅니다. 더 깊은 네트워크(50층 이상)를 효율적으로 만들기 위한 병목 (Bottleneck) 구조는 다음과 같습니다.\n기존의 블록(왼쪽)이 3x3 필터의 합성곱 층 두 개로 이루어졌다면, 병목 블록(오른쪽)은 1x1, 3x3, 1x1 합성곱 층 세 개로 구성됩니다. 첫 번째 1x1 합성곱은 채널 수를 줄여 계산량을 감소시키고(병목처럼 입구가 좁아짐), 3x3 합성곱으로 핵심적인 연산을 수행한 뒤, 마지막 1x1 합성곱으로 다시 채널 수를 원래대로 복원하는 방식입니다. 이 구조 덕분에 층은 더 깊게 쌓으면서도 전체적인 계산 복잡도는 VGG 네트워크보다 낮게 유지할 수 있었습니다. 실험 저자들은 제안한 ResNet의 효과를 증명하기 위해 이미지넷(ImageNet)과 CIFAR-10이라는 대표적인 이미지 데이터셋으로 다양한 실험을 진행했습니다.\n이미지넷(ImageNet) 분류 실험 이미지넷은 1000개의 클래스(종류)로 이루어진 128만 장의 방대한 이미지 데이터셋입니다.\n위 결과들은 ResNet이 성능 저하 문제를 어떻게 해결하는지 보여줍니다.\n왼쪽 그래프: 일반(plain) 네트워크의 경우, 34층(붉은색 선)이 18층(하늘색 선)보다 훈련 오류와 검증 오류 모두 더 높습니다. 전형적인 성능 저하 현상입니다. 오른쪽 그래프: ResNet의 경우, 상황이 역전됩니다. 34층 ResNet(붉은색 선)이 18층 ResNet(하늘색 선)보다 오류율이 훨씬 낮습니다. 깊이가 깊어질수록 성능이 향상된 것입니다. 위 표는 이 결과를 수치로 보여줍니다. 일반 네트워크는 18층(27.94%)에서 34층(28.54%)으로 갈 때 오류율이 높아졌지만, ResNet은 18층(27.88%)에서 34층(25.03%)으로 갈 때 오류율이 2.8%나 크게 감소했습니다.\n더 깊은 ResNet 모델들의 성능은 위 두 표와 같습니다. 저자들은 앞에서 설명한 \u0026lsquo;병목\u0026rsquo; 구조를 사용해 50층, 101층, 그리고 무려 152층에 달하는 ResNet을 만들었습니다. 34층(25.03%)부터 시작해 50층(22.85%), 101층(21.75%), 152층(21.43%)으로 깊어질수록 top-1 오류율이 꾸준히 감소하는 것을 볼 수 있습니다. 성능 저하 문제없이 깊이의 이점을 취한 것입니다.\n특히 152층 ResNet은 단일 모델만으로 4.49%의 top-5 검증 오류율을 달성했는데, 이는 당시 다른 여러 모델을 합친 앙상블(ensemble) 결과보다도 좋은 성적이었습니다.\n최종 대회 결과, 여러 ResNet 모델을 앙상블하여 이미지넷 테스트 데이터셋에서 **3.57%**라는 경이로운 top-5 오류율을 기록하며 ILSVRC 2015 대회에서 1위를 차지했습니다.\nCIFAR-10 분석 및 1000층 이상의 네트워크 CIFAR-10 데이터셋을 이용한 실험에서도 비슷한 결과가 나타났습니다. 위 그래프는 CIFAR-10에서의 훈련 과정을 보여줍니다.\n왼쪽 (plain networks): 일반 네트워크는 20층에서 56층으로 깊어질수록 오류율이 점점 높아지는 성능 저하 현상을 보입니다. 중간 (ResNets): 반면, ResNet은 20층부터 110층까지 깊이가 증가할수록 오류율이 꾸준히 감소합니다. 오른쪽 (110-layer vs 1202-layer): 저자들은 여기서 더 나아가 1202층이라는 극단적으로 깊은 네트워크를 훈련시키는 데 성공했습니다. 훈련 오류는 0.1% 미만으로 매우 낮았지만(오른쪽 그래프 아래쪽 선), 테스트 오류(7.93%)는 110층 모델(6.43%)보다 다소 높게 나타났습니다. 이는 작은 데이터셋에 비해 모델이 너무 거대해서 발생한 과적합(overfitting) 때문으로 분석됩니다. 위 그래프는 각 층의 응답(출력값)의 표준편차를 분석한 것입니다.\n그래프를 보면 전반적으로 ResNet(붉은색, 검은색 선)의 응답값이 일반 네트워크(노란색, 분홍색 선)보다 작습니다. 이는 ResNet의 잔차 함수가 일반적으로 \u0026lsquo;0\u0026rsquo;에 가까운 값을 갖는다는 가설을 뒷받침합니다. 즉, 각 층이 신호를 크게 바꾸기보다는 조금씩만 수정한다는 의미입니다. 또한 ResNet-20, 56, 110을 비교해보면, 네트워크가 깊어질수록 각 층의 응답값이 더 작아지는 경향을 보입니다. 더 많은 층이 협력하여 신호를 조금씩 점진적으로 바꾼다는 것을 시사합니다. 객체 탐지(Object Detection) 실험 ResNet은 단순히 이미지를 분류하는 것을 넘어, 이미지 속 특정 물체의 위치를 찾아내는 객체 탐지 과제에서도 뛰어난 성능을 보였습니다. 아래 표들은 기존의 VGG-16 네트워크를 ResNet-101로 교체했을 때의 성능 향상을 보여줍니다. 특히 어려운 COCO 데이터셋에서 mAP(객체 탐지 성능의 주요 척도)가 28%나 상대적으로 향상되었습니다. 이는 ResNet이 학습한 표현(representation) 자체가 매우 우수하다는 것을 증명합니다.\n결론 성능 저하 (Degradation) 문제 정의 및 해결: 이전까지는 명확하게 설명되지 않았던, 네트워크가 깊어질수록 훈련이 더 어려워지는 문제를 \u0026lsquo;성능 저하\u0026rsquo;로 명확히 정의하고, 이를 \u0026lsquo;잔차 학습(Residual Learning)\u0026lsquo;이라는 혁신적인 아이디어로 해결했습니다. 초심층 신경망 (Extremely Deep Network)의 가능성 제시: \u0026lsquo;지름길 연결(Shortcut Connection)\u0026lsquo;이라는 간단하면서도 강력한 구조를 통해 152층, 나아가 1000층이 넘는 매우 깊은 신경망의 훈련을 가능하게 했습니다. 이는 딥러닝 모델의 깊이에 대한 기존의 한계를 완전히 무너뜨린 것입니다. 다양한 분야에서의 SOTA (State-of-the-art) 달성: 제안된 ResNet은 이미지 분류뿐만 아니라 객체 탐지, 분할 등 다양한 컴퓨터 비전 분야에서 압도적인 성능을 보여주며 새로운 표준 모델로 자리 잡았습니다. FYI ResNet을 구현한 좋은 예시 링크가 있어서 가져와봤습니다!\nhttps://github.com/JayPatwardhan/ResNet-PyTorch\n","permalink":"https://mookjsi.github.io/posts/paper-review-resnet/","summary":"YBIGTA 09/16 DS Session Presentation","title":"ResNet - 더 깊은 신경망을 위한 잔차 학습"},{"content":"\nSlide 1: Title Slide Title: Advanced Policy Gradient Methods: TRPO \u0026amp; PPO Session: YBIGTA SUMMER SESSION Presenter: DS 26 Jungmook Kang Date: 2025.08.26 Slide 2-5: Why does Reinforcement Learning sometimes fail? Main Question: \u0026ldquo;Why does reinforcement learning sometimes break down?\u0026rdquo; Problem: Basic policy gradient methods (like A2C) have limitations. Making drastic changes to the policy—the agent\u0026rsquo;s decision-making criteria—can cause significant problems. Key Issues: Unstable Learning: If an update step is too large and in the wrong direction, the agent\u0026rsquo;s performance can collapse, making recovery impossible. This is more damaging than in supervised learning because a bad policy affects the distribution of states and rewards the agent will see in the future. Changing Data Distribution: As the policy changes, the data (states, actions, rewards) it collects also changes. This non-stationarity of the input data makes learning difficult. Example Analogy: A robot learning to walk. If it\u0026rsquo;s walking well and tries a new strategy by swinging its legs too wide, it will fall. Once it has fallen, it can no longer collect useful data about walking, and learning stops. Slide 6-8: What is TRPO? \u0026ldquo;Let\u0026rsquo;s not change the policy too much!\u0026rdquo; Concept: Trust Region Policy Optimization (TRPO). Core Idea: When updating the policy, TRPO establishes a \u0026ldquo;trust region\u0026rdquo; or a \u0026ldquo;safe zone\u0026rdquo; to ensure the new policy does not stray too far from the old one. Goal: \u0026ldquo;Maximize policy performance under the constraint that the difference (distance) between the old and new policies does not exceed a certain value, δ.\u0026rdquo; This prevents the destructive, large policy updates that can lead to performance collapse. Slide 9-11: The Mathematical Expression of TRPO This slide introduces the core optimization problem of TRPO. The goal is to maximize an objective function, subject to a constraint.\nObjective Function (What to Maximize): The expression $\\mathbb{E}[\\frac{\\pi_{\\theta}(a|s)}{\\pi_{\\theta_{old}}(a|s)}\\hat{A}]$ represents the expected advantage of the new policy $\\pi_{\\theta}$ relative to the old policy $\\pi_{\\theta_{old}}$. This is a surrogate objective that uses importance sampling to estimate the performance of the new policy using data collected from the old one. The term $\\frac{\\pi_{\\theta}(a|s)}{\\pi_{\\theta_{old}}(a|s)}$ is the importance sampling ratio. The full objective function is: $$ L_{\\theta_{old}}^{IS}(\\theta)=\\hat{\\mathbb{E}}_{t}\\left[\\frac{\\pi_{\\theta}(a_{t}\\mid s_{t})}{\\pi_{\\theta_{old}}(a_{t}\\mid s_{t})}\\hat{A}_{t}\\right] $$ Constraint (The \u0026ldquo;Trust Region\u0026rdquo;): The term $\\mathbb{E}[D_{KL}(\\pi_{\\theta_{old}}||\\pi_{\\theta})]\\le\\delta$ is the constraint that defines the trust region. $D_{KL}$ stands for Kullback-Leibler (KL) Divergence. It\u0026rsquo;s a way to measure the \u0026ldquo;distance\u0026rdquo; or difference between two probability distributions. Here, it measures how much the new policy $\\pi_{\\theta}$ has changed from the old policy $\\pi_{\\theta_{old}}$. By keeping this value less than a small constant $\\delta$, we ensure the policy update is small and stays within a \u0026ldquo;trusted\u0026rdquo; region where the performance estimate is reliable. The full optimization problem solved by TRPO is:\n$$ \\underset{\\theta}{\\text{maximize}} \\quad \\hat{\\mathbb{E}}_{t}\\left[\\frac{\\pi_{\\theta}(a_{t}|s_{t})}{\\pi_{\\theta_{old}}(a_{t}|s_{t})}\\hat{A}_{t}\\right] $$ $$ \\text{subject to} \\quad \\hat{\\mathbb{E}}_{t}\\left[KL\\big(\\pi_{\\theta_{old}}(\\cdot|s_{t}),\\,\\pi_{\\theta}(\\cdot|s_{t})\\big)\\right]\\le\\delta $$ Slide 12: Limitations of TRPO Problem: While TRPO\u0026rsquo;s core idea was groundbreaking for stabilizing RL, it wasn\u0026rsquo;t widely adopted in practice. Major Drawbacks: High Computational Cost: It uses a complex, second-order optimization technique called the \u0026ldquo;conjugate gradient method\u0026rdquo; which is computationally heavy. Difficult to Implement: The algorithm is complex to code and debug. Poor Performance on Certain Tasks: It struggled with tasks involving complex visual inputs (requiring deep CNNs), such as the Atari benchmark. It is also hard to use with architectures that have multiple outputs (e.g., a policy and a value function). Slide 13-14: PPO: The Practical Version of TRPO Concept: Proximal Policy Optimization (PPO). Core Idea: PPO inherits TRPO\u0026rsquo;s philosophy of \u0026ldquo;let\u0026rsquo;s change the policy a little at a time\u0026rdquo; but replaces the complex and strict trust region constraint with a simpler mechanism that is easier to implement and more efficient. How it Improves on TRPO: Instead of using a hard constraint, PPO modifies the objective function to penalize policies that move too far away from the old policy. The most common technique for this is called Clipping. Impact: PPO is now one of the most widely used policy optimization algorithms due to its simplicity, stability, and strong performance. Slide 15-19: PPO\u0026rsquo;s Core Idea: Clipping This section details the PPO-Clip objective function, which is the key to its success.\nPPO-Clip Objective Function: $$ L^{CLIP}(\\theta)=\\hat{\\mathbb{E}}\\left[\\min\\big(r_{t}(\\theta)\\hat{A}_{t},\\ \\operatorname{clip}(r_{t}(\\theta),1-\\epsilon,1+\\epsilon)\\hat{A}_{t}\\big)\\right] $$ Breakdown of Terms:\n$r_{t}(\\theta)=\\frac{\\pi_{\\theta}(a_{t}|s_{t})}{\\pi_{\\theta_{old}}(a_{t}|s_{t})}$: This is the same probability ratio used in TRPO. It indicates whether an action is more or less likely under the new policy compared to the old one. $clip(r_{t}(\\theta),1-\\epsilon,1+\\epsilon)$: This is the clipping mechanism. It forces the probability ratio $r_t(\\theta)$ to stay within a small range, $[1-\\epsilon, 1+\\epsilon]$ (e.g., [0.8, 1.2]). This acts as a safety rail, preventing the ratio from becoming too large or too small. $min(\u0026hellip;)$: The final objective takes the minimum of two values: The original objective ($r_{t}(\\theta)\\hat{A}_{t}$) The clipped objective ($clip(\u0026hellip;)\\hat{A}_{t}$) By taking the minimum, PPO creates a pessimistic, lower-bound estimate of the policy\u0026rsquo;s performance. This effectively puts a cap on the benefit you can get from a single update, which discourages excessively large changes to the policy. Analogy: It\u0026rsquo;s like setting a study plan. No matter how much you enjoy one subject, you cap its study time at \u0026ldquo;a maximum of 3 hours per day.\u0026rdquo; This prevents you from neglecting other subjects and keeps your overall learning balanced and stable.\nSlide 20-21: The Power and Application of PPO Why it\u0026rsquo;s popular: PPO is simple, powerful, and stable, making it the de-facto standard for reinforcement learning. Where is PPO used?: Robotics: Training stable and precise movements. Game Playing: Achieving superhuman performance in complex games. Large Language Models (LLMs): Fine-tuning models like ChatGPT to produce more helpful and safer responses (a process known as Reinforcement Learning from Human Feedback or RLHF). Major Users: Almost all leading AI companies, including OpenAI, DeepMind, Meta, and NVIDIA, use PPO as a core algorithm. ","permalink":"https://mookjsi.github.io/posts/trpoppo/","summary":"YBIGTA 08/25 Summer Session Presentation","title":"Advanced Policy Gradient Methods: TRPO \u0026 PPO"},{"content":"I\u0026rsquo;m sharing my full slide-by-slide review of the paper Promptriever: Instruction-Trained Retrievers, which was presented at ICLR 2025.\nThe paper tackles a big problem in current search models: they often fail to understand complex requests, especially negative ones (like \u0026ldquo;not A, but B\u0026rdquo;). The authors\u0026rsquo; solution is Promptriever, a new model trained with a special dataset that forces it to actually follow instructions.\nThis is my presentation on \u0026ldquo;Promptriever: Instruction-Trained Retrievers,\u0026rdquo; which I put together for the Information Theory and Machine Learning Lab.\nFirst, let\u0026rsquo;s acknowledge the researchers. The lead author is Orion Weller, who is affiliated with Johns Hopkins and Samaya AI. It\u0026rsquo;s also worth noting this work was accepted as a poster at ICLR 2025.\nI want to start with the paper\u0026rsquo;s core claim, which I think is really powerful. The authors state that their new training method is the first to prove that search models can be \u0026ldquo;intelligent, instruction-following partners, not just data finders.\u0026rdquo;\nHere are the other co-authors who contributed to this research.\nI\u0026rsquo;ve structured this review into three parts: Motivation, the Promptriever model, and the Experiments. We\u0026rsquo;ll start with the motivation behind the research.\nSo, how do current search engines \u0026ldquo;think\u0026rdquo;? They mostly use a retriever based on semantic similarity to rank documents. On the surface, this seems fine, but what\u0026rsquo;s the problem?\nThis example makes the problem obvious. Imagine you need a laptop that is not a MacBook and costs under $1000. A standard retriever sees the keywords \u0026ldquo;MacBook\u0026rdquo; and \u0026ldquo;under $1000\u0026rdquo; in an article about the MacBook Air and incorrectly flags it as highly relevant.\nThis leads to a frustrating user experience. You\u0026rsquo;re forced to keep tweaking keywords and filters just to find what you want.\nThis is where Promptriever comes in. It doesn\u0026rsquo;t just use semantic similarity. Instead, it operates on \u0026ldquo;dynamic relevance definitions,\u0026rdquo; which allows for a much more intelligent process.\nLet\u0026rsquo;s look at the same query again, but with Promptriever. It correctly understands the instructions—the core topic, the exclusion of MacBooks, and the price constraint. Because of this, it successfully returns a relevant document about a Dell XPS 13.\nThe key idea here is that Promptriever \u0026ldquo;dynamically adjusts relevance based on your natural language instructions.\u0026rdquo; It\u0026rsquo;s not just matching words; it\u0026rsquo;s understanding commands.\nWe\u0026rsquo;ve seen what it does, which leads to the next question: \u0026ldquo;But how on earth was this made?\u0026rdquo; Let\u0026rsquo;s get into the technical details.\nNow, we\u0026rsquo;ll dive into the second section, where I\u0026rsquo;ll break down the Promptriever model\u0026rsquo;s architecture and training.\nThe architecture is a combination of the LLaMA-2 7B language model and a Bi-encoder.\nThe main technical hurdle they faced is a well-known one: standard fine-tuning for information retrieval often destroys a model\u0026rsquo;s instruction-following ability. So how did they keep the model intelligent?\nThe answer, as they stated in their core message, lies in their \u0026ldquo;novel training data, which makes ignoring commands impossible for correct answers.\u0026rdquo;\nFor context, standard retrieval models are trained on simple (Query, Document) pairs from datasets like MSMARCO.\nPromptriever, however, uses a much richer format: Query + Instruction paired with Synthetic documents. This is what lets them train the model on complex, instruction-based prompts.\nThe most clever part of their training data is the Instruction-Negative. This is a document that\u0026rsquo;s correct for the query alone, but becomes incorrect when the instruction is added. This is what forces the model to pay attention.\nHere’s a perfect example. For the query \u0026ldquo;What is the capital of France?,\u0026rdquo; a general article about Paris is a good result. But if you add the instruction \u0026ldquo;mention its average annual rainfall,\u0026rdquo; that article is now an instruction-negative, and a new document with rainfall data becomes the right answer.\nThrough this process, the model learns that if it ignores the instruction, it will retrieve the wrong results. To get the right answer, it has to carefully read and follow the command.\nThe authors were careful about quality control. They found that about 15% of their generated instructions made the original document irrelevant. For those cases, they used an LLM to generate a new, correct document as a substitute.\nCreating these instruction-negatives was absolutely essential. Without them, the model could have just learned to ignore the instructions and still perform well on the base dataset. The negatives guarantee true instruction-following.\nNow for the final section, \u0026ldquo;Experiments,\u0026rdquo; where we\u0026rsquo;ll look at the results.\nFor a fair comparison, they ran an \u0026ldquo;Apples-to-Apples\u0026rdquo; test against RepLLaMA, using the exact same data and hyperparameters.\nThey used a range of datasets and evaluated performance with metrics like NDCG@10, MRR, and importantly, p-MRR, which is designed to measure sensitivity to instructions.\nThe results were impressive. In short, Promptriever achieved state-of-the-art performance, showed better robustness, and could be improved zero-shot just by prompting.\nThis table gives a detailed breakdown. You can see that Promptriever gets high scores across the board, but it really shines in the p-MRR metric, which confirms its superior instruction-following ability.\nOn the in-domain MSMARCO dataset, the performance was on par with the strong RepLLaMA baseline. This is great because it shows that the model gained its new skills without sacrificing core retrieval performance.\nThis is where it gets interesting. When given a helpful prompt, Promptriever\u0026rsquo;s performance on out-of-domain datasets actually improves, while other models get worse. This proves that it is genuinely \u0026ldquo;promptable.\u0026rdquo;\nThis table looks at the standard deviation of scores across different prompts. Promptriever\u0026rsquo;s lower deviation means its performance is much more stable and consistent, regardless of how the query is phrased.\nThe ablation study confirms it all. The performance gains are a direct result of the instruction-based training with instruction-negatives, not because of other factors like longer queries.\nThe authors also proved their training \u0026ldquo;recipe\u0026rdquo; is general. It works well on other base models like Mistral and Llama 3, not just LLaMA-2. As they put it, \u0026ldquo;A golden recipe doesn\u0026rsquo;t discriminate against ingredients!\u0026rdquo;\nFinally, let\u0026rsquo;s look at the reviewer feedback. When one reviewer claimed the data comparison was unfair, the authors argued that the data generation method is their core contribution. They also clarified that comparing to techniques like query rewriting was out of the paper\u0026rsquo;s scope.\nIn the end, the authors addressed all concerns. They ran the requested statistical tests and added more real-world examples during the rebuttal period, which satisfied the reviewers and got the paper accepted.\n","permalink":"https://mookjsi.github.io/posts/paper-review-promptriever/","summary":"06/12 ITML Lab Meeting","title":"Promptriever - Instruction-Trained Retrievers"},{"content":"This is a foundational paper from NIPS 1994 that introduced an idea that has become highly relevant again in the modern deep learning era: the connection between the geometry of the loss landscape and a model\u0026rsquo;s ability to generalize.\nThe core idea is simple yet powerful: instead of just finding the lowest point of the error function (the minimum), we should actively search for wide, flat regions. A model that corresponds to a flat minimum is less sensitive to small changes in its weights, which often translates to better performance on unseen data.\nThis is the title slide for my presentation on \u0026ldquo;Simplifying neural nets by discovering flat minima,\u0026rdquo; which I prepared for our lab meeting.\nFirst, let\u0026rsquo;s credit the authors: Sepp Hochreiter and Jürgen Schmidhuber. As you can see, this is a fairly old paper, but its insights are timeless and arguably more important than ever given the flood of modern research. The key question is, what can we learn from it today?\nHere are the authors of the paper. This work was originally presented at the NIPS 1994 conference (now known as NeurIPS).\nThis quote from the authors perfectly captures the paper\u0026rsquo;s central thesis: \u0026ldquo;Find wide, not sharp, minima - and your network generalizes for free.\u0026rdquo; It elegantly states that good generalization is a natural consequence of the shape of the solution space we find.\nMy presentation is structured into three main parts: First, the motivation for why we need a new approach. Second, a deeper dive into the core idea of flat minima. And finally, the specific algorithm they developed to find them.\nSo, let\u0026rsquo;s start with the motivation. Why was this research necessary?\nTo understand the paper\u0026rsquo;s contribution, it helps to look at the historical context. In the years leading up to 1994, popular techniques for improving generalization like Weight Decay and Optimal Brain Surgeon were based on making assumptions about the network\u0026rsquo;s weights (so-called \u0026ldquo;priors\u0026rdquo;). This paper marked a shift, arguing that we should focus on the geometry of the error surface rather than imposing assumptions about the weights themselves.\nThis 3D plot illustrates the core concept perfectly. On the right, we see a \u0026ldquo;sharp\u0026rdquo; minimum. While the loss is low at the very bottom, a small perturbation to the weights can cause a dramatic increase in loss. On the left, we have a \u0026ldquo;flat\u0026rdquo; minimum. Here, the loss remains low across a large connected region of the weight space. The hypothesis is that solutions in these flat regions are more robust and generalize better.\nHere\u0026rsquo;s a simple visual analogy. A sharp minimum is like a deep, narrow canyon. It\u0026rsquo;s difficult to land exactly at the bottom, and any small error puts you high up on the canyon walls. A flat minimum is like a wide, open valley. It\u0026rsquo;s much easier to find a good spot, and moving around a little doesn\u0026rsquo;t drastically change your altitude (or your model\u0026rsquo;s error). This robustness is linked to lower model complexity.\nSo, what was wrong with the existing methods? Weight-Decay, for instance, assumes a Gaussian prior and can sometimes shrink important weights too aggressively. Bayesian methods require you to hand-pick a \u0026ldquo;good\u0026rdquo; prior distribution. And methods like Optimal Brain Surgeon, while elegant, were very slow and memory-intensive because they required inverting the full Hessian matrix.\nThe \u0026ldquo;Flat Minima\u0026rdquo; approach offers solutions to these problems. First, it doesn\u0026rsquo;t require any pre-chosen priors; the geometry of the solution space itself defines what a \u0026ldquo;simple\u0026rdquo; model is. Second, it uses a clever computational method that makes it aware of second-order information but keeps the complexity on the same order as standard back-propagation. Finally, this process naturally prunes unnecessary weights, leading to a simpler model.\nNow, let\u0026rsquo;s formalize the problem by defining the tasks and architectures this method applies to.\nThe basic setup is a standard supervised learning problem. We have a set of inputs and outputs, and our training data consists of input-output pairs where the outputs have been perturbed by some noise.\nThe model is a neural network, represented by the function $f_w(x_p)$, which takes an input $x_p$ and produces an output, parameterized by a set of weights $W$. We measure its performance on the training set using the Mean Squared Error (MSE).\nBuilding on that, we can define the set of \u0026ldquo;acceptable\u0026rdquo; solutions. Given a tolerable error level, $E_{tol}$, the acceptable minimum is the entire set of weight vectors w for which the training MSE is less than or equal to this tolerance.\nNow we get to the core of the algorithm\u0026rsquo;s construction. For a given weight vector w, we define a \u0026ldquo;box\u0026rdquo; around it. For each individual weight $w_{ij}$, we find the maximum amount $\\delta$ it can be perturbed before the training error exceeds our tolerance $E_{tol}$. This gives us an interval $\\Delta w_{ij}$ for each weight.\nThese intervals for all the weights combine to form a high-dimensional hyper-cuboid in the weight space. The paper defines the \u0026ldquo;Flat Minima\u0026rdquo; as the volume of this box. The larger the volume, the flatter the minimum, and the more robust the solution.\nSo, how do we actually find these large-volume minima? That brings us to the algorithm itself.\nThe main objective of the algorithm is to maximize the volume of the box in weight space, which is represented as $\\Delta w$. A larger volume signifies a flatter, more desirable minimum.\nThis slide reiterates the goal, explicitly showing the formula for the box volume and reminding us that each edge of the box, $\\Delta w_{ij}$, is defined by how much a weight can change before the error surpasses a set tolerance.\nMaximizing a product of many terms is difficult. A standard trick is to instead minimize the negative logarithm of the value. Here, we shift our objective from maximizing the volume $\\Delta w$ to minimizing $B(w, D_0)$, which is proportional to the negative log of that volume.\nThis new objective function has a nice connection to the Minimum Description Length (MDL) principle. Minimizing this term is equivalent to finding a set of weights that can be described with the fewest number of bits, which corresponds to a simpler model.\nTo build the algorithm, we first need to mathematically define \u0026ldquo;flatness\u0026rdquo;. We start by defining the change in the network\u0026rsquo;s output, $ED(w, \\delta w)$, that results from a small change in weights, $\\delta w$.\nTo make this expression for output change usable, we approximate it using a first-order Taylor expansion. This allows us to express the new output, $o_k(w + \\delta w)$, in terms of the original output and the first derivatives (gradients).\nSubstituting the Taylor expansion back into our definition of output change gives us an approximate formula that depends on the sum of gradients multiplied by the weight changes.\nThis leads to our first flatness condition: for a minimum to be considered flat, the total change in output resulting from a weight perturbation must be less than or equal to some small constant, c. This ensures that small weight changes don\u0026rsquo;t lead to large output changes.\nThe second condition is designed to maximize the volume of our hyper-cuboid. To do this, we want to make the box as \u0026ldquo;spherical\u0026rdquo; as possible by ensuring that perturbations to each weight contribute equally to the total output change.\nHere is a clearer statement of Flatness Condition 2. It sets an equality: the output change caused by perturbing weight $w_{ij}$ should be equal to the output change caused by perturbing any other weight $w_{uv}$.\nBy rearranging the equation from Condition 2, we can express the allowable perturbation for one weight, $|\\delta w_{ij}|$, in terms of the perturbation of another weight and the ratio of their sensitivities (measured by their output gradients).\nThis slide simply presents both flatness conditions together, showing how they combine to define the properties of the solution we are seeking.\nBy solving the system of equations defined by both flatness conditions, we arrive at a final formula for the maximum allowable perturbation for any given weight, $|\\Delta w_{ij}|$. This formula depends on the network\u0026rsquo;s output gradients.\nLet\u0026rsquo;s quickly recap the algorithm\u0026rsquo;s goal. We aim to maximize the box volume $\\Delta w$, which is equivalent to minimizing the MDL cost function $B(w, D_0)$.\nNow that we have a formula for the size of the box edges, $\\Delta w_{ij}$, we can express our cost function $B(w, D_0)$ in terms of the network\u0026rsquo;s derivatives. This slide shows that connection, approximating the log of $\\Delta w_{ij}$ with the log of the derived formula.\nThis slide restates the formula for the size of the perturbation $|\\Delta w_{ij}|$, which is the key result from our derivation using the two flatness conditions.\nPlugging the expression for $\\Delta w_{ij}$ into our cost function $B(w, D_0) = -\\sum \\log \\Delta w_{ij}$ gives us this final, albeit complex-looking, penalty term that we need to minimize. This term explicitly captures the \u0026ldquo;flatness\u0026rdquo; of the minimum.\nThe complete objective function for training is then a combination of two parts: the standard MSE, which ensures the model fits the training data, and our new flatness penalty term, which encourages the model to find a simple, generalizable solution. A hyperparameter $\\lambda$ balances the two.\nTo minimize this objective function using gradient descent, we need to compute its gradient. The gradient of the flatness penalty term involves second-order derivatives of the network\u0026rsquo;s output, which would typically be very expensive to compute.\nHowever, the paper leverages a crucial insight. This complex gradient, which involves second-order information, can be calculated with a computational complexity of $O(W)$—the same as standard backpropagation—using a technique known as the Pearlmutter trick. This makes the entire algorithm practical and efficient.\nTo recap the key advantages: the \u0026ldquo;Flat Minima\u0026rdquo; method is appealing because it uses geometry instead of priors to define simplicity, it\u0026rsquo;s computationally efficient, and it naturally performs network pruning for better generalization.\nThe paper then presents three experiments to prove the effectiveness of the algorithm. These tests cover noisy classification, a recurrent network task, and a real-world regression problem using stock market data.\nIn the first experiment, the task was to classify a 2D point with both label and input noise. The network was trained on a small set of 200 samples and tested on a very large set of 120,000 samples to reliably measure generalization.\nThe results of the first experiment are shown here. This table presents 10 direct comparisons between conventional backprop and the new FMS approach. In every single run, the new method achieves a lower test error and gets significantly closer to the optimal error rate, clearly demonstrating superior generalization.\nThe second experiment used a recurrent neural network for a sequence classification task. The problem was designed to be solvable with just one hidden unit. While backprop failed to prune the redundant second unit, the FMS method successfully suppressed it, demonstrating its automatic model simplification capability.\nThe final experiment tackled a real-world problem: predicting directional changes in the DAX stock index. They used several sets of features, from fundamental economic indicators to technical trading signals.\nThe results from the stock market prediction task were compelling. The FMS method was benchmarked against standard Backprop, Optimal Brain Surgeon (OBS), and Weight Decay. FMS was better across all metrics and feature sets, achieving up to a 63% relative improvement over the best competitor, proving its value on noisy, real-world data.\n","permalink":"https://mookjsi.github.io/posts/paper-review-flatminima/","summary":"05/15 ITML Lab meeting","title":"Simplifying Neural Nets by Discovering Flat Minima"},{"content":"Hello everyone, I\u0026rsquo;m Jungmook Kang at Yonsei University. Today, I\u0026rsquo;m excited to share a review of a fascinating paper that was recently accepted to NeurIPS, which delves into the theoretical underpinnings of the attention mechanism. Let\u0026rsquo;s get started.\nThe title of the paper is \u0026ldquo;Max-Margin Token Selection in Attention Mechanism.\u0026rdquo; This work comes from our lab here at Yonsei University, and it explores the question of why attention works the way it does.\nSo, let\u0026rsquo;s begin with the motivation for this research. What prompted us to look into this?\nWe all know that the attention mechanism is incredibly effective. For a sentence like \u0026ldquo;The pizza came out of the oven and it tasted good!\u0026rdquo;, attention can correctly associate \u0026ldquo;it\u0026rdquo; with \u0026ldquo;pizza.\u0026rdquo; It works remarkably well\u0026hellip; but the story doesn\u0026rsquo;t end there.\nWhen we look at the standard Transformer architecture, which powers models like BERT and GPT, we see a complex system of encoders and decoders with multiple layers of multi-head attention. This raises some fundamental questions: Why is this architecture so successful? And more specifically, what is happening to the model\u0026rsquo;s weights during the optimization process that leads to this success?\nAnalyzing this architecture theoretically is very challenging. The optimization problem is both non-linear, due to functions like Softmax, and non-convex. This makes it extremely difficult to describe the training dynamics with traditional methods.\nTo tackle this, we turn to the concept of \u0026ldquo;Implicit Bias.\u0026rdquo; This is a phenomenon where the optimization algorithm itself—like Gradient Descent—has a preference for a certain type of solution, even when there\u0026rsquo;s no explicit regularization term in the loss function telling it to do so.\nThis leads us to the central question of our research: What is the implicit bias of the attention model? What kind of solution does it naturally favor?\nWe can get a clue from simpler models. It\u0026rsquo;s a known result from Soudry et al. (2018) that when you train a linear model with logistic loss using gradient descent, the solution tends to converge towards the one you\u0026rsquo;d get from a hard-margin Support Vector Machine (SVM). The goal of a hard-margin SVM is to find the hyperplane that maximizes the distance, or margin, to the nearest data points.\nSo, we formed a hypothesis: Could it be that the implicit bias of the much more complex attention model is also related to a hard-margin SVM solution?\nHere\u0026rsquo;s a core idea. We observe that attention has a tendency to focus on a small number of important tokens. We believe the principle guiding this selection is related to maximizing a margin. For instance, to distinguish between a cat and a dog, you might focus on the shape of the \u0026rsquo;ears\u0026rsquo; because that feature provides the clearest separation, the largest \u0026lsquo;margin,\u0026rsquo; between the two classes.\nThis brings us to the first main part of the analysis, where we explore the idea of global and local margin maximization within the attention mechanism.\nTo make the analysis tractable, we start with a simplified Softmax Attention model. The function f(X) takes an input sequence X and computes a final output. The key learnable parameters are p, the query embedding, and W, the key-query weights. In Transformers, p can be thought of as the embedding for the [CLS] token.\nOur training objective is to minimize the empirical risk for a binary classification task. We use a standard setup with input sequences X and labels Y, and a decreasing loss function like logistic loss. The model\u0026rsquo;s prediction f(Xi) is a function of the learnable parameters v, p, and W.\nHere, I\u0026rsquo;ll just quickly go over some of the mathematical notation we use throughout the paper. We use standard conventions for vectors and matrices, and we\u0026rsquo;ll use simplified notations like L(p) to denote the risk when v and W are fixed.\nOur approach involves studying the regularization path, which is the path of the solution p as we increase its allowed norm, R. This path mirrors the trajectory of gradient descent. We analyze a final attention model where the trainable parameters W and p jointly influence the softmax, leading to similar optimization dynamics.\nThis brings us to Lemma 1, which is a crucial simplification. It states that the weight matrix W is effectively a rank-1 matrix and its learning dynamics are completely determined by the vector p. This is very important because it means we can fix W and focus our entire analysis on the optimization of p.\nSo, we can formally define our problem. We are exploring the training risk L(v, p) where the key embeddings Ki are derived from the input Xi. For the analysis, we can even treat Xi and Ki as separate entities.\nTo ensure our proofs hold, we need Assumption A. This is a standard assumption that requires our loss function l to be well-behaved—specifically, it must be strictly decreasing and have a Lipschitz-continuous derivative. Common functions like logistic loss and exponential loss satisfy this condition.\nNow, we introduce the central piece of our theory: a hard-margin SVM problem, which we call ATT-SVM. The goal here is to find a direction p that, for each input sequence, separates one chosen token (k_iαi) from all other tokens (k_it) by a margin of at least 1. We will show that the optimization of softmax attention is effectively trying to solve this problem.\nTo formalize this, we define the score of a token (γ_it) as its contribution to the final correct prediction. The optimal tokens are naturally the ones with the highest scores for each input. The Globally-Optimal Max-Margin (GMM) direction, denoted p^mm*, is then the solution to our ATT-SVM problem when we choose these optimal tokens.\nTheorem 1 is our first main result. It states that the regularization path—the sequence of solutions as we increase the norm R—converges in direction to this GMM solution, p^mm*. In simple terms, as the optimization progresses and the norm of p grows, its direction aligns with the direction that best separates the highest-scoring tokens from the rest.\nTheorem 2 looks at the convergence of gradient descent directly. It says that under our assumptions, the norm of the weight vector p will grow towards infinity during training. Critically, for the simple case of a single training example (n=1), the direction of p converges to the GMM direction. However, for n \u0026gt; 1, it\u0026rsquo;s possible for the optimization to get trapped in a local minimum.\nTo test these theorems, we designed a simple experiment. We created synthetic data with three tokens, where we can visualize their key embeddings in 2D and independently control their scores using a third dimension. This lets us clearly see what\u0026rsquo;s happening.\nThese plots show the results. In Figure (a), where the conditions for global convergence are met, we see that all gradient descent trajectories (the grey arrows) correctly converge to the GMM direction (the red dashed line). In (b), we\u0026rsquo;ve changed the scores so that a locally optimal solution exists, and we see some trajectories get stuck there instead. Figure (c) shows the more complex scenario with multiple inputs, where finding the joint GMM solution is harder.\nThis brings us to the idea of locally-optimal tokens. These are tokens that might not be the highest-scoring ones globally, but they form a stable solution for the ATT-SVM problem. The direction associated with them is a locally-optimal max-margin (LMM) direction.\nTo talk about local convergence, we introduce the geometric concept of a cone. A cone around a direction q is simply the set of all vectors that are \u0026ldquo;close\u0026rdquo; in angle to q. The diagram illustrates an initialization p(0) that lies within the cone of an LMM direction p^mm.\nTheorem 3 formalizes local convergence. It states that if you initialize the gradient descent p(0) within the cone of an LMM direction, the optimization will stay within that cone and ultimately converge to that specific LMM direction.\nLooking back at our experiment in Figure (b), we can now understand it better through Theorem 3. The trajectories that don\u0026rsquo;t find the global optimum are the ones that were initialized inside the cone of the locally-optimal solution (the blue square), and as the theorem predicts, they converge to it.\nTheorem 4 provides a tightness guarantee. It essentially says that the LMM directions are the only stable convergence points. If you start in any direction q that is not an LMM direction, the optimization path will eventually move away from q.\nThis diagram illustrates Theorem 4. If our initial parameter p(0) is in a cone (the grey one) that does not contain any LMM or GMM direction, the optimization process will not converge in that direction. It is implicitly forced to seek out one of the valid max-margin solutions.\nTo summarize the first half: we\u0026rsquo;ve shown that when training only the attention parameter p, the implicit bias of gradient descent drives the solution towards a hard-margin SVM that separates tokens. Now, what happens if we also learn the prediction head v at the same time?\nThis leads to the second part of our analysis: the joint convergence of the prediction head v and the attention weights p.\nThe high-level intuition is that the model is linear in v, so the optimization with respect to v also has an implicit bias towards a standard max-margin classifier solution. The features for this classifier, x_i^p, are the outputs of the attention layer.\nThe challenge here is that the features r that v sees are determined by p, which itself is changing during training. This creates a coupled dynamic. We analyze this by separating the problem into cases based on whether the selected features are support vectors for the v-classifier or not.\nTheorem 5 addresses the case where we assume the selected tokens are all support vectors. We introduce Assumption C, which formalizes that if the attention doesn\u0026rsquo;t perfectly select the optimal token, the classification margin for v shrinks. Under this assumption, we find that v converges to the direction of a standard SVM solution, and p converges to the direction of our ATT-SVM solution.\nThis raises a natural question: Does every selected token really need to be a support vector, sitting right on the margin? That seems like a very strict condition. Intuitively, for the data points that are not support vectors, we don\u0026rsquo;t need to maximize their margin. We just need to make sure they are on the correct side of the decision boundary. This allows us to define a \u0026ldquo;relaxed\u0026rdquo; version of our ATT-SVM problem.\nTheorem 6 presents this more general result. The ATT-SVM problem is relaxed: for tokens corresponding to support vectors (i ∈ S), we require a margin of 1, but for non-support vectors (i ∈ S-bar), we only require a margin of 0 (correct classification). We only need Assumption C to hold for the support vectors. The result is that v still converges to the max-margin v^mm, and p converges to the solution of this new, relaxed SVM problem, p^relax.\nWe ran experiments for this joint convergence case as well. The plots show the trajectories for the attention weights p and the classifier head v. Plot (a) shows a case aligning with Theorem 5, where all inputs are support vectors. Plot (b) shows a case for Theorem 6, where one input is not a support vector. Plot (c) shows that the softmax probability for the optimal token quickly goes to 1, confirming that the attention is learning to select specific tokens as predicted.\nSo, to summarize the entire theoretical part: Whether we train the attention weights p alone or jointly with the classifier head v, the implicit bias of the optimization consistently pushes the model towards a hard-margin SVM solution. This provides a strong theoretical explanation for why attention learns to become sparse and focus on the most discriminative tokens.\nFinally, let\u0026rsquo;s look at a few more experiments to see these principles in action on more complex tasks.\nThis slide provides an experimental comparison between Normalized Gradient Descent (GD) and Vanilla GD, validating the paper\u0026rsquo;s theory. Plot (a) shows that while both methods learn to focus on a single token (softmax probability approaches 1.0), Normalized GD achieves this sparse attention much faster. Plot (b) demonstrates a key theoretical prediction: the norm of the attention weights ||p|| diverges (grows linearly without bound) when using Normalized GD. This behavior is characteristic of an optimization process seeking a max-margin solution.\nHere, we trained a vision transformer on an image classification task. Figure 7 shows that as training progresses over epochs, the sparsity of the attention map increases (red curve goes down), meaning the model learns to focus on fewer, more important image patches. At the same time, the norm of the attention weights ||W|| steadily increases (blue curve), which is exactly what our theory predicts will happen as the solution converges towards an infinite-norm, max-margin boundary. The images in Figure 6 visually show this focusing effect over time.\nThis final experiment shows how the choice of loss function affects the dynamics. We compare a correlation loss (l(x) = -x) with the logistic loss. The gradient\u0026rsquo;s magnitude depends on the token\u0026rsquo;s score γ differently for each loss. For correlation loss, larger scores get larger gradients, while for logistic loss, the gradient is largest for scores near zero. This results in different trajectories, but as you can see, both are ultimately guided by the same underlying max-margin principle, pushing towards a separating hyperplane.\n","permalink":"https://mookjsi.github.io/posts/paper-review-maxtoken/","summary":"04/30 ITML Lab Meeting","title":"Max-Margin Token Selection in Attention Mechanism"},{"content":"\nSlide 1: Preface 2025년 4월 1일 YBIGTA DS Session에서 발표한 Transformer 자료입니다. Attention의 직관부터 계산 과정, Transformer의 Encoder–Decoder 구조, BERT의 문맥 표현과 활용까지 순서대로 살펴봅니다.\nSlide 2: What is Attention? Attention은 현재 처리하는 정보와 관련성이 높은 입력에 더 큰 가중치를 주어 정보를 모으는 연산입니다. 먼저 Query, Key, Value의 역할을 직관적으로 이해합니다.\nSlide 3: Transformer 전체 구조 전체 구조를 한 번에 외우기보다 Embedding, Positional Encoding, Attention, 잔차 연결을 나누어 살펴봅니다. 이후 각 구성 요소가 Encoder와 Decoder 안에서 어떻게 연결되는지 확인합니다.\nSlide 4: Query, Key, Value **Query(Q)**는 무엇을 찾는지, **Key(K)**는 각 후보를 비교할 특징, **Value(V)**는 실제로 가져올 정보입니다. 소개팅 비유에서 이상형의 기준은 Query, 상대의 소개는 Key, 실제로 종합할 특성은 Value에 해당합니다.\nSlide 5: Scaled Dot-Product Attention Query와 Key의 내적으로 관련도를 계산하고, Key의 차원 $d_k$의 제곱근으로 나눈 뒤 Softmax를 적용합니다. 마지막으로 Value를 가중합합니다.\n$$ \\operatorname{Attention}(Q,K,V)=\\operatorname{softmax}\\left(\\frac{QK^\\top}{\\sqrt{d_k}}\\right)V. $$ Softmax는 각 Query에 대응하는 Key 방향으로 적용합니다. 출력은 후보 하나를 선택한 값이 아니라 Value들의 가중합입니다.\nSlide 6: Attention의 직관적 예시 슬라이드의 후보별 점수는 관련도가 높은 대상에 더 큰 비중이 배정되는 과정을 보여줍니다. 다만 실제 Attention은 가장 큰 점수를 받은 후보만 고르는 것이 아니라, 모든 Value에 가중치를 곱해 더합니다.\nSlide 7: Attention Step-by-Step 이제 번역 예시를 통해 Attention 계산을 단계별로 따라갑니다. 이 부분의 그림은 발표 자료에 명시된 24-1 Transformer Session 자료(Wooseok Seo) 및 StatQuest YouTube Channel을 참고합니다.\nSlide 8: 기존 LSTM의 정보 병목 기본적인 Encoder–Decoder LSTM은 입력 문장을 고정된 크기의 상태로 요약해 Decoder에 전달합니다. 문장이 길어지면 앞부분의 세부 정보를 충분히 보존하기 어려워질 수 있습니다.\nSlide 9: Attention으로 입력을 다시 참조하기 Attention은 Decoder가 출력 단어를 만들 때 Encoder의 여러 위치를 직접 참조할 수 있게 합니다. 하나의 최종 상태에만 의존하던 정보 전달 경로를 확장합니다.\nSlide 10: 번역 예시 “Let’s go”를 “vamos”로 번역하는 예시입니다. Decoder는 시작 신호를 받아 첫 출력 단어를 예측하며, 이때 입력의 어느 부분에 주목할지 계산합니다. 그림의 시작·종료 토큰 표기는 설명용 예시를 따릅니다.\nSlide 11: Attention 계산 흐름 Encoder의 상태와 현재 Decoder 상태를 비교하고, 비교 점수를 정규화한 뒤 입력 정보를 가중합합니다. 이 결과가 다음 단어의 예측을 돕습니다.\nSlide 12: Similarity 현재 Decoder 상태를 각 Encoder 상태와 비교합니다. 입력 위치마다 하나의 관련도 점수가 만들어집니다.\nSlide 13: Dot Product 두 벡터의 내적은 대응하는 성분을 곱한 뒤 더한 값입니다. 그림은 Encoder 상태와 Decoder 상태 사이의 유사도를 내적으로 계산하는 과정을 보여줍니다.\nSlide 14: Softmax 관련도 점수에 Softmax를 적용하면 양수이면서 합이 1인 가중치를 얻습니다. 점수가 큰 입력 위치일수록 더 큰 비중을 받습니다.\nSlide 15: 가중합으로 Context 만들기 정규화된 가중치를 각 Encoder 상태에 곱한 뒤 더합니다. 이렇게 얻은 Context는 현재 출력 단어를 예측할 때 필요한 입력 정보를 요약합니다.\nSlide 16: Fully Connected Layer Attention으로 얻은 Context와 Decoder의 정보를 출력층으로 전달합니다. 출력층의 점수에 Softmax를 적용하면 어휘 집합의 각 단어에 대한 확률분포를 얻습니다.\nSlide 17: 출력과 종료 예측한 토큰을 다음 단계의 입력으로 사용하며 생성을 이어 갑니다. 종료 토큰을 예측하면 번역을 마칩니다.\nSlide 18: Transformer Step-by-Step 이제 순환 구조 대신 Attention을 중심으로 구성한 Transformer를 살펴봅니다. 이 부분 역시 발표 자료에 표시된 Wooseok Seo의 Session 자료와 StatQuest 그림을 바탕으로 설명합니다.\nSlide 19: Transformer Overview Encoder는 입력 문장의 표현을 만들고, Decoder는 이미 주어진 출력 토큰과 Encoder의 정보를 참고해 다음 토큰을 예측합니다. 그림은 계산 흐름을 보여주기 위한 단순화된 구조입니다.\nSlide 20: Word Embedding 각 토큰을 학습 가능한 실수 벡터로 변환합니다. One-hot 벡터에 Embedding 행렬을 곱하는 것은 해당 토큰에 대응하는 행 또는 열을 선택하는 것과 같습니다.\nSlide 21: Positional Encoding의 필요성 순수한 Self-Attention 연산만으로는 토큰의 위치를 구분할 수 없습니다. 따라서 토큰 표현에 순서 정보를 더해 “누가 무엇을 했는지”를 구별할 수 있도록 합니다.\nSlide 22: 사인·코사인 위치 인코딩 원래 Transformer는 서로 다른 주파수의 사인·코사인 함수를 이용해 위치 벡터를 구성합니다. 각 위치는 Embedding과 같은 차원의 위치 표현을 갖습니다.\nSlide 23: 첫 번째 위치의 표현 첫 번째 토큰의 위치에 해당하는 함수값들을 모아 위치 벡터를 만듭니다. 벡터의 각 성분은 서로 다른 주파수의 함수에서 얻습니다.\nSlide 24: 두 번째 위치의 표현 두 번째 토큰에는 두 번째 위치의 함수값들을 사용합니다. 같은 단어라도 위치가 달라지면 더해지는 위치 벡터가 달라집니다.\nSlide 25: 세 번째 위치의 표현 세 번째 토큰도 같은 규칙으로 위치 벡터를 얻습니다. 모든 위치에 동일한 함수 체계를 적용하되, 위치 좌표가 달라집니다.\nSlide 26: Embedding과 위치 정보의 합 단어 Embedding과 Positional Encoding을 성분별로 더합니다. 이 합이 Attention에 입력되어 단어의 내용과 위치 정보를 함께 전달합니다.\nSlide 27: 단어 순서가 달라질 때 “Squatch eats pizza”와 “Pizza eats Squatch”는 같은 단어를 포함해도 의미가 다릅니다. 각 단어에 결합하는 위치 벡터가 달라지므로 입력 표현도 달라집니다.\nSlide 28: 번역 예시의 위치 인코딩 다시 “Let’s go” 예시로 돌아와 위치 벡터를 구성합니다. 그림의 작은 차원은 계산을 보여주기 위한 예시입니다.\nSlide 29: Attention에 들어갈 입력 각 토큰의 Embedding에 위치 정보를 더한 결과를 얻었습니다. 다음 단계에서는 이 표현을 선형 변환해 Query, Key, Value를 만듭니다.\nSlide 30: Self-Attention Self-Attention은 같은 시퀀스의 토큰들이 서로를 참조하는 연산입니다. 문장 속 “it”이 무엇을 가리키는지 이해하려면 다른 단어와의 관계가 필요합니다.\nSlide 31: 문맥 속 단어 관계 “The pizza came out of the oven and it tasted good”에서 “it”은 “oven”보다 “pizza”와 의미적으로 연결됩니다. Attention은 이런 관계를 학습 가능한 가중치로 표현할 수 있습니다.\nSlide 32: Query 생성 각 토큰 표현에 Query용 선형 변환을 적용합니다. Query는 해당 토큰이 다른 위치에서 어떤 정보를 찾을지를 결정하는 벡터입니다.\nSlide 33: Key 생성 같은 입력 표현에 별도의 Key용 선형 변환을 적용합니다. Query와 Key는 서로 다른 역할을 수행하므로 일반적으로 서로 다른 가중치 행렬을 사용합니다.\nSlide 34: Query–Key 점수 한 토큰의 Query와 모든 토큰의 Key 사이의 내적을 계산합니다. 원래 Scaled Dot-Product Attention에서는 이 값을 $\\sqrt{d_k}$로 나누어 점수의 규모를 조절합니다.\nSlide 35: Attention 가중치 점수에 Softmax를 적용해 현재 Query가 각 입력 위치를 얼마나 참고할지 결정합니다. Encoder의 Self-Attention에서는 일반적으로 입력의 앞뒤 위치를 모두 볼 수 있습니다.\nSlide 36: Value 가중합 Value용 선형 변환으로 얻은 벡터들에 Attention 가중치를 곱해 더합니다. 이 가중합이 해당 Query 위치의 Attention 출력입니다.\nSlide 37: 다른 토큰의 Attention 다른 토큰도 자신의 Query로 같은 과정을 수행합니다. Key와 Value를 토큰마다 별도의 모형으로 새로 만드는 것이 아니라, 공유된 변환을 각 토큰에 적용합니다.\nSlide 38: 병렬 계산 모든 위치의 Query, Key, Value를 행렬로 모으면 Attention을 행렬 연산으로 계산할 수 있습니다. 순환 신경망과 달리 Encoder의 각 위치를 순서대로 처리할 필요가 없습니다.\nSlide 39: Residual Connection Attention의 출력에 입력 표현을 더하는 잔차 연결을 사용합니다. 원래 Transformer에는 정규화와 위치별 Feed-Forward Network도 포함되며, 이 그림은 흐름을 단순화한 것입니다.\nSlide 40: Encoder 계산 정리 Word Embedding → Positional Encoding → Self-Attention → 잔차 연결의 흐름을 정리합니다. 실제 Encoder 블록은 Multi-Head Attention, Add \u0026amp; Norm, Feed-Forward Network를 포함하고 여러 층으로 쌓입니다.\nSlide 41: Decoder로 이동 Encoder가 입력 문장을 표현했다면, Decoder는 출력 문장을 생성합니다. 그림의 왼쪽은 입력 언어, 오른쪽은 출력 언어의 토큰을 처리합니다.\nSlide 42: Encoder와 Decoder의 차이 Decoder도 Embedding과 Attention을 사용하지만 원래 Transformer에서 Encoder와 완전히 같지는 않습니다. 미래 토큰을 가리는 Masked Self-Attention과 Encoder–Decoder Attention이 추가적인 핵심입니다.\nSlide 43: Decoder Embedding 출력 측의 시작 토큰이나 이전 토큰을 Embedding으로 변환합니다. 그 표현에 위치 정보를 더해 Decoder의 입력을 만듭니다.\nSlide 44: Decoder Self-Attention Decoder의 Query·Key·Value 변환은 Encoder와 별도로 학습됩니다. 자기회귀 학습에서는 현재 위치가 미래의 정답 토큰을 보지 않도록 Causal Mask를 적용합니다.\nSlide 45: Encoder–Decoder Attention Cross-Attention은 Decoder가 Encoder의 출력을 참고하는 단계입니다. 생성 중인 출력 문장과 입력 문장을 연결합니다.\nSlide 46: Cross-Attention의 Query와 Key Query는 Decoder의 표현에서, Key와 Value는 Encoder의 출력에서 만들어집니다. 현재 생성하려는 토큰이 입력 문장의 어느 위치와 관련 있는지 비교합니다.\nSlide 47: 입력 위치별 가중치 Decoder Query와 Encoder Key의 점수를 정규화합니다. 각 입력 위치에 배정된 가중치는 현재 출력 단계에서 참고할 비중을 나타냅니다.\nSlide 48: Encoder 정보의 가중합 Encoder에서 얻은 Value에 가중치를 적용해 Context를 만듭니다. Decoder는 입력 문장에서 필요한 정보를 선택적으로 받아들입니다.\nSlide 49: 세 가지 Attention의 역할 Encoder Self-Attention은 입력 내부 관계, Decoder Self-Attention은 출력의 이전 문맥, Cross-Attention은 입력과 출력 사이의 관계를 처리합니다. 각 모듈은 보통 별도의 가중치를 사용하며, 같은 모듈의 변환은 토큰 위치에 걸쳐 공유됩니다.\nSlide 50: Decoder의 잔차 연결 Cross-Attention의 출력에도 잔차 연결을 적용합니다. 전체 Decoder 블록에서는 정규화와 Feed-Forward Network가 함께 사용됩니다.\nSlide 51: 첫 번째 토큰 예측 Decoder의 최종 표현을 어휘 집합 크기의 점수 벡터로 변환하고 Softmax를 적용합니다. 예시에서는 첫 번역 토큰으로 “vamos”를 얻습니다.\nSlide 52: 다음 생성 단계 이전에 생성한 토큰을 다음 단계의 문맥에 포함합니다. 학습 시 정답의 이전 토큰을 주는 Teacher Forcing과 실제 추론 시 생성한 토큰을 사용하는 과정은 구분해야 합니다.\nSlide 53: 종료 토큰 예측 다음 토큰이 종료 토큰이면 생성을 멈춥니다. 실제 추론에서는 탐욕적 선택, Beam Search, 샘플링 등 목적에 맞는 생성 전략을 사용할 수 있습니다.\nSlide 54: Encoder–Decoder 전체 흐름 입력 표현 생성, 출력 문맥 처리, 입력 참조, 다음 토큰 예측이 하나의 흐름으로 연결됩니다. 학습에서는 마스킹을 통해 여러 출력 위치를 병렬 계산할 수 있지만, 자기회귀 추론은 토큰을 순차 생성합니다.\nSlide 55: Encoder-Only Transformer: BERT 마지막 부분에서는 Encoder만 사용하는 BERT를 살펴봅니다. 이 부분의 그림은 발표 자료에 명시된 StatQuest YouTube Channel을 참고합니다.\nSlide 56: Encoder–Decoder Transformer 원래 Transformer는 번역처럼 입력 시퀀스를 받아 출력 시퀀스를 만드는 과제를 위해 제안되었습니다. Encoder와 Decoder가 서로 다른 역할을 맡습니다.\nSlide 57: Decoder-Only Transformer: GPT GPT 계열의 기본 구조는 Causal Self-Attention을 사용하는 Decoder-only Transformer입니다. 원래 Encoder–Decoder의 Decoder에서 Encoder를 참조하는 Cross-Attention 없이 이전 토큰들을 바탕으로 다음 토큰을 예측합니다.\nSlide 58: Encoder-Only Transformer BERT는 양방향 문맥을 참고하는 Encoder 기반 모형입니다. 대표적인 사전학습 목표는 가려진 토큰을 복원하는 Masked Language Modeling이며, 토큰마다 문맥을 반영한 표현을 만듭니다.\nSlide 59: 문맥 표현이 필요한 이유 단순한 단어별 Embedding만으로는 같은 단어가 문맥에 따라 달라지는 의미를 충분히 표현하기 어렵습니다. BERT는 주변 단어를 함께 처리하여 이를 보완합니다.\nSlide 60: 단어 Embedding의 의미 “great”와 “awesome”처럼 유사한 단어의 관계는 학습을 통해 표현에 반영되어야 합니다. 그림의 숫자는 직관을 위한 예시이며, 실제 의미 관계는 다차원 벡터 공간에서 다룹니다.\nSlide 61: 주변 단어 예측으로 학습하기 주변 단어를 예측하는 목적함수를 이용하면 단어 벡터에도 통계적인 문맥 정보가 반영됩니다. 자주 비슷한 환경에서 등장하는 단어들의 표현을 학습할 수 있습니다.\nSlide 62: 유사한 문맥의 단어 “Pizza is great”와 “Pizza is awesome”처럼 비슷한 문맥에 등장하는 표현은 유사성을 학습할 단서를 제공합니다. 특정 확률값은 슬라이드의 설명용 예시입니다.\nSlide 63: 여러 단어를 문맥으로 사용하기 하나의 단어가 아니라 여러 단어를 함께 사용하면 예측에 활용할 정보가 늘어납니다. 다만 문맥을 어떻게 결합하는지가 중요합니다.\nSlide 64: 순서와 관계 정보의 한계 슬라이드의 단순한 문맥 결합 방식은 단어 순서와 세밀한 관계를 충분히 반영하지 못합니다. 이는 모든 기존 Embedding 방법에 대한 일반적 한계가 아니라, 여기서 비교하는 단순화된 모형의 한계입니다.\nSlide 65: BERT의 문맥 기반 표현 BERT는 위치 정보와 양방향 Self-Attention을 이용해 각 토큰의 문맥 표현을 만듭니다. 단순히 문장 전체를 한 벡터로 압축하는 모형이라기보다, 먼저 토큰별 표현을 출력하는 Encoder입니다.\nSlide 66: 같은 단어, 다른 의미 “Pizza is great!”와 “My cellphone’s broken, great.”의 “great”는 서로 다른 문맥에 놓여 있습니다. BERT는 주변 문장을 참고해 두 위치에 서로 다른 표현을 부여할 수 있습니다.\nSlide 67: Word Embedding과 BERT 비교 고정된 단어 Embedding은 같은 토큰에 같은 벡터를 부여하지만, BERT의 출력은 문맥에 따라 달라집니다. 문장 표현이 필요할 때는 목적에 맞는 Pooling이나 추가 학습을 적용합니다.\nSlide 68: 문장 유사도 유사한 의미의 문장을 가까운 표현으로 배치하면 의미 기반 비교에 활용할 수 있습니다. 다만 일반 BERT의 출력만으로 좋은 문장 유사도가 자동 보장되는 것은 아니며, 문장 임베딩 학습이 도움이 됩니다.\nSlide 69: 문서 표현과 검색 문서도 표현 벡터로 변환하여 유사도를 비교하거나 군집화할 수 있습니다. 긴 문서는 길이 제한을 고려해 나누고, 과제에 맞는 표현과 유사도 함수를 선택해야 합니다.\nSlide 70: RAG Retrieval RAG는 질문과 관련된 문서를 검색해 생성 모형의 입력에 제공하는 구조입니다. BERT 계열 Encoder를 기반으로 검색에 맞게 학습한 임베딩 모형을 Retrieval에 사용할 수 있습니다.\nSlide 71: 감정 분류와 마무리 문맥 표현 위에 분류기를 추가하면 긍정·부정 같은 감정 분류를 수행할 수 있습니다. 이 발표의 핵심은 Attention의 가중합 → Transformer의 정보 흐름 → 문맥을 반영한 표현의 활용으로 이어집니다.\n","permalink":"https://mookjsi.github.io/posts/transformer/","summary":"YBIGTA 04/01 DS Session Presentation. Attention, Transformer, and BERT step-by-step.","title":"Transformer: Attention부터 BERT까지"},{"content":"This is my detailed slide-by-slide analysis of the paper Stochastic Approximation to Contrastive Learning, which was submitted to the ICLR 2025 conference.\nThe paper tackles a critical challenge in contrastive learning: its heavy reliance on large batch sizes and the associated computational cost. The authors introduce SACLR, a novel framework inspired by Stochastic Cluster Embedding (SCE) that reformulates the objective using I-divergence. The goal was to enable efficient training with as little as one negative sample, a significant departure from methods like SimCLR.\nWhile the premise is compelling, the paper faced substantial criticism during the open review process regarding its experimental comparisons, novelty, and the substantiation of its claims. Despite rebuttals and additional experiments, it was ultimately rejected. In this review, I\u0026rsquo;ll walk through the method as presented and layer in the context from the public reviews to provide a complete picture of its strengths and weaknesses.\nThis is the title slide for my review of the paper \u0026ldquo;Stochastic Approximation to Contrastive Learning.\u0026rdquo; This presentation was prepared for the Information Theory and Machine Learning Lab at Yonsei University.\nTo begin, I\u0026rsquo;ll recap the core concept of Representation Learning. This field is all about how we represent data, which leads to the fundamental question: what exactly is a \u0026ldquo;representation\u0026rdquo; in the context of machine learning?\nI\u0026rsquo;ll illustrate this with a simple task. Imagine you need to solve the division problem CCV / VI. For most people, this is not immediately obvious.\nNow, consider this problem: 210 / 6. This is likely much easier, and you can quickly determine the answer is 35. The interesting part is that both problems represent the exact same calculation.\nThe key difference lies in the representation of the same numerical information. The first task used Roman numerals, while the second used Arabic numerals. The choice of representation dramatically changes the difficulty of the task.\nThis analogy illustrates a critical point that is central to representation learning: the right representation can make a complex task much easier to solve.\nTo summarize this introductory point: the difficulty of many information processing tasks is highly dependent on how that information is represented.\nSo, the crucial question for us is: how can we obtain a \u0026ldquo;good representation\u0026rdquo; for various machine learning tasks? Today, I\u0026rsquo;ll focus on one prominent approach for achieving this: Self-Supervised Learning.\nSelf-Supervised Learning is a subset of the broader field of Representation Learning.\nA primary motivation for the development of self-supervised methods is the immense cost and effort required to obtain large-scale labeled datasets for traditional supervised learning.\nThe solution that Self-Supervised Learning proposes is to find a way to learn a \u0026ldquo;good representation\u0026rdquo; that captures the essential features of the data using only an unlabeled dataset.\nThis slide illustrates the typical self-supervised learning pipeline. First, a model is trained on a \u0026ldquo;pretext task\u0026rdquo; using a large amount of unlabeled data. The learned model is then transferred and fine-tuned on a \u0026ldquo;downstream task\u0026rdquo; using task-specific (and often limited) labeled data.\nThe goal of the pre-training stage is to transform raw data, which can be a poor representation for a computer (like a raw image of a dog), into a feature vector that is a much better representation for downstream tasks.\nThe central question this paper investigates is the pre-training step: how exactly does the model learn a good representation from unlabeled data?\nWithin the realm of Self-Supervised Learning, I will now narrow the focus to Contrastive Learning. This approach is based on making \u0026ldquo;inter-sample\u0026rdquo; predictions.\nHere is the core mechanic of contrastive learning. We start with an \u0026ldquo;anchor\u0026rdquo; image. We create two different augmented versions, or \u0026ldquo;views,\u0026rdquo; of this anchor, which form a \u0026ldquo;positive pair.\u0026rdquo; We then contrast this with a \u0026ldquo;negative pair,\u0026rdquo; which is formed by the anchor and a view from a completely different image.\nIn summary, the objective of contrastive learning is to learn effective representations by mapping similar data points close to each other in the representation space, while simultaneously pushing dissimilar data points far apart.\nThis slide outlines the flow of the main arguments in this review. I\u0026rsquo;ll begin by discussing the high computational costs that arise from the conventional definition of positive and negative pairs. Then, I will introduce the paper\u0026rsquo;s proposed method, which uses matrix approximation with I-divergence to create a decomposable and stochastic loss, ultimately achieving competitive results with a low batch size and fewer negative pairs.\nNow, we move from the recap to the main introduction of the paper\u0026rsquo;s contribution.\nThe core problem is that while supervised learning is effective, it depends on having extensive labeled data. Self-Supervised Learning is the alternative we are exploring.\nHowever, popular contrastive learning methods like SimCLR require very large batch sizes to ensure a sufficient balance of positive and negative examples. This expends a large amount of computational resources, particularly on the negative pairs. A method called Sog-CLR attempted to address this by mixing an EMA of image similarities into the denominator of the InfoNCE loss.\nTo be more specific, SimCLR\u0026rsquo;s InfoNCE loss operates in a full-batch mode, which is not decomposable in a mini-batch setting. Sog-CLR showed improvement by incorporating a running average for the negative pair estimations.\nThis paper poses the question: even with Sog-CLR\u0026rsquo;s improvements, is there still room for further optimization? It introduces SACLR, a method that uses I-divergence to reformulate the objective into a matrix approximation problem that is decomposable across instance pairs.\nThe key idea behind SACLR is this reformulation using I-divergence, which allows the objective to be decomposed and approximated stochastically. This is presented as an advancement over Sog-CLR\u0026rsquo;s EMA mixing approach.\nThe paper\u0026rsquo;s central claim is that its method, SACLR, can learn high-quality representations with a small batch size and very few negative pairs. While reviewers found the core idea of tackling the large batch size problem to be an interesting and valuable contribution, and saw the novel formulation inspired by Stochastic Cluster Embedding as a strength, they heavily scrutinized the experimental evidence supporting these claims.\nTo understand SACLR, we first need to look at its theoretical foundation: Stochastic Cluster Embedding (SCE). I will now detail the matrix approximation with I-divergence that underpins the method.\nIn SCE, we have embedded data points, like $y_i$ and $y_j$. We define a similarity kernel $q_{ij}$ between these points in the embedded space, typically using a Gaussian or a Student\u0026rsquo;s t-distribution kernel. This value should be close to 1 for similar points.\nWe also define a target similarity matrix, P, which represents the desired similarities in the embedded space. For example, perfectly clustered data would have a block-diagonal P matrix.\nThe goal is to make the learned similarity matrix Q as close as possible to our desirable target matrix P. The question is, how do we measure this closeness?\nThis is where the choice of divergence metric is crucial. t-SNE uses the KL-divergence. In contrast, SCE uses the I-divergence, which includes an additional scaling factor \u0026rsquo;s\u0026rsquo; and linear terms.\nThis slide highlights the formulas for both KL-divergence, used in t-SNE, and the I-divergence with a scaling factor, used in SCE.\nAn important property is that the I-divergence can reduce to the KL-divergence. This happens if the scaling factor \u0026rsquo;s\u0026rsquo; is set to be the inverse of the sum of all kernel similarities, effectively normalizing the Q matrix.\nSCE defines the scaling factor \u0026rsquo;s\u0026rsquo; using a weighted sum controlled by the parameter α, which introduces additional repulsion to improve cluster quality. A key methodological point, raised by Reviewer C43T, was why \u0026rsquo;s\u0026rsquo; is treated as a constant during optimization when it is a function of the embeddings. The authors clarified that they use an interleaving optimization strategy: the model parameters are optimized while \u0026rsquo;s\u0026rsquo; is fixed, and then \u0026rsquo;s\u0026rsquo; is periodically updated based on the new embeddings.\nBy plugging this definition of the weights $w_{ij}$ into the formula for \u0026rsquo;s\u0026rsquo;, the denominator term can be rewritten as a sum of two expectations.\nThese two expectations have clear interpretations: $E_1$ is the expected similarity for pairs drawn from the target distribution P, while $E_2$ is the expected similarity for pairs drawn uniformly at random from all possible pairs.\nThis formulation allows the I-divergence objective to be rewritten in a stochastic form, separating it into an attraction term based on the target distribution and a repulsion term based on the uniform distribution. The terms themselves are simple functions of the similarity $q_{ij}$.\nNow, let\u0026rsquo;s apply this SCE framework to Contrastive Learning. In our setting, for each input $x_i$, we generate two augmented views, $\\tilde{x}{i}^{(1)}$ and $\\tilde{x}{i}^{(2)}$. We denote their embeddings as $\\tilde{y}{i}^{(u)}$ and the similarity between any two embeddings as $q{ij}^{(u,v)}$.\nThe goal in contrastive learning is to make embeddings from the same instance ($i=j$) similar, and embeddings from different instances ($i \\ne j$) dissimilar. We can formally define this as a target tensor $p$, where the target similarity is 1 only for positive pairs ($p_{ii}^{(1,2)}$ and $p_{ii}^{(2,1)}$) and 0 for all other pairs.\nThis slide provides a concrete example of the target tensor $P$ for a case with N=3 instances. The matrices for same-view similarities ($P^{(1,1)}, P^{(2,2)}$) are all zeros, while the matrices for cross-view similarities ($P^{(1,2)}, P^{(2,1)}$) are identity matrices, capturing the positive pair targets.\nTo simplify the math, we can flatten this four-dimensional tensor structure into standard 2D matrices. The $2N \\times 2N$ target matrix $\\psi$ is formed by reorganizing the elements of the tensor $p$. This results in a sparse matrix where the identity matrices from the tensor become off-diagonal blocks.\nFor notational simplicity, we neglect the diagonal elements of the matrices $\\psi$ and $\\phi$ in the approximation, as they are constant for the kernels used and do not affect the optimization.\nNow we apply the SCE I-divergence formula, but to our new flattened matrices $\\psi$ and $\\phi$ which represent the contrastive learning problem.\nApplying the I-divergence $D_{I}(\\psi||s\\phi)$ and using the specific structure of our target matrix $\\psi$ (which is mostly zeros), the loss function simplifies significantly. The scaling factor $s$ is updated periodically, with its weights $w_{ij}^{u,v}$ also adapted for the contrastive case.\nThe full loss function $\\mathcal{L}{CLR}(\\theta)$ can be expressed as an expectation over the data indices. This form consists of a term for positive pairs ($log~q{ii}^{1,2}$) and a repulsion term involving a sum of similarities over all pairs.\nTo make this computationally feasible, we use a Monte Carlo approximation. This gives us the final SACLR objective, $\\mathcal{L}{SACLR}(\\theta)$, which is calculated over a mini-batch $\\mathcal{B}$ and a set of M negative samples $\\mathcal{M}{i}$. The paper studies two variants: SACLR-1 (M=1) and SACLR-all (M=B).\nThe scaling factor $s$ is also estimated stochastically. Its inverse, $s^{-1}$, is approximated using samples from the mini-batch, and this estimate is updated smoothly using an exponential moving average (EMA) after each batch.\nThe paper also explores a row-wise decomposition of the matrix approximation. Instead of one global scaling factor \u0026rsquo;s\u0026rsquo;, each row \u0026lsquo;a\u0026rsquo; of the similarity matrix gets its own scaling factor $s_a$. This results in the loss function $\\mathcal{L}_{CLR-row}(\\theta)$.\nThis slide provides proof for the simplified row-wise SACLR loss function. By substituting the sparse target matrix $\\psi$ into the general I-divergence formula and summing over all rows, we arrive at the expression shown.\nA key theoretical finding presented in the paper is that under specific conditions, the SACLR-row objective becomes equivalent to the SimCLR loss. This link, however, became a point of discussion during the review. Reviewer gz9D argued that this equivalence doesn\u0026rsquo;t explain why SACLR should be expected to outperform SimCLR. The authors countered that the method\u0026rsquo;s advantage comes not from this specific condition, but from using a different, more flexible weighting scheme for the scaling factor.\nHere is the proof of Theorem 3.1. By substituting the condition for the scaling factors into the loss function, the repulsion term simplifies to a constant, and the remaining terms can be rearranged to form precisely the SimCLR objective.\nJust as with the full matrix version, the row-wise loss can be approximated stochastically for mini-batch training. This gives us the $\\mathcal{L}_{SACLR-row}(\\theta)$ objective.\nSimilarly, the row-wise scaling factors $s_{2(i-1)+u}$ are estimated stochastically within each mini-batch and updated using an EMA rule.\nThis diagram provides a summary of the theoretical framework I have just presented. We started with the concept of I-divergence and a scaling factor, which we used to build a matrix approximation. This was then decomposed row-wise, and both versions were made practical via stochastic approximation. Now, it\u0026rsquo;s time to see the experimental results.\nThis slide presents the full pseudocode for the SACLR algorithm. A major point of contention in the initial review was that the paper claimed to be \u0026ldquo;more computationally efficient\u0026rdquo; without providing empirical data on runtime or memory. The detailed ablation studies on computational cost, shown later in the presentation, were added during the rebuttal period as a direct response to this criticism from the reviewers.\nNow we move to the experiments section. The standard evaluation protocol for self-supervised methods is used: first, a model is pre-trained without labels on a dataset like ImageNet or CIFAR. The learned weights from this backbone are then used to initialize a new network, a linear layer is added, and this new network is trained with labels to perform a classification task.\nTable 1 shows the Top-1 linear classification accuracies on ImageNet. While SACLR-ALL is shown to be competitive with some methods like MoCo v2, this comparison drew significant criticism during the review process. The Area Chair and multiple reviewers stated that the baseline methods used for comparison were \u0026ldquo;weak\u0026rdquo; and the performance gains \u0026ldquo;marginal,\u0026rdquo; noting that many stronger, more recent methods were omitted.\nThis table shows results for longer training, with SACLR-MIX surpassing SimCLR and SogCLR in this setup. However, reviewers found this comparison inadequate as well. Reviewer gz9D pointed out that results for top-performing methods like VICReg and Barlow Twins from other benchmark papers were significantly higher. The authors argued their goal was primarily efficiency without heavy tuning, but this did not overcome the concerns about the weak comparison set.\nThis experiment in Table 3 specifically investigates performance when using only a single negative sample (M=1) per image. SACLR-1 achieves a Top-1 accuracy of 65.3%, significantly outperforming classical contrastive losses like Triplet and Logistic loss under the same constraint.\nThis table evaluates semi-supervised learning performance, showing SACLR\u0026rsquo;s strength in data-limited regimes. It is worth noting that the initial submission focused almost exclusively on linear evaluation. Reviewers Tx4K and gz9D strongly recommended including more comprehensive evaluations like semi-supervised fine-tuning to provide a more complete picture, and the additional kNN and fine-tuning results were added to the paper in response.\nThe learned representations are also evaluated on transfer learning classification tasks. As shown in Table 5, the representations learned by SACLR-ALL and SACLR-MIX transfer very well to other datasets like VOC07 and especially iNaturalist18, where they significantly outperform SimCLR and MoCo v2.\nTable 6 shows transfer learning results on more complex downstream tasks: object detection and segmentation on VOC and COCO. Across all metrics, the SACLR variants are highly competitive and often outperform strong baselines like SimCLR, BYOL, and MoCo v2, with SACLR-MIX showing the strongest results overall.\nThis table provides a direct comparison with other stochastic estimation-based contrastive methods, using an architecture similar to the iSog-CLR paper for a fair comparison. The results on CIFAR10, CIFAR100, and ImageNet100 show that both the matrix and row versions of SACLR are highly competitive, often achieving the best or second-best performance in this specific class of methods.\nThis slide presents several ablation studies on computational complexity and robustness. These experiments were largely added in response to direct reviewer feedback. Reviewers requested empirical data on runtime and memory to substantiate the paper\u0026rsquo;s efficiency claims, as well as a study on the impact of batch size to support the claim that SACLR performs well in small-batch settings. These tables represent the authors\u0026rsquo; attempt to provide that missing evidence.\n","permalink":"https://mookjsi.github.io/posts/paper-review-stochastic/","summary":"ICLR 2025 Paper Review","title":"Stochastic Approximation to Contrastive Learning"},{"content":"This is a detailed slide-by-slide review of the paper When to Retrieve?, which was submitted to ACL 2024 but was ultimately rejected.\nThe paper questions the efficiency of the standard Retrieval-Augmented Generation (RAG) framework, which naively performs retrieval for every query. The authors propose an adaptive retrieval model (RET indicator) that dynamically decides, for each query, whether external knowledge retrieval is necessary. If the LLM\u0026rsquo;s parametric memory is sufficient, retrieval is skipped; otherwise, external information is fetched.\nThis is the title slide for my presentation on the paper \u0026ldquo;When to Retrieve?\u0026rdquo;, which I delivered at the Yonsei University Machine Learning Lab on February 28, 2025.\nTo set the stage, I\u0026rsquo;m introducing a real-world application I developed, \u0026ldquo;momugo,\u0026rdquo; a restaurant recommendation app. This slide shows the user input screen, where a user is asking for a recommendation for a quiet place to talk with a friend while enjoying soju and hot fish cake soup.\nThis slide demonstrates the detailed output of the \u0026ldquo;momugo\u0026rdquo; app. When a user clicks on a recommended restaurant, it displays more information, including relevant review snippets that match the user\u0026rsquo;s query, providing a justification for the recommendation.\nHere, I\u0026rsquo;m breaking down the initial data filtering process in my application. The system first performs a primary filtering based on structured data like category and business hours. Then, it moves to a more detailed secondary filtering based on the specifics of the user\u0026rsquo;s natural language query.\nThis slide illustrates the core retrieval and generation pipeline. After the initial filtering, the user\u0026rsquo;s query is used to find the top 10 most similar review embeddings from a vector database. The top 3 restaurants are then selected, and an LLM generates a descriptive recommendation reason for each.\nI\u0026rsquo;m detailing the \u0026ldquo;Detailed Filtering\u0026rdquo; step. An LLM is prompted with a system message to analyze the user\u0026rsquo;s query and extract specific requirements, such as \u0026ldquo;corkage available\u0026rdquo; or \u0026ldquo;pet-friendly,\u0026rdquo; into a structured JSON format.\nThis slide provides a high-level overview, separating the entire process into two main phases: Retrieval and Generation. The retrieval part finds the most relevant restaurants, and the generation part creates the user-facing explanation.\nI\u0026rsquo;m explaining the embedding process for the retrieval phase. The descriptions and latest reviews for each restaurant are converted into a 1536-dimensional vector using OpenAI\u0026rsquo;s text-embedding-3-small model and stored in a Pinecone vector database.\nThis slide details the retrieval mechanism. We embed all reviews and the user\u0026rsquo;s query. Using LangChain, we retrieve the top 10 review vectors based on cosine similarity. Finally, we determine the top 3 restaurants by calculating the average vector similarity for each.\nThis slide outlines the generation phase. The top 3 restaurants identified during retrieval, along with their metadata and the original user query, are used to create three separate prompts for the LLM.\nI\u0026rsquo;m showcasing the prompt engineering aspect for the generation phase. A structured prompt, including a system message and a human message with the query and restaurant context, is fed to the LLM to generate a tailored recommendation reason for each of the top 3 restaurants.\nThis slide concludes the overview of my application\u0026rsquo;s architecture. It shows how the generated recommendation reasons (from the LLM) and the filtered restaurant data are combined to produce the final, detailed output card shown to the user.\nShifting from my personal project to the main topic, this slide introduces the standard Retrieval-Augmented Generation (RAG) process, breaking it down into the \u0026lsquo;Retrieval\u0026rsquo; and \u0026lsquo;Generation\u0026rsquo; stages.\nHere, I pose a critical question about the standard RAG framework: Is the naive approach of always retrieving information for every query the most effective or efficient method?\nThis slide frames the core problem investigated in the paper. I\u0026rsquo;m questioning the fundamental assumption of RAG: \u0026ldquo;Should we always retrieve, regardless of the query?\u0026rdquo; This sets the stage for a more nuanced approach.\nI\u0026rsquo;m introducing the central concept of the paper: an adaptive retrieval model. The key idea is to use an indicator, which the authors call \u0026ldquo;RET,\u0026rdquo; to decide whether to retrieve external information or to answer directly from the LLM\u0026rsquo;s parametric memory.\nNow that we\u0026rsquo;ve established the need for a decision mechanism, the key research question becomes: \u0026ldquo;Where to place a RET?\u0026rdquo; In other words, how does the model learn when it\u0026rsquo;s appropriate to trigger the retrieval step?\nThis slide presents the core hypothesis of the paper. The authors believe that retrieval is unnecessary for \u0026ldquo;popular entities\u0026rdquo; (information likely stored in the LLM\u0026rsquo;s parameters) but crucial for \u0026ldquo;non-popular entities.\u0026rdquo;\nBuilding on the hypothesis, I\u0026rsquo;m highlighting the practical challenge: How can a model quantitatively identify if an entity is \u0026ldquo;popular\u0026rdquo;? The paper proposes a model that can learn this distinction to enhance the efficiency and accuracy of the RAG process.\nThis slide formally introduces the paper I\u0026rsquo;m reviewing: \u0026ldquo;When to Retrieve: Teaching LLMs to Utilize Information Retrieval Effectively\u0026rdquo; by Labruna, Campos, and Azkune. They name their proposed model \u0026ldquo;ADAPT-LLM.\u0026rdquo;\nI\u0026rsquo;m providing context with related works. This slide contrasts \u0026ldquo;Closed-book QA,\u0026rdquo; which relies solely on an LLM\u0026rsquo;s internal knowledge, with \u0026ldquo;Open-book QA,\u0026rdquo; which always uses an external information retrieval system.\nThis slide summarizes key issues in the field and their corresponding solutions. It covers the high cost of retraining models, the lexical gap in keyword-based retrieval, and the latency costs associated with retrieval, positioning an adaptive approach as a solution.\nContinuing with the related works, this slide discusses the problem of tool overuse in models like Toolformer and the unrealistic nature of previous popularity-based retrieval methods. It positions ADAPT-LLM as a solution that provides a robust baseline for comparison.\nHere, I\u0026rsquo;m outlining the four-step process of the ADAPT-LLM framework: 1) A query is sent to the model. 2) The model decides whether to retrieve or not. 3) If needed, it retrieves information. 4) It generates the final answer.\nThis slide focuses on the critical decision-making step. The central question is how the model determines whether to retrieve information. The paper\u0026rsquo;s answer is to fine-tune the LLM on a specially curated dataset to learn this behavior.\nI\u0026rsquo;m illustrating the data preparation process for fine-tuning ADAPT-LLM. The process starts with QA data, which is fed to a base LLM. The model\u0026rsquo;s answers are classified as correct or incorrect, which then informs the creation of different types of training prompts.\nThis slide provides a concrete example of the data preparation pipeline. Using a QA pair about the capital of South Korea, I show how the query is extracted from the source data.\nContinuing the example, this slide shows the base LLM generating both a correct answer (\u0026ldquo;Seoul\u0026rdquo;) and an incorrect answer (\u0026ldquo;Busan\u0026rdquo;) to the query, which is a crucial step for creating the fine-tuning dataset.\nThis slide details how the fine-tuning dataset, named DS_adapt, is constructed. Based on the LLM\u0026rsquo;s correctness, three types of prompts are generated: a direct answer for correct parametric knowledge, a \u0026lt;RET\u0026gt; token for incorrect answers, and a context-based prompt for incorrect answers.\nThis slide visualizes the final step of the model creation process. The DS_adapt dataset, with its varied prompt structures, is used to fine-tune a base LLM, resulting in the final ADAPT-LLM.\nI\u0026rsquo;m presenting the headline results from the paper. The table shows that ADAPT-LLM, trained on both NQ and SQuAD datasets, outperforms both the NEVER RETRIEVE (NR-LLM) and ALWAYS RETRIEVE (AR-LLM) baselines in terms of accuracy on the PopQA test set.\nThis slide outlines the structure of the experiments section of my review. I will cover three key areas: comparison to baselines, the model\u0026rsquo;s ability to determine when context is needed, and a comparison with the state-of-the-art approach for the PopQA dataset.\nI\u0026rsquo;m beginning the detailed experimental setup. This slide specifies the training datasets used for the fine-tuning process: Natural Questions (NQ) and Stanford Question Answering Dataset (SQuAD).\nThis slide specifies the base Large Language Model used in the experiments. The authors chose the Llama-2-7B model as the foundation for their fine-tuning.\nHere, I specify the dataset used for evaluating the models at test time. All configurations are evaluated on the PopQA dataset, which is designed to test knowledge of popular entities.\nI\u0026rsquo;m explaining how the baseline models are created for comparison. The NR-LLM (NEVER RETRIEVE) is fine-tuned only on prompts that require direct, parametric answers.\nSimilarly, this slide explains the creation of the AR-LLM (ALWAYS RETRIEVE) baseline. This model is fine-tuned exclusively on prompts that include retrieved context, forcing it to always rely on external information.\nThis slide recaps the training process for the main model, ADAPT-LLM. It is trained on the comprehensive DS_adapt dataset, which includes a mix of parametric, retrieval-triggering, and context-aware prompts.\nI\u0026rsquo;m presenting the main results table again, this time to emphasize the direct performance comparison. ADAPT-LLM consistently achieves the highest accuracy, demonstrating the effectiveness of its selective retrieval strategy.\nTo provide more context on the datasets, this slide presents a table comparing the statistics of NQ, SQuAD, and PopQA, including the number of questions and the average length of questions and answers.\nNow, I\u0026rsquo;m moving to the second part of the experimental analysis: evaluating ADAPT-LLM\u0026rsquo;s ability to correctly decide when to retrieve. This slide sets up the analysis of the model\u0026rsquo;s decision-making accuracy.\nThis slide presents a detailed breakdown of ADAPT-LLM\u0026rsquo;s performance. It analyzes the accuracy of the model in four scenarios: when it correctly decides to retrieve (and is given context), when it incorrectly decides not to retrieve (and isn\u0026rsquo;t given context), and so on.\nI\u0026rsquo;m highlighting a key observation from the results table. The accuracy for questions where the model chose to retrieve (Acc. w/ context for (RET)) seems quite low, around 33%. This prompts a deeper investigation.\nThis slide provides an explanation for the previously noted low accuracy. The authors point out that the performance of the underlying Information Retrieval (IR) system itself was a limiting factor.\nTo support the claim about poor IR performance, this slide presents results from Table 4 of the paper. It shows a massive accuracy gap when using the gold standard passages versus passages retrieved by the Contriever system, confirming the IR bottleneck.\nDespite the issues with the IR component, this slide shows that the model\u0026rsquo;s decision-making process is sound. The histograms show a clear inverse correlation between entity popularity and the usage of the \u0026lt;RET\u0026gt; token, confirming the model learned the core hypothesis.\nI\u0026rsquo;m now moving to the final experimental comparison: ADAPT-LLM versus the previous state-of-the-art method for the PopQA dataset. This slide visually contrasts the two approaches, highlighting differences in training data and thresholding methods.\nThis slide presents the results of the state-of-the-art comparison. While the accuracy is comparable, I\u0026rsquo;m highlighting the authors\u0026rsquo; claims that ADAPT-LLM is a more generalizable and efficient approach due to its lower reliance on the IR system and its independence from dataset-specific features like popularity scores.\nTo begin the conclusion, I\u0026rsquo;m bringing back the diagram illustrating the creation of the DS_adapt fine-tuning dataset. This serves as a reminder of the core technical contribution of the paper.\nThis slide recaps the fine-tuning process itself, showing how the diverse set of prompts from DS_adapt is used to train the base LLM into the final, adaptive ADAPT-LLM.\nIn my final slide, I\u0026rsquo;m summarizing the key takeaways from the paper. The experiments demonstrate that ADAPT-LLM is a robust model that successfully learns when to retrieve information, outperforming standard baselines and showing strong potential as a general, efficient approach to adaptive RAG.\n","permalink":"https://mookjsi.github.io/posts/paper-review-whentoretrieve/","summary":"ACL 2024 Paper Review","title":"When to Retrieve?"},{"content":"Education Seoul National University, Seoul, Korea (Mar 2026 -)\nM.S in Statistics Yonsei University, Seoul, Korea (Mar 2022 - Feb 2026)\nB.A in Applied Statistics Research Interests Machine Learning High Dimensional Data Analysis ","permalink":"https://mookjsi.github.io/about/","summary":"\u003ch2 id=\"education\"\u003eEducation\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003eSeoul National University\u003c/strong\u003e, Seoul, Korea (Mar 2026 -)\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eM.S in Statistics\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003eYonsei University\u003c/strong\u003e, Seoul, Korea (Mar 2022 - Feb 2026)\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eB.A in Applied Statistics\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003chr\u003e\n\u003ch2 id=\"research-interests\"\u003eResearch Interests\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eMachine Learning\u003c/li\u003e\n\u003cli\u003eHigh Dimensional Data Analysis\u003c/li\u003e\n\u003c/ul\u003e","title":"About Me"}]