<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Asriel Han on Medium]]></title>
        <description><![CDATA[Stories by Asriel Han on Medium]]></description>
        <link>https://medium.com/@asrielhan?source=rss-efefa7748079------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jtTRg8W-7K3_FLY41PE5lQ.png</url>
            <title>Stories by Asriel Han on Medium</title>
            <link>https://medium.com/@asrielhan?source=rss-efefa7748079------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:44:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asrielhan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unveiling the Secrets of Denoising in Diffusion Models — Part One]]></title>
            <link>https://medium.com/@asrielhan/unveiling-the-secrets-of-denoising-in-diffusion-models-part-one-821d66a663f9?source=rss-efefa7748079------2</link>
            <guid isPermaLink="false">https://medium.com/p/821d66a663f9</guid>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[denoising]]></category>
            <category><![CDATA[ai-image-generator]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[ai-art]]></category>
            <dc:creator><![CDATA[Asriel Han]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 19:37:01 GMT</pubDate>
            <atom:updated>2024-01-17T23:06:01.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unveiling the Secrets of Denoising in Diffusion Models</h3><p>In the fascinating intersection of creativity and technology lies the world of AI-generated imagery. If you’ve ventured into this article, you might be thinking, “I’ve navigated the realms of stable diffusion, producing numerous AI-generated pieces. I’m familiar with platforms like HuggingFace APIs or ComfyUI. Do I really need to explore another tutorial on diffusion models?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*64GMs-VPxJBMJ-8GKHg2aw.png" /><figcaption>You’ve likely encountered this graph a thousand times, yet still don’t know what’s inside the grey box</figcaption></figure><p>Pause for a moment. This isn’t just another standard guide. Our journey together goes beyond merely telling you which parameters to use or avoid. My objective is to empower you with a deep understanding of the principles and mechanics underlying this complex machine. With this knowledge, you can harness it to achieve your unique creative objectives.</p><p>Let’s embark on a journey to demystify the complexities of diffusion models, unraveling step by step the magic that transforms mere numbers into breathtaking AI art. Our first destination is the core of the diffusion model: <strong>the denoising process</strong>. This process is the essence of how diffusion models conjure high-fidelity images seemingly out of nothing. But what exactly happens during this process? How long does it take, and why does the time vary for different images? Through the lens of an AI-generated artwork, this article will guide you through the intricacies of the diffusion process, offering insights into its transformative capabilities.</p><h3><strong>The Art of Denoising: More Than Meets the Eye</strong></h3><p>At its core, the denoising process in diffusion models is like an art restorer meticulously removing layers of grime to reveal a masterpiece beneath. It begins with a text prompt, or a text-image pair, and gradually eliminates noise, transforming a blank, noisy canvas into a vivid, new image. It’s akin to slowly lifting a veil to unveil the hidden artwork beneath.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*KuejfyJa2ts566nl5D6rLA.gif" /><figcaption>An animation of the denoising process within the Stable Diffusion model</figcaption></figure><p>Yet, this straightforward explanation often leads to more head-scratching than clarity. You might wonder, “If the starting point is merely a text prompt, what ‘noisy image’ is the model even working on?” Or perhaps, “How many steps does the model take to achieve this feat? Can it be infinite?” And then there are the curiosities about noise reduction itself: How much noise does each step erase? What about tasks like image-to-image translation or inpainting — can the model continue its ‘cleaning spree’ on an already clean image?</p><p>To answer these questions and more, it’s essential to dive deeper into the intricacies of the denoising mechanism within diffusion models. It’s not just about wiping away noise; it’s about understanding the choreography of each step in this delicate dance of image creation.</p><h3><strong>The Clockwork of Creativity: </strong>The Rhythmic Timesteps of Diffusion Models</h3><p>Embarking on our exploration, it’s imperative to first understand a key concept at the heart of the denoising process: timesteps. A timestep represents a “state” of an image during the timeline of denoising and image generation. Early-stage, higher-value timesteps showcase the raw, unrefined noise, akin to an orchestra warming up before a symphony. Conversely, lower-value timesteps represent the final bars of the composition, where the image emerges in its full glory, almost ready for the grand finale. Based on this framework, the denoising process essentially involves the image-in-progress transitioning from one timestep to the next, and then to the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQ2g6OuydugNma5mLkjJuQ.png" /><figcaption>A display of the sample image with its 1,000 timesteps</figcaption></figure><p>The total number of timesteps is a variable, but it is typically configured to be 1,000 in most widely-used Stable Diffusion models. This segmentation turns the transformation process into a gallery of 1,000 unique ‘frames’, each capturing a moment of the image’s evolution from chaos to clarity. Imagine taking a real-world image or an output from the diffusion model and being able to project it back to any chosen timestep ‘t’ using a straightforward function f(I, t), where ‘I’ represents the original image and ‘t’ the selected timestep. In reverse, for any given image at a certain timestep ‘t’, the model plays the role of a skilled artist, predicting and crafting a less noisy version, striving to revert it back to its original, pristine state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZEsw5DY4EzQeAdJX2bEqQ.png" /><figcaption>An in-depth examination of the distinction between two successive timestep images reveals that the difference is quite subtle. You can observe that the earlier timestep image exhibits slightly more grainy noise over the head of the horse.</figcaption></figure><h3>Training the Artist: The Art of Teaching AI to Remove Noise</h3><p>Now that we have a grasp of timesteps, we can delve into comprehending the training and inference process of the diffusion model. Let’s begin with training since the procedure for transitioning timesteps during training is simpler compared to inference. Furthermore, all the established diffusion fine-tuning techniques, such as lora or dreambooth, employ the same training methodology. Familiarizing yourself with this process will boost your confidence in your future lora-related endeavors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1cT6bypF0Pjjjl_Ey3a9A.png" /><figcaption>Illustration of the training procedure for a diffusion model</figcaption></figure><h4><strong>The Initiation — Selecting a Canvas:</strong></h4><p>Image we have a vast library of (image, prompt) pairs. During each training iteration, the model selects one pair. This image serves as the canvas upon which the model will learn the nuances of adding and removing noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*PwN1ARth_A6D11scPigXLg.png" /><figcaption>Step one: Randomly choose pairs of (image, prompt) from the training dataset</figcaption></figure><h4>Choosing the Timestep:</h4><p>Next, the model randomly picks a timestep ‘t’ from its range. This timestep is crucial as it determines the degree of noise to be added to the image. Imagine taking a clear image and deliberately shrouding it in a veil of obscurity, representative of a specific stage in the noise addition journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77zE8YqyWo6xBxq4CH81qw.png" /><figcaption>Step two: Select a random timestep for each image and introduce noise into the training image</figcaption></figure><h4>Predictive Denoising:</h4><p>Now, we arrive at a pivotal aspect of the training process. At this stage, the model simultaneously examines the noisy image and the specified timestep ‘t.’ It endeavors to forecast the precise noise that was introduced, aiming to reverse the image to its initial state by subtracting the predicted noise. This process occurs in a single step, with the model directly transitioning the noisy image at timestep ‘t’ back to its original form, bypassing intermediate timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04eAVuXYGKMqAFohPWpTEg.png" /><figcaption>Step three: The diffusion model performs a one-step denoising process to predict the clean image from a noisy image at various timesteps</figcaption></figure><h4>Learning Through Comparison:</h4><p>The true learning for the model takes place during this phase. It evaluates its predicted image against the original image, and the closer the model’s prediction aligns with the original image, the more effectively it has learned. This comparison imparts to the model the ability to undo the noise-introduction process at any specified timestep, which forms the core principle of denoising.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdRmpnRsI_gFBhAL8KHWVA.png" /><figcaption>Step four: Calculate the loss function by comparing the training image to the predicted image</figcaption></figure><p>By iteratively performing these actions on various images and timesteps, the model progressively develops into a denoising expert. It’s akin to training an artist to initially identify the brushstrokes that mar a painting and then skillfully restore it to its original splendor.</p><h3>Denoising Process in Text-to-Image Inference: Navigating the Steps of Creation</h3><p>In the world of text-to-image inference, the denoising process takes a more elaborate and intricate path. Unlike the training phase, inference is a multi-stage journey, where the image evolves progressively from one timestep to the next, rather than leaping directly to its final state.</p><p>This discrepancy naturally raises further inquiries, such as whether we are required to traverse all 1,000 timesteps. If not, how do we determine which timestep to transition to next? This entails the incorporation of an additional parameter, referred to as “<strong>inference steps</strong>,” or sometimes known as ‘<strong>num_inference_steps</strong>’ in huggingface, which assumes a pivotal role in determining how the model progresses from noise to a coherent image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ky_4MROS1s-eezZ4MJ5p_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mU9D6TsXeY2TARTY8uTz6g.png" /><figcaption>The relationship between timesteps and inference steps is interconnected. Various values for inference steps will impact the striding window, consequently affecting the selection of timesteps.</figcaption></figure><p>This newly introduced parameter plays a pivotal role in shaping the model’s navigation through the timesteps during the inference process. Essentially, it governs the granularity of the denoising steps. When we specify <strong>num_inference_steps</strong> as a particular value <strong>m</strong>, it results in the division of the total number of timesteps, denoted as <strong>N</strong>, by <strong>m</strong>, yielding a stride value denoted as <strong>s = N/m</strong>. This stride value holds significance as it aids in the selection of a subset of timesteps from the complete range. These chosen timesteps are spaced apart by this stride value, forming a sequence that can be expressed as:</p><p><strong><em>[0, s, 2*s, … , (num_inference_steps — 1) * s, num_inference_steps * s]</em></strong></p><p><strong>Starting point:</strong> The denoising procedure initiates at the highest strided timestep, precisely at ‘num_inference_steps * s,’ where the model transforms a randomized noisy image into its most heavily affected noise state. Guided by both the provided text prompt and the current timestep value, the model proceeds to make predictions for denoising at this noise level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaKy8mHPnyFWl9QT4DO_bg.jpeg" /><figcaption>illustration of denoising process during inference.</figcaption></figure><p><strong>Iterative Denoising and Noise Introduction:</strong> Once the denoising prediction has been generated, and the corresponding predicted clean image is formed at the current timestep. This image, along with the current noisy state and the targeted next timestep, guides the model to predict the image at the next lower timestep. Since we don’t yet know the true ‘clean’ image in text-to-image tasks, we use the predicted clean image as a stand-in. This iterative dance of denoising and noise reintroduction gradually refines the image, step by meticulous step.</p><p>The model continues its elegant descent through the timesteps, each step bringing the image into sharper focus and closer alignment with the text prompt. Finally, at timestep 0, the performance reaches its climax. The model unveils a coherent, detailed image, a grand transformation from the initial randomness to a visual narrative inspired by the text.</p><h3>Denoising in image-to-image</h3><p>Having completed the denoising phase in the text-to-image conversion journey, we are now extending our exploration into various aspects of diffusion models. Our focus will be on the denoising mechanism employed in the image-to-image translation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrdclWCFLnHR2XZ7CTT-bg.png" /><figcaption>image-to-image translation process from a blackbox POV</figcaption></figure><p>The denoising process in image-to-image translation shares similarities with the one in text-to-image generation but incorporates several crucial variations owing to the presence of both a text prompt and an image as inputs. These distinctions stem from the distinctive characteristics of the input data and how the model interacts with it.</p><p><strong>Starting Point</strong></p><p>In contrast to the initial state of text-to-image generation, which relies solely on a text prompt as input, image-to-image translation begins with the presence of both a text prompt and a tangible reference image. This reference image serves as the starting point and the canvas that the model will intricately modify. The input image is initially transformed into its noisy state through the function <strong>f(I, t)</strong>, as previously discussed.</p><p>However, there’s a twist: In the text-to-image generation process, we always commence with the largest timestep, ‘<strong>num_inference_steps * s</strong>,’ where the image is transformed into a state that predominantly resembles random noise. But when applied to an image-to-image translation model, a question arises: If we do the same thing to image-to-image translation, how does the reference image contribute to the process, considering that there may be little difference between projecting the reference image at the highest timestep state and projecting a black frame at the highest timestep state?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72k1t_5LIZ1DpOml0MIikQ.png" /><figcaption>When we convert any image to its high timestep state, it can hardly be differentiated from other images</figcaption></figure><p><strong>‘Strength’ — The Key to Transformation<br></strong>The answer is, we don’t. We initiate the denoising process at a midpoint, introducing a new parameter called ‘strength.’ This ‘strength’ parameter, which varies between 0 and 1, determines the starting point along the denoising timeline and governs the intensity of the initial denoising state, calculated as <strong>N//m * (strength * m)</strong>. To illustrate, consider ‘inference_steps’ set at 20, resulting in strides such as [950, 900, …, 0]. The ‘strength’ parameter influences where this denoising process commences. A ‘strength’ value of 1 thrusts the image into the chaos of complete noise <strong>(timestep 950)</strong>, while a value of 0.5 initiates the process at a more moderate noise level <strong>(timestep 450)</strong>, preserving a greater semblance of the original image’s essence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyLBuihmtQVMlWj-LAGIPQ.png" /><figcaption>How the choice of strength value affect the starting point and denoising process of diffusion model</figcaption></figure><p><strong>The iterative process<br></strong>Once the starting point is set by ‘inference_steps’ and ‘strength’, the model embarks on a familiar iterative process of denoising and noise addition, same to text-to-image. The end result of the journey, however, is tailored uniquely by the ‘strength’ parameter, ensuring that different timesteps starting point for the same image transformation is distinct and personalized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_1iDfbYXBciyC5WvJfv2Q.png" /><figcaption>Given the same starting point, how does different prompt affect the image-to-image translation process</figcaption></figure><p><strong>Mastering the Art — Controlling the Transformation<br></strong>Hence, through the manipulation of ‘inference_steps’ and ‘strength,’ we possess the tools to control the extent of transformation. Increasing ‘inference_steps’ while simultaneously reducing ‘strength’ results in a gentle refinement of the image. This approach ensures subtlety and maintains a robust connection to the original while introducing new elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*L6oYINP-4EJyLfBluT_Mog.gif" /><figcaption>Animation of image-to-image denoising process in duffision model</figcaption></figure><p>In the world of image-to-image translation, the denoising process is a delicate balancing act. It’s about honoring the integrity of the original image while ushering it towards a new visual narrative. This process resembles a painter thoughtfully choosing which strokes to highlight and which aspects of the original masterpiece to preserve and enhance.</p><h3>Denoising in inpainting</h3><p>Inpainting, the artistic endeavor of reconstructing missing or compromised parts of an image, occupies a unique niche in the domain of stable diffusion models. While it shares a common framework with image-to-image translation, inpainting introduces a distinct nuance in the denoising process, especially in managing noise between the masked (inpainting-required) and non-masked regions. Let’s unravel this sophisticated tapestry</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t156n27U0sonc7HGjNpuYg.png" /><figcaption>Blackbox POV of image inpainting from diffusion model</figcaption></figure><p><strong>The Starting Point — Reference Image with a Twist<br></strong>Inpainting embarks on its journey with a reference image, akin to image-to-image translation. However, this image harbors a secret: parts of it are masked, signifying areas craving reconstruction. These masked regions are the blank canvases awaiting the model’s artistic touch, while the unmasked areas offer a contextual backdrop.</p><p><strong>The Choreography of Denoising and Noise Addition<br></strong>This process parallels the steps in image-to-image translation but diverges in a key aspect: the treatment of noise in each timestep ‘t’. The model performs its standard denoising prediction across the whole image, but the subsequent noise reintroduction varies between the masked and unmasked regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ1JEdynJUJVLyjFTvDeUQ.png" /><figcaption>Step wise complex process of denoising in inpainting process</figcaption></figure><p><strong>A Dual Approach in Noise Sampling:</strong></p><ul><li><strong>For the Mask Region:</strong> In the areas that are masked, the model adds noise to its previous prediction. This step allows for a gradual and natural development of the inpainted content, ensuring that the new elements blend seamlessly with the existing image.</li><li><strong>For the Non-Mask Region:</strong> Conversely, in the non-masked parts of the image, the model reverts back to the original image at each timestep. It adds noise to this original content, then seamlessly blends it with the masked region. This ensures that the non-masked area remains true to the original image, providing a stable and consistent backdrop for the inpainted parts.</li></ul><p>The final step involves blending the newly-noised non-mask region with the inpainted mask region. This blending is crucial for maintaining the coherence and visual flow of the image. The model then proceeds to make its denoising prediction for the next timestep, ‘t-1’, taking into account both the original image in the non-mask region and its previous inpainting predictions in the masked area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkDyrKH2BECDGBd5daeZqA.png" /><figcaption>Examining a single timestep of the denoising process in masked inpainting. Among the four images, the input image and input mask remain constant, while the guided text prompts vary from top left to bottom right: “A spiderman riding a horse,” “An alien riding a horse,” “A robot riding a horse,” and “An astronaut riding a horse.” Notice how the area outside the mask (indicated by the red line) remains consistently identical, whereas the region within the mask differs between the prompts.</figcaption></figure><p>Thus, inpainting within stable diffusion models masterfully ensures that the non-masked region upholds its original character, thanks to its predefined denoising trajectory. Simultaneously, the masked area blossoms with each timestep, shaped by the surrounding context and the model’s inventive predictions, crafting a harmonious and coherent whole.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821d66a663f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing Generative AI for Augmentation of ID Document Imagery]]></title>
            <link>https://medium.com/@asrielhan/harnessing-generative-ai-for-augmentation-of-id-document-imagery-9f59be7bc405?source=rss-efefa7748079------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f59be7bc405</guid>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Asriel Han]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 21:22:10 GMT</pubDate>
            <atom:updated>2023-06-11T21:26:23.069Z</atom:updated>
            <content:encoded><![CDATA[<p>The digital age has brought about remarkable advancements in technology, but with these advancements come new challenges. Among these is the growing prevalence of counterfeit and forged documents, a trend that is rapidly escalating due to the ease with which such fraudulent activities can now be executed. This escalation poses significant threats to both individual identity and financial security across society.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5Oy_S19AOsgmPISamegWg.png" /><figcaption><em>A set of counterfeit ID cards scattered across a table — MidJourney</em></figcaption></figure><p>An increasingly prevalent countermeasure to this looming threat involves the integration of sophisticated computer vision (CV) and Natural Language Processing (NLP) strategies by numerous organizations, specifically targeted towards identifying and counteracting document fraud. Although these techniques offer powerful tools in the fight against fraud, they necessitate the availability of comprehensive, meticulously labeled training datasets to effectively train the underlying algorithms.</p><p>Yet, procuring such datasets, particularly those revolving around ID document data, emerges as a daunting task due to the strict security and privacy regulations in place. The persisting deficiency of adequately annotated data consistently poses a significant hurdle within the discipline, hampering progress and restricting the scope for breakthroughs in fraud detection.</p><h3><strong>Generative AI: A Novel Approach</strong></h3><p>In this context, the potential of Generative AI emerges as a beacon of hope. Generative AI, a subset of AI, has the potential to provide a unique solution to this data scarcity problem. The principle behind this technology is the creation or ‘generation’ of new data instances that mimic the characteristics of the original data.</p><p>Specifically, for ID document imagery, Generative AI can be utilized to generate synthetic data that closely resemble real ID documents, effectively augmenting the limited datasets available. This synthetic data can then be used for the training of downstream computer vision and NLP models, thereby bypassing the challenges associated with data privacy and security.</p><p>The use of synthetic data doesn’t only solve the problem of scarcity, but also offers a controlled environment where specific features or anomalies can be introduced deliberately. This ensures more robust model training as it allows the system to encounter and learn from a wide range of potential scenarios, including edge cases that may not be represented in the real-world data.</p><p>While the concept of synthetic data generation may appear novel, its potential benefits to the field of fraud detection are undeniable. The subsequent sections of this blog will delve deeper into the utility of Generative AI, discuss the steps involved in generating synthetic ID document imagery, and explore the possibilities this technological innovation brings to the table for enhancing security measures.</p><h3><strong>Experiments</strong></h3><p>In this section, we explore the potential approaches to leveraging generative models, specifically large diffusion models, to generate and augment document data. Through a series of experiments, we assess the strengths and limitations of these methods, guiding our path towards an optimized solution.</p><p><strong>Approach 1: Direct Generation of ID Documents using a Diffusion Model</strong></p><p>Our first approach entailed prompting a Stable Diffusion model to generate ID documents directly. The prompts ranged in complexity; from basic requests such as “a photo of an ID card”, to intricately engineered prompts designed to elicit a specific response, like “US ID card, in the style of harmonious chaos, hybrid of contemporary and traditional, opacity and translucency, suburban ennui capturer, non-representational forms”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Mj-dOAEu3QLJIvUTddbV2w.png" /><figcaption>diffusion generated ID documents</figcaption></figure><p>Despite the range and diversity of the prompts, the results were less than satisfactory. The majority of the outputs failed to replicate the intricate details found in real ID documents, often presenting skewed or distorted text, characters, and letters, thus demonstrating the limitations of the diffusion model in generating text-based images.</p><p><strong>Approach 2: Inpainting with a Pre-Trained Diffusion Model to Augment Existing Documents</strong></p><p>The second approach involved leveraging the inpainting function of a pre-trained diffusion model to augment existing document data. This method showed efficacy in altering the non-text portions of the documents, adding another layer of complexity and variability to the synthetic data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_grG3t1YKOlcWDSrptHeg.png" /><figcaption>A group of synthetic ID documents collected from government websites</figcaption></figure><p>However, this approach, similar to the first, also faltered when it came to text rendering. Despite its successes with non-textual elements, the model was not able to effectively handle the modification or creation of text within the documents. This reiterated the challenge of producing synthetic data that accurately represents the complex, text-heavy nature of ID documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9CSDeE7y5_3BFTKWO9cFA.png" /><figcaption>diffusion-augmented ID documents. Leftmost is the original image, second to left is the masked region, and the rest three are augmented images.</figcaption></figure><p>These experiments underline the complexity of generating synthetic ID document imagery and emphasize the need for more refined techniques, particularly when it comes to the handling and generation of text within these documents. The subsequent part of this article will discuss potential solutions to these challenges and explore the future prospects of Generative AI in document fraud detection.</p><p><strong>Approach 3: Integrating Fine-Tuned Language and Vision Models for Automated Synthetic Visual Document Generation</strong></p><p>The limitations encountered in the previous approaches highlight the insufficiency of off-the-shelf models for specific tasks such as text rendering and comprehensive composition understanding. As such, a more nuanced solution is proposed: a customized pipeline that leverages both fine-tuned language models and retrained vision diffusion models, tailor-made for our use case.</p><p>The first step in this pipeline involves using <a href="https://github.com/PaddlePaddle/PaddleOCR">Optical Character Recognition (OCR)</a> and <a href="https://huggingface.co/docs/transformers/model_doc/layoutlmv3">LayoutLM</a> to semantically comprehend and parse the document. This step retrieves different text regions and their respective contents, effectively breaking down the document into its individual components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKXf2ZbNSBFyd6KW-5N7dg.png" /><figcaption>face detection result</figcaption></figure><p>Following this, we employ <a href="https://github.com/serengil/retinaface">Retina Face detector</a> and face parsing techniques to extract the headshot regions. These regions, though small in comparison to the entire document, carry crucial information and are thus treated with individual care.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U2P3-VgCck0hysKipNFJQQ.png" /><figcaption>Dense OCR result</figcaption></figure><p>Next, we leverage <a href="https://chat.openai.com/?model=gpt-4">ChatGPT</a> to automatically generate a multitude of variations in the text layout. By introducing this variability, we ensure that the synthetic data covers a wide range of possible document formats and layouts, thus enhancing the diversity of our training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkyiWOvI1RixGdiA-HsHxA.png" /><figcaption>LayoutLM result</figcaption></figure><p>Subsequently, we introduce the new layout to a modified diffusion model. This model, equipped with a character encoder plugin, is capable of editing burned-in text within the image in a harmonious manner, learning from the font size, style, and color of surrounding or neighboring texts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfKW-DOF6I3B2999UWScog.png" /><figcaption>before and after</figcaption></figure><p>In parallel to this process, the model also modifies the headshot region using the face segmentation mask as an inpainting mask. This allows for the creation of diverse and realistic headshots within the synthetic documents.</p><p>This innovative pipeline represents a significant stride forward in the generation of synthetic ID document imagery. By simultaneously addressing the challenges of text rendering and image processing, it provides a comprehensive solution to the limitations identified in the previous approaches. The following section will discuss the results and implications of this method, offering insights into the future of Generative AI in document fraud detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uDPA1AGWgTbNV1CX8ggfA.gif" /><figcaption>Animated results of ID card augmentation</figcaption></figure><p>One of the notable outcomes of this approach was the significant improvement in text rendering and composition understanding. This was achieved by using a fine-tuned language model to generate numerous text layout variations and a modified diffusion model to harmonize text editing, effectively overcoming the challenges faced in previous approaches. Furthermore, the model demonstrated an impressive capacity to handle complex tasks such as headshot modification, showcasing its potential for generating comprehensive and detailed synthetic data.</p><p>However, it is important to acknowledge that while these advances are significant, they represent just one step on the journey towards a comprehensive solution for document fraud detection. Future research will need to continue refining these techniques and exploring novel ways to further enhance the generation of synthetic data.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, the use of Generative AI in creating synthetic ID document imagery presents an exciting frontier in the fight against document fraud. The progress made thus far underscores the potential of AI to address complex challenges and offers a glimpse into the future of a safer, more secure digital society. As we continue to refine and develop these techniques, we can look forward to more robust, effective solutions in the realm of document security</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f59be7bc405" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn a Foundation Model into a Data Factory — Part One]]></title>
            <link>https://medium.com/@asrielhan/turn-a-foundation-model-into-a-data-factory-part-one-a6996dcc9b73?source=rss-efefa7748079------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6996dcc9b73</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-labeling]]></category>
            <dc:creator><![CDATA[Asriel Han]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 20:58:38 GMT</pubDate>
            <atom:updated>2023-04-21T20:58:38.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turn a Foundation Model into a Data Factory — Part One</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*4jd7UuUazKJbEiqUZZbXLA.gif" /><figcaption>Augmented image data through text and latent space</figcaption></figure><p>The availability of high-quality training data is critical to the success of any AI project. Unfortunately, collecting and labeling large volumes of data is time-consuming, expensive, and in some cases, impractical. Traditional solutions to this problem, such as conventional <a href="https://www.v7labs.com/blog/data-augmentation-guide#:~:text=Data%20augmentation%20is%20a%20process,data%20to%20amplify%20the%20dataset.">data augmentation algorithm</a>, <a href="https://www.techtarget.com/searchcio/definition/synthetic-data#:~:text=Synthetic%20data%20is%20information%20that&#39;s,to%20train%20machine%20learning%20models.">synthetic data generation</a>, and <a href="https://labelbox.com/guides/data-labeling/">human labor labeling</a>, have their own limitations and drawbacks.</p><p>In this series of blog posts, I want to explore a relatively new approach to tackling the training data issue: using foundation (generative) models to mass produce annotated datasets. I’ll examine a simple, real-world example of this application: using generative models to complement and augment large-scale labeled datasets such as the <a href="https://mmlab.ie.cuhk.edu.hk/projects/CelebA.html">CelebA</a> dataset, which contains over 200K celebrity images each with 40 attribute annotations. The code shown later in the post is built on top of existing work from the <a href="https://github.com/ml-research/semantic-image-editing">SEGA</a> repo, which explores latent space editing on diffusion model output. You can find all the coding in this post on GitHub: <a href="https://github.com/asrlhhh/diffusion-data-factory">https://github.com/asrlhhh/diffusion-data-factory</a></p><p>This post will explore the following topics:</p><ul><li>Existing data labeling solutions</li><li>The process of the diffusion model</li><li>The concepts of data distillation</li><li>The mass production of annotated datasets through the diffusion model’s text space</li><li>The mass production of annotated datasets through the diffusion model’s latent space</li></ul><p>In upcoming posts, I’ll assess the effectiveness of diffusion models in comparison to other methods, focusing on their ability to augment data and labels while maintaining existing features and preserving facial identity. Additionally, I’ll examine the enhancements these models contribute to the performance of those trained on augmented datasets.</p><h3>Limitations of existing data labeling solutions</h3><p>Despite the usefulness of existing solutions, they are not without limitations.</p><ul><li>Data augmentation algorithms are usually too simplistic to bring expected diversity to the dataset</li><li>Synthetic data generation can be computationally intensive and may not fully reflect the complexity of real-world data</li><li>Employing human labor for labeling can be costly and time-consuming, and the result can lack quality and consistency</li></ul><p>These limitations make it challenging to obtain sufficient quantities of high-quality labeled data, which can impede the development of effective AI models. This is an especially big problem for individual ML engineers, small teams, and early-stage companies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taw4SMLIoYQIMuYe7XCM1w.gif" /><figcaption><em>Clockwise from top left: 1) Illustration of traditional data augmentation techniques on image data [</em><a href="https://www.youtube.com/watch?v=mTVf7BN7S8w&amp;t=46s"><em>source</em></a><em>]. 2) A sample of a human data labeling tool in action [</em><a href="https://youtu.be/LQe7XplKfcE?t=542"><em>Source</em></a><em>] 3) NVIDIA Omniverse Replicator for DRIVE Sim — showcasing synthetic data generation capabilities [</em><a href="https://www.youtube.com/watch?v=gPaFgNEF82Q"><em>Source</em></a><em>] 4) An example of image data generated by early generative models, such as StyleGAN.</em></figcaption></figure><h3>Diffusion models and Stable Diffusion</h3><p><a href="https://en.wikipedia.org/wiki/Foundation_models">Foundation models</a>, such as diffusion models, address the challenge of insufficiently labeled data by learning the distribution of training data and generating high-quality, realistic data. <a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">Diffusion models</a> employ denoising score matching, a process that corrupts data with noise over multiple steps and then reverses, refining the noise using a learned denoising function. This generates realistic data samples resembling the training data, making diffusion models ideal for creating complex datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jjt6l90yO3A_eYLN.png" /><figcaption><em>Diffusion process in training &amp; inference time [</em><a href="https://www.paepper.com/blog/posts/how-and-why-stable-diffusion-works-for-text-to-image-generation/"><em>image source</em></a><em>]</em></figcaption></figure><p><a href="https://stability.ai/blog/stable-diffusion-public-release">Stable Diffusion</a> offers an efficient alternative to regular diffusion models by working in latent space. It uses an autoencoder to compress image data, accelerating diffusion processes. The inner diffusion model, with a <a href="https://vaclavkosar.com/ml/cross-attention-in-transformer-architecture">cross-attention mechanism</a>, converts text prompts into image embeddings. This enables Stable Diffusion to generate high-quality, annotated images by linking textual descriptions to visuals, creating large-scale labeled datasets with minimal human intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Kw9-DogPJevypGq.png" /><figcaption><em>Stable Diffusion process [</em><a href="https://www.paepper.com/blog/posts/how-and-why-stable-diffusion-works-for-text-to-image-generation/"><em>image source</em></a><em>]</em></figcaption></figure><h3><strong>Data distillation</strong></h3><p>Data distillation, which involves extracting labeled datasets from large models to train smaller, specialized models, is a <a href="https://neptune.ai/blog/knowledge-distillation">knowledge distillation</a> methodology that has emerged alongside the development of large foundation models. Work on distilling data from pretrained transformers like GPT began in 2021, and since then, numerous studies have explored data distillation for training data augmentation in large language models. In computer vision, data distillation often focuses on extracting annotated image–label pairs or well-aligned image pairs for image-to-image translation. A <a href="https://arxiv.org/pdf/2104.02815v1.pdf">2021 paper</a> initially proposed using synthetic face images generated by StyleGAN to train and test facial recognition models. Subsequently, various studies have investigated leveraging knowledge distillation for tasks like detection and segmentation in the field. [<a href="https://paperswithcode.com/paper/blind-knowledge-distillation-for-robust-image">1</a>] [<a href="https://paperswithcode.com/paper/robust-and-efficient-segmentation-of-cross">2</a>]</p><h3>Simple use case: augmenting a benchmark facial image dataset</h3><p>In this use case, we’ll delve into how a large diffusion model, Stable Diffusion, can be employed to augment the widely used <a href="https://mmlab.ie.cuhk.edu.hk/projects/CelebA.html">CelebA facial dataset</a> through a guided data distillation process. CelebA is a large-scale dataset containing over 200,000 celebrity images, each annotated with 40 attributes, along with landmarks. Stable Diffusion, as part of the family of diffusion models, can generate a vast number of synthetic yet realistic-looking facial images, complete with attribute labels. This approach not only accelerates the creation of a high-quality labeled dataset but also mitigates the need for human labor–intensive labeling processes. By harnessing the power of diffusion models, we can rapidly develop smaller scale AI models for applications such as facial recognition, attribute prediction, and even content generation in the entertainment industry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zV2o9klZPv7ld3WO.png" /><figcaption>Cover image from official CelebA dataset website</figcaption></figure><h3><strong>The labels imbalance issue in the CelebA dataset</strong></h3><p>In the world of machine learning, the concept of a flawless dataset is always a fallacy. Regardless of the meticulousness of their labeling, every dataset inevitably inherits limitations and biases from the real world. The CelebA dataset, for instance, comprises 200,000 images, each annotated with 40 labels. However, upon closer examination of these annotations, it becomes evident that each binary label exhibits an imbalance, with the majority of annotations being either predominantly positive or negative. This phenomenon can typically be attributed to the unequal representation of labels within the real world where the data were captured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8W0PJQLOC2nAO-7-VUC0YQ.png" /><figcaption><em>Stacked bar chart illustrating the annotation distribution of each label</em></figcaption></figure><p>The aforementioned imbalance is illustrated in the correlation heat map below. As mentioned, real-world data often exhibit inherent statistical biases, such as the strong positive correlation between ‘<strong>Heavy_Makeup</strong>’ and ‘<strong>Wearing_Lipstick</strong>’ or the pronounced negative correlation between ‘<strong>Male</strong>’ and ‘<strong>Heavy_Makeup</strong>.’ This skewed distribution may lead to a model internalizing these biases and generating inaccurate predictions. For instance, whenever the model identifies an individual wearing makeup, it may consistently assign a positive label to ‘Wearing_Lipstick’ as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNb1NmoCQ5UONCL6JsaAbA.png" /><figcaption><em>Heatmap distribution of the correlation score between labels</em></figcaption></figure><p>This is where generative models such as Stable Diffusion can be advantageous. By using its prompt and latent input, we can augment the existing dataset and reestablish label balance. I’ll provide a step-by-step walkthrough of the codebase to establish a “data factory.”</p><h3><strong>Step One: Setting up the base prompt template</strong></h3><p>As the first step, we create a text prompt template designed to facilitate the generation of labeled facial datasets with diverse attributes. The template consists of 35 out of the original 40 attribute categories in CelebA. I removed a few attributes that are either beyond the model’s capacity (5 o’clock shadow) or likely to induce ethical concerns (like ‘attractive’). The rest are common features such as nose size, hair color, bangs, mouth size, cheeks, face shape, eyebrow shape, eye size, skin tone, facial hair, and apparel. For each category, we define an array of possible labels corresponding to different facial features or characteristics. The model will then randomly assign these labels to generate a diverse range of facial images accordingly.</p><pre>prompt_template = {<br>   &quot;base&quot;: &quot;A professional colorful headshot of a{Smiling}{Young} {Male},&quot;,<br>   &quot;hair&quot;: &quot;{Wavy_Hair}{hair_color}{Receding_Hairline} hairs,&quot;,<br>   . . . more key, value pairs hidden . . .<br>   &quot;apparels&quot;: &quot; wearing{Wearing_Earrings}{Wearing_Hat}{Wearing_Lipstick}{Wearing_Necklace}{Wearing_Necktie}, &quot;<br>}<br><br>prompt_map = {<br>   &quot;Smiling&quot;: {0:&quot;&quot;, 1:&quot;smiling&quot;},<br>   &quot;Young&quot;: {0:&quot;&quot;, 1:&quot;young&quot;, -1:&quot;old&quot;},<br>   &quot;Wavy_Hair&quot;: {0:&quot;&quot;, 1:&quot;wavy&quot;, -1:&quot;straight&quot;},<br>   &quot;hair_color&quot;: {0:&quot;&quot;, 1:&quot;blonde&quot;, 2:&quot;black&quot;, 3:&quot;brown&quot;, 4:&quot;gray&quot;},<br>   . . . more key, value pairs hidden . . . <br>   &quot;Wearing_Earrings&quot;: {0:&quot;&quot;, 1:&quot;earrings&quot;},&quot;Wearing_Hat&quot;: {0:&quot;&quot;, 1:&quot;hat&quot;},<br>   &quot;Wearing_Lipstick&quot;: {0:&quot;&quot;, 1:&quot;lipstick&quot;},&quot;Wearing_Necklace&quot;: {0:&quot;&quot;, 1:&quot;necklace&quot;},<br>   &quot;Wearing_Necktie&quot;: {0:&quot;&quot;, 1:&quot;necktie&quot;}<br>}</pre><h3>Step Two: Random initialization of prompt</h3><p>Then, we define a function called <em>randomize_prompt</em> to dynamically generate diverse facial images by randomizing the text prompt for each iteration. The function ensures that any combination of the 35 features can be included in the generated images by leveraging both positive and negative prompt directions.</p><p>To handle any potential mutual exclusions between attributes, the function calls <em>handle_mutual_exlusion</em> before constructing the final prompt. The resulting prompt string is then populated with the randomized values and string representations, ensuring a diverse range of facial features and characteristics in the generated images. By limiting the token count to a predefined threshold <em>token_limit</em>, the function ensures that the generated prompt remains within the model’s input constraints.</p><pre>def randomize_prompt():<br>   # randomly select a key value from each key of the prompt_map<br>   # make sure that there are half the keys that have non -1 values<br>   # and return the prompt<br>   . . . codes hidden . . .<br>   # randomly select half of the keys for positive prompts and the other for negative prompts; save in prompt_template_keys dict<br>   prompt_final = &quot;&quot;<br>   prompt_template_keys = list(prompt_template.keys())<br>   prompt_template_keys.remove(&quot;base&quot;)<br>   random.shuffle(prompt_template_keys)<br>   prompt_template_keys = [&quot;base&quot;] + prompt_template_keys<br>   new_prompt_map_random = {}<br>   for i,prompt_key in enumerate(prompt_template_keys):<br>       container = PromptContainer(prompt_template[prompt_key])<br>       current_prompt_keys = container.get_all_variables()<br>       for key in current_prompt_keys:<br>           new_prompt_map_random[key] = prompt_map_random[key]<br>       tmp_prompt = container.populate(prompt_map_random_val)<br>       if len(token_counter(prompt_final+tmp_prompt)[&#39;input_ids&#39;]) &gt; token_limit:<br>           break<br>       prompt_final += tmp_prompt<br>   if prompt_final[-1:] == &quot;,&quot;:<br>       prompt_final = prompt_final[:-1] + &quot;.&quot;<br>   prompt_final = prompt_final + &quot; high quality, detailed.&quot;<br>   return prompt_final, negative_prompts, prompt_map_random</pre><h3>Step Three: Label retrieval</h3><p>We define the function get_labels() to retrieve and generate labels for each generated image based on the randomized text prompt. This function is crucial for creating a labeled dataset that can be used to train AI models on various facial attributes.</p><pre>def get_labels(prompt_map_random_val):<br>   # get the labels for the prompt<br>   labels = {}<br>   for key in prompt_map_random_val:<br>       if key == &quot;hair_color&quot;:<br>           hair_map = hair_color_map[prompt_map_random_val[key]]<br>           labels.update(hair_map)<br>       elif key == &quot;Wavy_Hair&quot;:<br>           hair_map = hair_style_map[prompt_map_random_val[key]]<br>           labels.update(hair_map)<br>       else:<br>           labels[key] = prompt_map_random_val[key]<br>   return labels</pre><h3>Step Four: Filtering low-quality output images</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BD3WgzbbneUiVSQlDdN2ZQ.png" /><figcaption><em>Four of ten images randomly sampled from Stable Diffusion are unclean or corrupted</em></figcaption></figure><p>In the process of generating facial images, it’s essential to ensure that the output images meet the desired quality standards. However, a large diffusion model can sometimes generate corrupted images, leading to distorted faces, partial faces, multiple faces, or even completely blank frames. To address this issue, I’ve designed a function called <em>has_single_high_quality_face</em> to filter out and discard low-quality output along with its labels during the production phase.</p><p>This function takes an input image and a minimum confidence threshold as arguments and checks if the image has exactly one high-quality face. It utilizes the <a href="https://github.com/serengil/deepface">DeepFace</a> library for initial face detection and the <a href="https://github.com/serengil/retinaface">RetinaFace</a> model as the detector backend. The function then filters high-quality faces based on the confidence score, ensuring that only images with a single face meeting the specified confidence threshold is retained.</p><p>The function also uses <a href="https://github.com/davisking/dlib">Dlib</a>’s shape predictor to detect facial landmarks and calculate the bounding box that includes hair. It verifies that the entire bounding box is within the image dimensions. This verification is essential in guaranteeing the integrity of the resulting facial images, as it ensures their completeness and prevents the occurrence of multiple faces within the same bounding box.</p><p>By employing this filtering step, the dataset production pipeline ensures that only high-quality facial images (those most similar to images of faces captured in the real world) are included in the final dataset, enhancing the effectiveness and reliability of the generated dataset for various AI applications.</p><pre>def has_single_high_quality_face(img, min_confidence=0.9):<br>   &quot;&quot;&quot;<br>   Check if the input image has one and only one high-quality face.<br>  <br>   Args:<br>       image_path (str): Path to the input image file.<br>       min_confidence (float): Minimum confidence score to consider a face as high-quality.<br>      <br>   Returns:<br>       bool: True if the image contains one and only one high-quality face, False otherwise.<br>   &quot;&quot;&quot;<br><br>   # Detect faces using DeepFace<br>   face_detections = DeepFace.extract_faces(img, detector_backend=&#39;retinaface&#39;, enforce_detection=False)<br>  <br>   # Filter high-quality faces based on confidence<br>   high_quality_faces = [face for face in face_detections if face[&#39;confidence&#39;] &gt;= min_confidence]<br>   if len(high_quality_faces) != 1:<br>       return False<br><br>   # Use Dlib&#39;s shape predictor for facial landmarks<br>   predictor_path = &quot;./shape_predictor_68_face_landmarks.dat&quot;<br>   predictor = dlib.shape_predictor(predictor_path)<br>   detector = dlib.get_frontal_face_detector()<br>   dlib_rects = detector(img, 1)<br>   if len(dlib_rects) != 1:<br>       return False<br>   dlib_rect = dlib_rects[0]<br><br>   # Get facial landmarks<br>   shape = predictor(img, dlib_rect)<br>   padding_ratio = 10<br>  <br>   # Calculate the bounding box including hair<br>   min_x = max(0, dlib_rect.left() - int(padding_ratio * dlib_rect.width()))<br>   min_y = max(0, dlib_rect.top() - int(2 * padding_ratio * dlib_rect.height()))<br>   max_x = min(img.shape[1], dlib_rect.right() + int(padding_ratio * dlib_rect.width()))<br>   max_y = min(img.shape[0], dlib_rect.bottom() + int(padding_ratio * dlib_rect.height()))<br><br>   # Check if the entire bounding box is within the image dimensions<br>   if min_x &gt;= 0 and min_y &gt;= 0 and max_x &lt;= img.shape[1] and max_y &lt;= img.shape[0]:<br>       return True<br>   else:<br>       return False</pre><h3>Step Five: Save the seed, prompts, and labels</h3><p>We save the images, seed number, positive prompt, negative prompt, and labels locally as the final step of generating the original face images. This allows us to duplicate each data point during the augmentation process later.</p><pre>for seed in tqdm(range(20000)):<br>   gen.manual_seed(seed)<br>   initial_prompt, negative_prompts, prompt_map = randomize_prompt()<br>   negative_prompts = &quot;, &quot;.join(negative_prompts)<br>   labels = get_labels(prompt_map)<br>   out = pipe(prompt=initial_prompt, negative_prompt=negative_prompts, generator=gen, num_images_per_prompt=num_images_per_prompt, guidance_scale=guidance_scale)<br>   images = out.images<br>   image = images[0]<br>   image = pil_to_numpy(image)<br>   if_face = has_single_high_quality_face(image, min_confidence=0.9)<br>   if if_face:<br>       filtered_seeds.append({&quot;seed&quot;:seed,&quot;init prompt&quot;:initial_prompt,&quot;negative prompt&quot;:negative_prompts, &quot;label&quot;:labels})<br>       image_path = str(seed).zfill(4)+&quot;.png&quot;<br>       image_path_full = os.path.join(selected_folder_full_path,image_path)<br>       save_image(image, image_path_full)<br>   else:<br>       image_path = str(seed).zfill(4)+&quot;.png&quot;<br>       image_path_full = os.path.join(filtered_folder_full_path,image_path)<br><br>with open(&quot;selected_seeds.json&quot;, &quot;w&quot;) as file:<br>   json.dump(filtered_seeds, file)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kUqxjEvB9SQwJ0PA.png" /><figcaption><em>Fifty samples of the generated images</em></figcaption></figure><h3>Step Six: Traversing the latent space for a cleaner, smoother transition</h3><p>The CelebA dataset contains 202,599 images and 10,177 unique identities, with most identities having multiple images. The ratio of images to identities is approximately 1 to 20. Therefore, to recreate the dataset, it’s necessary to generate faces of the same identities in different scenarios and possibly with different features.</p><p>Latent space interpolation in diffusion models achieves this by augmenting facial images with arbitrary features and varying strengths. By leveraging the principles of semantic guidance (SEGA) and isolating semantics within the latent space, it becomes possible to manipulate the image generation process in a controlled manner. The high-dimensional latent space can be understood as a composition of sub-spaces representing various semantic concepts. By interpolating between these sub-spaces, one can generate images with specific attributes or features.</p><p>For instance, let’s consider the task of augmenting a facial image with a specific hairstyle or facial feature. By identifying the dimensions within the latent space that encode the target concept, such as the desired hairstyle or feature, we can calculate the noise estimate conditioned on that concept description. The difference between the conditioned and unconditioned estimates can then be scaled and applied to the original image, effectively modifying the image to incorporate the desired feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YwjSaRQsiAI1NW5L.png" /><figcaption><em>Comparison between manipulating images in latent space vs. in text space</em></figcaption></figure><p>This method enables precise control over the strength and combination of arbitrary features added to the generated image. Through latent space interpolation in diffusion models, we can generate a diverse array of facial images with varying attributes, greatly expanding possibilities for creating large-scale, annotated datasets for various AI applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-wUNyuVl1_yWDlInfJA-A.gif" /><figcaption><em>Multi-label image transition through latent space</em></figcaption></figure><h3>Step Seven: Setting up warm-up and cooldown steps for regional control</h3><p>Some of the above samples, such as the open-mouth one, exhibit significant changes in appearance even with latent transition. To preserve the identity during augmentation, we require additional control over the transition process to ensure that it’s more localized and precise.</p><p>By leveraging the warm-up parameter δ, it becomes possible to implement regional controls over the image generation process, allowing for more nuanced and targeted augmentation of images. The warm-up parameter δ determines the point in the diffusion process at which guidance γ is applied. By setting a higher value for δ, the guidance is applied later in the process, ensuring that only fine-grained details of the image are altered while preserving the overall composition.</p><pre>for attribute_ind,single_attribute in enumerate(attributes_lst):<br>       direction_lst = generate_random_bool_list(len(single_attribute))<br>       guidance_lst = generate_random_float_list(len(single_attribute), edit_guidance_scale_min, edit_guidance_scale_max)<br>       threshold_lst = generate_random_float_list(len(single_attribute), edit_threshold_min, edit_threshold_max)<br>       warmup_steps = []<br>       cooldown_steps = []<br>       attribute_prompts = []<br>       for attribute in single_attribute:<br>           warmup_steps.append(attributes_full[attribute][&#39;warmups&#39;])<br>           cooldown_steps.append(attributes_full[attribute][&#39;cooldowns&#39;])<br>           attribute_prompts.append(attributes_full[attribute][&#39;prompt&#39;])<br>       labels_from_latent = {}<br>       for attr, direction in zip(single_attribute,direction_lst):<br>           if attr in labels:<br>               if direction:<br>                   labels_from_latent[attr] = -1<br>               else:<br>                   labels_from_latent[attr] = 1<br>       gen.manual_seed(seed)<br>       out = pipe(prompt = initial_prompt, generator = gen,<br>                  num_images_per_prompt = num_images_per_prompt, guidance_scale=guidance_scale,<br>                  editing_prompt= attribute_prompts,negative_prompt=negative_prompt,<br>                  reverse_editing_direction=direction_lst, # Direction of guidance i.e. increase all concepts<br>                  edit_warmup_steps= warmup_steps, # Warmup period for each concept<br>                  edit_cooldown_steps= cooldown_steps,<br>                  edit_guidance_scale=guidance_lst, # Guidance scale for each concept<br>                  edit_threshold=threshold_lst, # Threshold for each concept. Threshold equals the percentile of the latent space that will be discarded. I.e. threshold=0.99 uses 1% of the latent dimensions<br>                  edit_momentum_scale=0.3, # Momentum scale that will be added to the latent guidance<br>                  edit_mom_beta=0.6, # Momentum beta<br>                  edit_weights=[1]*len(attributes) # Weights of the individual concepts against each other<br>                 )<br>       images = out.images<br>       update_labels = labels.copy()<br>       update_labels.update(labels_from_latent)<br>       image = images[0]<br>       tmp = pil_to_numpy(image)<br>       if_face = has_single_high_quality_face(tmp, min_confidence=0.9)<br>       if if_face:<br>           png_name = str(image_cnt).zfill(6)+&quot;.png&quot;<br>           save_image(tmp, os.path.join(data_folder,png_name))<br>           annotate_data[&quot;path&quot;].append(os.path.join(data_folder,png_name))<br>           annotate_data[&quot;labels&quot;].append(update_labels)<br>           image_cnt = image_cnt + 1</pre><p>This warm-up technique lets users selectively modify specific regions or features within the generated image without affecting other parts. For example, one could apply regional control to change the hairstyle or add accessories to a facial image without altering the face’s underlying structure. The warm-up parameter provides an additional layer of control, allowing for more refined image augmentation and the creation of diverse, high-quality datasets with targeted attribute variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOwg5L8O22wNQg5jxdZqtQ.gif" /><figcaption><em>Comparison of latent space transitions with (on the left) and without (on the right) warm-up/cooldown controls.</em></figcaption></figure><p>The following examples demonstrate smooth latent transitions achieved using warm-up and cooldown steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbeNAIAopOmrT2Q3tabkWg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZ68KV1qNBj-NgZNKnPQdg.gif" /></figure><h3>Step Eight (optional): Enhancing output quality and correcting corruption using face restoration</h3><p>In the final step of generating facial images, an optional step is introduced to enhance the quality of the generated dataset by using a blind face restoration model, <a href="https://github.com/sczhou/CodeFormer/tree/50489a6736ef6ac75f00582a646782049898fe43">CodeFormer</a>. This model restores the quality of the facial images generated by the large diffusion model, making them more like real-world datasets such as CelebA.</p><p>The blind face restoration model works by improving the overall quality and clarity of the generated images while ensuring that all the labeled features remain unchanged. This can be beneficial when the goal is to create a high-quality dataset for training or fine-tuning AI models, as it helps reduce potential biases and improve generalization capabilities.</p><p>However, using the blind face restoration model can sometimes result in the removal of some fine-grained details on the face. The trade-off between quality enhancement and detail preservation is a crucial aspect to consider when deciding whether to apply the restoration step. This step is made optional in the pipeline to allow users to balance their dataset’s quality based on their specific requirements and preferences. In some cases, retaining certain fine-grained details might be more critical than obtaining the highest possible image quality, making the optionality of this step valuable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iII9x6ZI5IfClT0r.png" /><figcaption><em>Comparisons of the original output image (left) with the version that underwent face restoration (right). CodeFormer can correct artifacts, such as in eyes and teeth, introduced by the diffusion model while retaining the facial identity.</em></figcaption></figure><h3>Conclusion</h3><p>In this post, I’ve presented the process of setting up a diffusion model as a data factory, with an emphasis on generating high-quality facial datasets featuring diverse annotations that resemble and surpass the characteristics and distributions found in the CelebA dataset. When configured appropriately, foundation models can act as potent data-generation engines. Nonetheless, they possess limitations that may necessitate collaboration with other AI models or algorithms to produce accurate data and annotations.</p><p>In future posts, I’ll explore other functionalities of Stable Diffusion and compare diffusion and other generative models, investigating their ability to augment training and testing datasets. Stay tuned for upcoming articles in this series, and follow my LinkedIn account to stay informed about my ongoing journey in this field.</p><h3><strong>Coming next: Exploring Image Prompt for Augmenting Existing Data</strong></h3><p>In the next post, I’ll explore the use of the image prompt component of Stable Diffusion to facilitate granular editing on existing CelebA images, rather than generating new ones. By encoding the original CelebA images into latent vectors, we can employ the same semantic guidance methodology to modify these images for enhanced facial features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQQ7z1UVtGvGxjKu-QktoA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6996dcc9b73" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>