<?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 Sneha Ghantasala on Medium]]></title>
        <description><![CDATA[Stories by Sneha Ghantasala on Medium]]></description>
        <link>https://medium.com/@sneha-ghantasala?source=rss-872faa985ff7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s9KFnbbduDFiH9xFUwPX1A.jpeg</url>
            <title>Stories by Sneha Ghantasala on Medium</title>
            <link>https://medium.com/@sneha-ghantasala?source=rss-872faa985ff7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:52:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sneha-ghantasala/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[Tensor Parallel LLM Inferencing]]></title>
            <link>https://medium.com/tr-labs-ml-engineering-blog/tensor-parallel-llm-inferencing-09138daf0ba7?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/09138daf0ba7</guid>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[tensor-parallelism]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 21:18:53 GMT</pubDate>
            <atom:updated>2024-10-24T21:18:53.521Z</atom:updated>
            <content:encoded><![CDATA[<p>As models increase in size, it becomes impossible to fit them in a single GPU for inference. There are different types of model parallelism techniques to tackle this issue. Tensor parallelism is a type of model parallelism where the model is split across multiple GPUs such that computations can happen in parallel. This is unlike pipeline model parallelism where the model is split vertically such that the first few layers are in one GPU, the next few layers in the second GPU and so on. In pipeline parallelism, all GPUs are not working simultaneously (unless you have a stream of constant batches of requests), for example, the second GPU can only begin its computations after it gets the results of the previous layer from the first GPU. On the other hand, with tensor parallelism there could be a larger overhead of sharing partial calculation results between all involved GPUs. Depending on the memory, throughput, latency requirements and implementation of the technique you might resort to either pipeline or tensor parallelism or to a combination of both.</p><p>In this article, we will be deep diving into tensor parallel model parallelism for transformer based models, i.e. language models. There are different implementations for tensor parallel model parallelism, and we will be looking at the <a href="https://arxiv.org/pdf/1909.08053">Megatron-LM implementation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKRMXnncpQtmtzRFL7Qx5Q.png" /><figcaption><em>Pipeline Parallelism vs Tensor Parallelism: </em><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/model-parallel-intro.html"><em>Credits: AWS</em></a></figcaption></figure><h3><strong>Megatron-LM</strong></h3><p><a href="https://arxiv.org/pdf/1909.08053">Megatron-LM paper</a> describes an efficient and simple to implement approach for tensor parallelism in large language models (LLMs). The key takeaways of this implementation are:<br>1. They take advantage of the transformer model architecture to create a simple model parallel implementation.<br>2. Model parallelism is introduced separately in the self-attention blocks, the multi-layer perceptron (MLP) blocks, the input embedding weight matrix and the output embedding generated.<br>3. For the self-attention blocks inherent parallelism in the multihead attention operation is exploited, partitioning such that the matrix multiply corresponding to each attention head is done locally on one GPU.</p><blockquote>Much of our model parallel approach can be characterized as techniques aimed at reducing communication and keeping the GPUs compute bound. Rather than having one GPU compute part of the dropout, layer normalization, or residual connections and broadcast the results to other GPUs, we choose to duplicate the computation across GPUs. Specifically, we maintain duplicate copies of layer normalization parameters on each GPU, and take the output of the model parallel region and run dropout and residual connection on these tensors before feeding them as input to the next model parallel regions. To optimize the model we allow each model parallel worker to optimize its own set of parameters. Since all values are either local to or duplicated on a GPU, there is no need for communicating updated parameter values in this formulation.<br><strong>[verbatim from the paper]</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*_8TbqsIZGOlJMfKWcFh7MQ.png" /><figcaption><em>Transformers Model Architecture: </em><a href="https://arxiv.org/pdf/1909.08053"><em>Credits: Megatron-LM Paper</em></a></figcaption></figure><h3><strong>vLLM</strong></h3><p>In our experiments, we used <a href="https://docs.vllm.ai/en/latest/serving/distributed_serving.html">vLLM</a>, a library for LLM inferencing and serving. The library supports deploying LLMs via the distributed tensor parallelism approach. It currently supports Nvidia’s implementation and integration of Megatron-LM’s tensor parallel algorithm. We mainly focused on single instance multi GPU deployments.</p><p>The <em>tensor_parallel_size</em> configuration parameter tells vLLM how many GPUs to use for distributed model parallelism. During model inference, we resort to greedy sampling (i.e. <em>model temperature</em> set to 0) to ensure deterministic results, meaning identical inputs will consistently produce identical outputs. Here’s how <em>tensor_parallel_size</em> affected greedy sampling in our experiments:</p><ul><li>We observed deterministic outputs for the same input across model deployments that share identical <em>tensor_parallel_size</em> values.</li><li>But outputs between model deployments with differing <em>tensor_parallel_size</em> values were not the same.</li></ul><p>For example, for a query like:<br>&gt; <em>Tell a story</em>.</p><p>For multiple runs, Output: <em>tensor_parallel_size</em>: 1</p><blockquote>Once upon a time in a far away land there was a kingdom that was being overrun by wolves. The king of the kingdom called a meeting of the town elders to discuss what should be done to stop the wolves from eating the townsfolk and livestock. The town elders discussed many options and decided the best course of action was to have a competition to see who could kill the most wolves…</blockquote><p>For multiple runs, Output: <em>tensor_parallel_size</em>: 2</p><blockquote>Once upon a time in a far far away land there was a kingdom that was being terrorized by a great and powerful wizard who would cast a spell every new moon that would cause the citizens to dance themselves to death. \n\nNow in this kingdom there was a great and powerful wizard too, and he decided that he had enough of being terrorized by this other wizard, so he decided to put a stop to it…</blockquote><p>For multiple runs, Output: <em>tensor_parallel_size</em>: 4</p><blockquote>Once upon a time in a far far away land there was a kingdom that was being terrorized by a great and powerful wizard who would cast a spell every new moon that would cause the citizens to dance themselves to death. \n\nThere was a great uproar in the land and the King decided that he must find a way to stop this wizard and save his people…</blockquote><p>We were curious why this could happen. The first thing that comes to our mind when the outputs are different is that the output probabilities are different, which in turn means that some computations are happening differently. Initially, we couldn’t understand how this was possible, so we raised a GitHub Issue in vLLM’s code repository for the same.</p><p>In the meantime, we were also looking at the source code to understand where the <em>tensor_parallel_size</em> parameter makes a difference. All in all, it boiled down to one of the most basic concepts in floating point arithmetic:<br>Floating point arithmetic is not associative, i.e.</p><blockquote>(a + b) + c != a + (b + c)</blockquote><p>(It is commutative though, i.e. <em>a + b = b + a</em>)</p><p>In tensor parallellism, after the parallel computations are done, the results of a particular GPU’s computations are communicated to all other GPUs via an AllReduce operation. In Nvidia’s Megatron-LM implementation, NCCL’s AllReduce function is used for communicating and reducing outputs across the GPUs.</p><p>Since floating point arithmetic isn’t associative, it means that the order in which the output reductions happen matters. This is what was eventually posted in the <a href="https://github.com/vllm-project/vllm/issues/2891#issuecomment-2312069636">GitHub Issue</a> raised as well.</p><p>Another point to note is that, NCCL has a few different implementations for the AllReduce algorithm. When <a href="https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html#AllReduce">NCCL’s AllReduce</a> method is used, NCCL selects a specific implementation by estimating the time each implementation will take based on the network topology and then chooses the fastest one. [1]</p><h3><strong>Takeaways..</strong></h3><p>Observations and deductions from our experiments:</p><ul><li>Despite minor discrepancies in calculations, differences in output tokens only become noticeable when top probabilities vary. For example, we’ve seen that different <em>tensor_parallel_size</em> deployments yield identical outputs for some inputs, while for others, the initial few generated tokens are the same but gradually start to differ. It’s worth noting that once a single token deviates, the likelihood of subsequent tokens diverging increases.</li><li>Differences in model outputs can also depend on the openness of the question. For open-ended questions, the top probabilities for output tokens might be very close. So, even minor changes in calculations can lead to significantly different outputs.<br>For example, the outputs we get for a query like,<br>&gt; <strong><em>Tell a story. (see above)</em></strong><br>In contrast, for a query like,<br>&gt; <strong><em>Write a python function to convert a string to capital letters.</em></strong><br>Output for all <em>tensor_parallel_size</em> configurations (1, 2, 4):<br><strong><em>def str_to_capital(str):\n return str.upper()</em></strong></li><li>The variation in outputs across tensor parallel sizes also seemed to depend on the model itself. In our experiments, we observed less variation when experimenting with newer models like llama3 compared to older models based on mpt. This could be because of how and how much the model was trained.</li><li>The GPU architecture on which the deployment happens also matters. Meaning the outputs could be different across different architectures as well. Different GPUs can cause the LLM to output different results, even with the same environment, settings, and seed. This variability increases with longer prompts because they require more calculations, increasing the propagation of inaccuracies and promoting divergences between two GPUs. [4]</li><li>There is inherent randomness as part of certain algorithm/library implementations, which can be turned off. For example, <a href="https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms">here</a> are some settings for pytorch.</li></ul><p>That’s all for now. We would love to learn about your experiences with tensor parallel model deployments, as well! Drop us a comment here or on our <a href="https://www.linkedin.com/groups/8168422/">LinkedIn group</a>.</p><h3><strong>Good Reads and References</strong></h3><ol><li>Communication with NCCL: <a href="https://youtu.be/T22e3fgit-A?si=RpUy17v4PnZHqkEo">Lecture 17: NCCL</a></li><li><a href="https://youtu.be/TB07_mUMt0U?si=l9EfYtEJLJEWU5cf">Deep Learning Determinism</a></li><li><a href="https://arxiv.org/html/2408.05148v1">Impacts of floating-point non-associativity on reproducibility for HPC and deep learning applications</a></li><li><a href="https://medium.com/@anis.zakari/changing-the-gpu-is-changing-the-behaviour-of-your-llm-0e6dd8dfaaae">Changing the GPU is changing the behaviour of your LLM</a></li><li><a href="https://community.openai.com/t/a-question-on-determinism/8185?trk=article-ssr-frontend-pulse_little-text-block">A question on Determinism: OpenAI forum</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09138daf0ba7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tr-labs-ml-engineering-blog/tensor-parallel-llm-inferencing-09138daf0ba7">Tensor Parallel LLM Inferencing</a> was originally published in <a href="https://medium.com/tr-labs-ml-engineering-blog">Thomson Reuters Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slow Reads for S3 Files in Pandas & How to Optimize it]]></title>
            <link>https://medium.com/tr-labs-ml-engineering-blog/slow-reads-for-s3-files-in-pandas-how-to-optimize-it-c3bfdb947a70?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3bfdb947a70</guid>
            <category><![CDATA[tr-lab]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[slow]]></category>
            <category><![CDATA[pickles]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 08:16:46 GMT</pubDate>
            <atom:updated>2023-02-17T08:16:46.730Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of one of our projects, we needed to load pickle files with sizes in the range of 10s of GBs from AWS S3 in AWS Sagemaker endpoints (private subnet is configured with S3 VPC endpoints). When using the pandas library to do this, passing the S3 URI of the file as an argument takes 16 min but downloading the file and then passing the file object takes 3 min. <em>Why?</em></p><p><strong>Our Scenario</strong> <br>We are using pandas for reading a large pickle file (in the range of 12 GB) from AWS S3. In this case, we are trying to understand why the pandas library shows a significant performance difference to read the same file when the argument is passed in a different way.</p><p><strong>Our Experiments<br></strong>Let’s deep dive into our 2 ways of loading the pickle data from S3 to investigate the reason behind the performance gap. To replicate these experiments, you would need to use the following library versions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*YPGuGOfr9SMfYgcWnfEmHA.jpeg" /></figure><p>Please note that the code tests were run in the same environment with the same file, multiple times — restarting kernels, changing kernels, and changing the order.</p><p><strong>Test 1</strong> <br>Read the pickle file from S3 using the pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_pickle.html">read_pickle </a>function passing S3 URI.<br><strong>Time taken: ~16 min</strong></p><pre>import pandas as pd<br>import time<br>​<br>start_time = time.time()<br>​<br>s3_uri = &quot;{s3_uri}&quot;<br>pq_file_data = pd.read_pickle(s3_uri)<br>​<br>end_time = time.time()<br>total_time = end_time - start_time<br>print(total_time)<br>​<br>#943.84 sec</pre><p><strong>Test 2<br>​​​​​​​</strong>Getting the S3 file using boto3 and passing it directly to the pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_pickle.html">read_pickle</a> function.<br><strong>Time taken: ~3 min</strong></p><pre>import pandas as pd<br>import time<br>import boto3<br>​<br>start_time = time.time()<br>​<br>s3_bucket_name = &quot;{s3_bucket_name}&quot;<br>filename = &quot;{pickle_filename_s3_path}&quot;<br>​<br>s3 = boto3.resource(&quot;s3&quot;)<br>file_obj = s3.Bucket(s3_bucket_name).Object(filename).get()[&quot;Body&quot;]<br>pq_file_data = pd.read_pickle(file_obj)<br>​<br>end_time = time.time()<br>total_time = end_time - start_time<br>print(total_time)<br>​<br>#178.28 sec</pre><p>Passing S3 URI takes ~16 min, while downloading and passing the file directly takes ~3 min. <strong>About 5x slower</strong></p><p><strong>Initial Investigation steps</strong></p><ol><li>Reading pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_pickle.html">documentation</a> and going through the <a href="https://github.com/pandas-dev/pandas">source code</a>.</li><li>Using Python’s inbuilt profiler to understand what takes time. We could also build a graph using the profiler’s output. Attached are a few graphs in the <a href="#ded3">Appendix section</a>. The red blocks are the most time-consuming blocks.</li><li>Using a debugger to understand the code flow for the two code tests.</li></ol><p><strong>Initial Findings</strong></p><ol><li>Test 1 streams in chunks, while Test 2 downloads the entire file and passes it so some performance gap is expected (i.e. Test 1 will take more time than Test 2). But the observed difference is quite high. Is the 5x performance difference justified?</li><li>The source code suggests that the pandas library internally calls the pickle library (Python in-built library) to read the pickle files (at least in our scenario).</li><li>For Test 1, the pandas library uses the <a href="https://pypi.org/project/s3fs/">s3fs</a> library to establish a connection with S3 and read the file.</li><li>The graphs generated using the profiler suggest for Code test 2 (pandas): read_ method ‘acquire’ of ‘_thread.lock’ objects takes up a lot of time. This doesn’t help figure out the large performance gap.</li></ol><p><strong>Further investigation steps</strong></p><ol><li>Reading documentation and reviewing the source codes for the pickle and <a href="https://github.com/fsspec/s3fs">s3fs</a> libraries.</li><li>Figuring out what are the different kinds of parameters affecting the read performance and playing around with them.</li></ol><p><strong>Our Final Findings</strong></p><ol><li>S3fs implements <a href="https://filesystem-spec.readthedocs.io/en/latest/">fsspec</a> and pandas uses the fsspec interface to access file systems (in our case S3).</li><li>The parameters <em>default_block_size </em>and <em>default_cache_type </em>of s3fs affect the read performance. At the time of writing this blog, s3fs had the <em>default_cache_type </em>set as<em> bytes </em>and the<em> default_block_size </em>as 5*2**20 Bytes (5MB). We can modify them. Below is the code snippet for the same.</li></ol><pre>import pandas as pd<br>​<br>pd.read_pickle({s3_uri}, storage_options={&quot;default_block_size&quot;:{block_size}, &quot;default_cache_type&quot;:{cache_type}})</pre><p>Here’s a table outlining the experiments done with different configurations obtained by modifying the values for those parameters.</p><p>The experiments suggest that changing the <em>default_cache_type</em> to <em>readahead</em> would give a good read performance improvement and a <a href="https://github.com/fsspec/s3fs/issues/677">Github Issue</a> for the same had been raised in s3fs’s Github repository.</p><p><strong>The experiment results were acknowledged by the s3fs devs and the <em>default_cache_type</em> has been changed to <em>readahead.</em></strong> <br> <br><strong><em> </em></strong><em>Note: The experiments weren’t performed multiple times with the same parameters for most of the configurations, so the read times can vary by a few seconds.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*ilZNzhVjagykIY9_kezrnw.png" /></figure><p>The cache_type parameter actually refers to the buffering scheme used while reading the file and the block_size parameter is used to configure the buffer size as mentioned <a href="https://filesystem-spec.readthedocs.io/en/latest/features.html#file-buffering-and-random-access">here</a>. For more information about the different cache types, you could refer to <a href="https://filesystem-spec.readthedocs.io/en/latest/api.html#readbuffering">this</a>.</p><p><strong>Conclusion<br>Pandas actually has nothing to do with the read performance of the files. It’s s3fs!</strong></p><p>We can configure the required parameters via Pandas for better performance. It may not be easy to know which one would be optimal — experiments like the one above may be required.</p><p>Choosing caches/blocksize involve tradeoffs. Here are some observations —</p><p>Did you know ‘all’ cache type is faster than downloading the full file and passing it to read_pickle but it requires 2x more memory since it holds the full size in memory while unpickling</p><p>And finally, ‘readahead’ cache’s memory requirement is much closer to the actual file size but it’s <strong>~1.75x slower </strong>(given optimal block_size).</p><p><strong>Thank you!</strong></p><p><strong>Appendix</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*6zxqv-0vEa1GDTS89Y_XPA.png" /><figcaption>Profiler Output Graph: Code Test 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQJQjXZKqf-b5pN6HWORuA.png" /><figcaption>Profiler Output Graph: Code Test 2</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3bfdb947a70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tr-labs-ml-engineering-blog/slow-reads-for-s3-files-in-pandas-how-to-optimize-it-c3bfdb947a70">Slow Reads for S3 Files in Pandas &amp; How to Optimize it</a> was originally published in <a href="https://medium.com/tr-labs-ml-engineering-blog">Thomson Reuters Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP: Word Embedding Algorithms]]></title>
            <link>https://sneha-ghantasala.medium.com/nlp-word-embedding-algorithms-158be887ffdb?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/158be887ffdb</guid>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[embedding-algorithm]]></category>
            <category><![CDATA[gloves]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 12:23:35 GMT</pubDate>
            <atom:updated>2021-04-29T12:23:35.960Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are Word Embedding Algorithms and why are they Useful?</strong></p><p>Word Embedding algorithms help create more meaningful vector representations for a word in a vocabulary. To train any ML model we need to have inputs as numbers. The input for NLP models is text (words), so we need to have a way to represent this data in numbers. The easiest way to represent a word in a vocabulary, so that we can train language models (for use cases like sentiment classification, language translation) is a one hot vector representation. But using this representation implies that no word is in any way related to another word in the vocabulary. Words like orange, apple, banana are more similar to each other and are used in similar contexts and so having similar representations for these words makes more sense. Word Embedding Algorithms aim to create such representations for words. They capture the relationships between words. We could visualize each number in the vector as corresponding to a feature and hence the embedding is a vector with values for each feature.</p><p>Word embeddings let our algorithm understand analogies (like man is to woman as king is to queen). Using word embeddings enable us to build NLP applications with relatively small labeled training sets.</p><p><strong>Overview of a few Word Embedding Algorithms</strong></p><p><em>The goal of these algorithms is not to do well on the learning objectives, but to learn good word embeddings.</em></p><p><em>There are word embeddings readily available online under permissive licenses which have been trained on huge corpuses of data. It’s a good idea to use them instead of training the models from scratch.</em></p><p><a href="https://arxiv.org/abs/1301.3781"><strong>WORD2VEC</strong></a></p><p>The main objective of this algorithm is to predict a target word based on a context word. There are different ways to select context words and target word, like:</p><ol><li>Skip gram model<br>Predict target words which are randomly chosen words within a window (say +/- 5–10 words) of the input context word.</li><li>CBow (Continuous bag of words)<br>Takes the surrounding contexts for a middle word and uses the surrounding words to try to predict the middle word.</li></ol><p>Approximate Model Architecture for Skip Gram model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ml4FGV1CavbfbxiRcwbM4A.png" /><figcaption>Referenced from Coursera</figcaption></figure><p>For understanding the architecture, let’s assume:<br>1. vocabulary size is 10000 words.<br>2. ‘glass 34’ means that the word ‘glass’ is the 34th word in the vocabulary<br>3. 034 is the one hot encoding of the word where the 34th value in the vector is 1 and the size of the vector is vocabulary size i.e 10000.<br>4. E — a parameter which the model will learn. This is the final Embedding matrix we are trying to build.<br>5. e34 is the word embedding of the 34th word in the vocabulary. In this case it’s the word embedding of ‘glass’.<br>6. Softmax layer — Predicts the probabilities for each word in the vocabulary being within the defined window of the input context word. The number of classes is the size of the vocabulary i.e 10000 in our example.</p><p>The probability of a particular word in the vocabulary being a target word given a context word for the skip gram model is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGjhnd0VdsEpMRXmc-IDKw.png" /></figure><p>Where Zt = transpose(parameter vector for that target word)*(embedding vector for the context word) + bias and n is the vocabulary size, i.e</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAIBDDXAiytUl1ydLIAsqQ.png" /></figure><p>Approximate Model Architecture for CBow model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vba1oBgkUNfL_mfiuzTdTg.png" /><figcaption>Referenced from <a href="https://www.coursera.org/lecture/nlp-sequence-models/word2vec-8CZiw">Coursera</a></figcaption></figure><p>Similar assumptions/naming conventions as the skip gram model hold for the above architecture as well.</p><p>Loss function for the Word2Vec model is the softmax loss function (In the below formula y is a one hot encoded predicted output target vector and y-hat is the one hot encoded correct target vector; n is the vocabulary size).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USSf9Q5KHUJ8NpZFqwt-uw.png" /><figcaption>Softmax Loss Function</figcaption></figure><p>The problem with the above architectures is that the computation of the Softmax Layer is very expensive and is proportional to the vocabulary size. Generally word embedding algorithms are trained on huge corpuses of data and hence this computation is a bottleneck. Some of the solutions to this problem are:</p><ol><li>Hierarchical Softmax<br>Instead of trying to categorize the input into all 10000 categories (vocab size) in one go, it has a binary classifier which first tells if the output is in/ the first x (or a different number) categories or the last 10000-x categories. And then there is another binary classifier which tells if the output is in the first y categories in this sub branch or the last and so on. It mimics a tree structure and eventually we’ll get to know which category the input can be classified(the leaf of the tree) into. Each of the nodes of the tree is a binary classifier. The computational cost of this scales like log(vocabulary size) rather than linear. In practice, this classifier doesn’t use a perfectly balanced or symmetric tree (with equal number of words on each side of the branch), they are developed such that the common words are on the top of the tree and can be reached faster(just a few traversals) and the less common words are buried much deeper in the tree.</li><li><a href="https://arxiv.org/abs/1310.4546">Negative Sampling</a><br>The main architecture change introduced by this idea is replacing the softmax classifier with multiple binary classifiers. The learning objective of the algorithm is changed to: Given a pair of words, predict if this is a context, target pair. For training this model, for each positive sample of a context, target pair we will have ‘k’ negative samples. To generate a positive sample we take a context word and look around a window of +/- 10 words and pick a target word. To generate a negative sample, we take the same context word and pick a word at random from the vocabulary as the target word (under the assumption that the random word picked probably won’t be associated with the context word). ‘k’ is generally in the range of 5–20 for smaller datasets and 2–5 for larger datasets. The model is basically a logistic regression model with the sigmoid activation function applied to the softmax input of the previous architectures. In summary, instead of having one giant 10000 (vocab size) way softmax we have instead turned it into 10000 binary classification problems, each of which is very cheap to compute. And in every iteration we are only going to train (k+1) of the binary classifiers which is relatively cheap to do. There are various heuristic methods to sample negative samples for choosing the target words for the context words and it can be found in the <a href="https://arxiv.org/abs/1310.4546">paper</a>.</li></ol><p>Modifications to the Word2Vec algorithm have also been made, like Facebook proposed the ‘FastText’ algorithm which is an extension of Word2Vec.</p><p><a href="https://www.aclweb.org/anthology/D14-1162/"><strong>GloVe</strong></a><strong> (Global Vectors for Word Representation)</strong></p><p>This is not used as much as the Word2vec model, but it has enthusiasts mainly because of it’s simplicity. Let:</p><ol><li>Xij = Number of times the word i(target word) appears in the context of j(context word), depending on the definition of context and target words Xij can be equal to Xji.</li><li>Vocabulary size =n for example: 10000 words</li></ol><p>The algorithm’s learning objective is to minimize the difference between transpose(θi)ej (softmax input in the above architectures) and log(Xij). We are trying to measure how related the context and target words are as measured by how often they occur with each other. We are trying to solve for parameters θ and e using gradient descent to minimize the following square cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0lOSRCNJngUjVJPuoBYDA.png" /><figcaption>Taken from <a href="https://www.coursera.org/lecture/nlp-sequence-models/glove-word-vectors-IxDTG">Coursera</a></figcaption></figure><p>We have an extra weighting term in the beginning of the equation for cases when Xij = 0. It also gives a meaningful amount of computation for less frequent words and makes sure a very huge value isn’t given for frequent words in our corpus. There are various heuristics in choosing this weighting function. One more thing to note here is that, when we look at the equation, the roles of θi and ej are symmetric in terms of optimizing the learning objective. So, we the take final embedding vector of a word as (θi + ej)/2.</p><p><em>References: </em><a href="https://www.coursera.org/specializations/natural-language-processing"><em>Coursera</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=158be887ffdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML PAPER: STYLEGAN — TL;DR]]></title>
            <link>https://sneha-ghantasala.medium.com/ml-paper-stylegan-tl-dr-5ed2e6954690?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed2e6954690</guid>
            <category><![CDATA[stylegan]]></category>
            <category><![CDATA[stylegan-paper]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 11:36:18 GMT</pubDate>
            <atom:updated>2020-12-29T11:36:18.697Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML PAPER: STYLEGAN — TL;DR</h3><blockquote>Research paper: <a href="https://arxiv.org/abs/1812.04948">A Style-Based Generator Architecture for Generative Adversarial Networks</a><br>Paper published — 29th March 2019 — by Nvidia<br>Website: <a href="https://github.com/NVlabs/stylegan">https://github.com/NVlabs/stylegan</a></blockquote><p><em>Disclaimer: These are just notes and lot of the text is taken from the paper.</em></p><p><strong>Main contributions:</strong></p><ol><li>They propose an alternative generator architecture for generative adversarial networks (GANs), borrowing from style transfer literature.</li><li>The new architecture leads to an automatically learned, unsupervised separation of high-level attributes (e.g., pose and identity when trained on human faces) and stochastic variation in the generated images (e.g., freckles, hair), and it enables intuitive, scale-specific control of the synthesis.</li><li>The new generator: <br>1. Improves the state-of-the-art in terms of traditional distribution quality metrics <br>2. Leads to demonstrably better interpolation properties<br>3. Leads to better disentangles the latent factors of variation.</li><li>To quantify interpolation quality and disentanglement, they propose two new, automated methods that are applicable to any generator architecture. <br>1. Perceptual path length<br>2. Linear separability<br><em>Further information on these methods can be found in detail in the </em><a href="https://arxiv.org/abs/1812.04948"><em>paper</em></a><em>.</em></li><li>Finally, they present a new dataset of human faces (Flickr-Faces-HQ, FFHQ) that offers much higher quality and covers considerably wider variation than existing high-resolution datasets. They have made this<br><a href="https://github.com/NVlabs/ffhq-dataset">dataset</a> publicly available, along with their source code and<br>pre-trained networks.</li></ol><p><strong>Generator Architecture changes:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*xrn7LQTLvh5lOysaKtM5Qw.png" /><figcaption>Figure 1: Image taken from the <a href="https://arxiv.org/abs/1812.04948">research paper</a>.</figcaption></figure><ol><li>Their baseline configuration is the <a href="https://arxiv.org/abs/1710.10196">Progressive GAN</a> setup of Karras et al., from which they inherit the networks and all hyperparameters except where stated otherwise.</li><li>They first switch to an improved baseline by using bilinear up/downsampling operations, longer training, and tuned hyperparameters.</li><li>They then improve this new baseline further by adding the mapping network and AdaIN operations , and make a surprising observation that the network no longer benefits from feeding the latent code into the<br>first convolution layer. <br>Traditionally the latent code is provided to the generator through an input layer, i.e., the first layer of a feedforward network (Figure 1a). They depart from this design by omitting the input layer altogether and starting from a learned constant instead (Figure 1b, right). Given a latent code z in the input latent space Z, a non-linear mapping network f : Z → W first produces w ∈ W (Figure 1b, left). For simplicity, they set the dimensionality of both spaces to 512, and the mapping f is implemented using an 8-layer MLP (Multi Layer Perceptron). They therefore simplify the architecture by removing the traditional input layer and starting the<br>image synthesis from a learned 4 × 4 × 512 constant tensor. Learned affine transformations then specialize w to styles y = (ys, yb) that control adaptive instance normalization(AdaIN) operations after each convolution layer of the synthesis network g. They find it quite remarkable that the synthesis network is able to produce meaningful results even though it receives input only through the styles that control the AdaIN operations.<br><em>The AdaIN operation is defined as in Figure 2, where each feature map xi is <br>normalized separately, and then scaled and biased using the corresponding scalar components from style y. Thus the dimensionality of y is twice the number of feature maps on that layer.</em></li><li>Finally, they introduce the below features which improve the results further by decorrelating neighboring styles and enabling more fine grained control over the generated imagery :<br><strong>1. Noise inputs (Stochastic Noise):</strong><br>They provide their generator with a direct means to generate stochastic detail (exact placement of hairs, stubble, freckles, or skin pores) by introducing explicit noise inputs. These are single-channel images consisting of uncorrelated Gaussian noise, and they feed a dedicated noise image to each layer of the synthesis network. The noise image is broadcasted to all feature maps using learned per-feature scaling factors and then added to the output of the corresponding convolution.<br>They find it interesting that the effect of noise appears tightly localized in the network. They hypothesize that at any point in the generator, there is pressure to introduce new content as soon as possible, and the easiest way for their network to create stochastic variation is to rely on the noise provided. A fresh set of noise is available for every layer, and thus there is no incentive to generate the stochastic effects from earlier activations, leading to a localized effect.<br>This observation is in line with style transfer literature, where it has been established that spatially invariant statistics (Gram matrix, channel-wise mean, variance, etc.) reliably encode the style of an image while spatially varying features encode a specific instance.<br>In their style-based generator, the style affects the entire image because complete feature maps are scaled and biased with the same values. Therefore, global effects such as pose, lighting, or background style can be controlled coherently. Meanwhile, the noise is added independently to each pixel and is thus ideally suited for controlling stochastic variation. If the network tried to control, e.g., pose using the noise, that would lead to spatially inconsistent decisions that would then be penalized by the discriminator. Thus the network learns to use the global and local channels appropriately, without explicit guidance.<br><strong>2. Mixing regularization<br></strong>To further encourage the styles to localize, they employ mixing regularization, where a given percentage of images are generated using two random latent codes instead of one during training. When generating such an image, they simply switch from one latent code to another — an operation they refer to as style mixing — at a randomly selected point in the synthesis network. They run two latent codes z1, z2 through the mapping network, and have the corresponding w1, w2 control the styles so that w1 applies before the crossover point and w2 after it. This regularization technique prevents the network from assuming that adjacent styles are correlated.</li><li>They evaluate their methods using two different loss functions: <br>1. For CELEBA-HQ they rely on WGAN-GP<br>2. FFHQ uses WGAN-GP for configuration A and non-saturating loss with R1 regularization for configurations B–F. They found these choices to give the best results.</li><li>Their contributions do not modify the loss function. They do not modify the discriminator or the loss function in any way, and their work is thus orthogonal to the ongoing discussion about GAN loss functions, regularization, and hyperparameters.</li><li>They observe that the style-based generator improves FIDs quite significantly over the traditional generator, almost 20%, corroborating the large-scale ImageNet measurements made in parallel work.</li><li>Their generator allows applying the truncation selectively to low resolutions only, so that high resolution details are not affected. All FIDs in the paper are computed without the truncation trick, and they only use it for illustrative purposes</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*NueZyeYTAeJ6cRrIid3l8w.png" /><figcaption>Figure 1: Image taken from the <a href="https://arxiv.org/abs/1812.04948">research paper</a>.</figcaption></figure><p><strong>Prior Work/Ideas</strong></p><ol><li>Progressive GANs architecture. They use this architecture, network hyperparameters as their baseline.</li><li>Previously a few authors have considered feeding parts of the latent code to multiple generator layers.</li><li>In parallel work, Chen et al. “self modulate” the generator using AdaINs, similarly to their work, but do not consider an intermediate latent space or noise inputs.</li></ol><p><strong>Training Details</strong></p><p>Can be found in full detail in the <a href="https://arxiv.org/abs/1812.04948">paper</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*JPw18oWnCpy9Og0OJ57dGg.png" /><figcaption>Table 1: Image taken from the <a href="https://arxiv.org/abs/1812.04948">research paper</a>.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed2e6954690" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML PAPER: CYCLEGAN — TL;DR]]></title>
            <link>https://sneha-ghantasala.medium.com/ml-paper-cyclegan-tl-dr-5f9a786aafd8?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9a786aafd8</guid>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[ml-paper-summary]]></category>
            <category><![CDATA[cyclegan]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 08:33:11 GMT</pubDate>
            <atom:updated>2020-12-29T08:33:11.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML PAPER: CYCLEGAN — TL;DR</h3><blockquote><em>Research Paper: </em><a href="https://arxiv.org/abs/1703.10593">Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks</a></blockquote><blockquote><em>Paper published — </em>24th August 2020<em> — Berkeley AI Research (BAIR) Laboratory, UC Berkeley</em></blockquote><blockquote>Website: <a href="https://junyanz.github.io/CycleGAN/">https://junyanz.github.io/CycleGAN/</a></blockquote><blockquote>Pytorch implementation: <a href="https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix">https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix</a></blockquote><blockquote>Torch implementation: <a href="https://github.com/junyanz/CycleGAN">https://github.com/junyanz/CycleGAN</a></blockquote><p><em>Disclaimer: These are just notes and lot of the text is taken from the paper.</em></p><p>Image-to-image translation is a class of vision and graphics problems where the goal is to learn the mapping between an input image and an output image using a training set of aligned image pairs. However, for many tasks, paired training data will not be available. They present an approach for learning to translate an image from a source domain X to a target domain Y in the absence of paired examples. Their goal is to learn a mapping G : X → Y such that the distribution of images from G(X) is indistinguishable from the distribution Y using an adversarial loss.</p><p>Because this mapping is highly under-constrained, they couple it with an inverse mapping F : Y → X and introduce a cycle consistency loss to enforce F(G(X)) ≈ X (and vice versa). Qualitative results are presented on several tasks where paired training data does not exist, including collection style transfer, object transfiguration, season transfer, photo enhancement, etc. Quantitative comparisons against several prior methods demonstrate the superiority of their approach.</p><p>In this paper, they present a method that can learn to do the same: capturing special characteristics of one image collection and figuring out how these characteristics could be translated into the other image collection, all in the absence of any paired training examples.</p><p>This problem can be more broadly described as image to-image translation, converting an image from one representation of a given scene, x, to another, y, e.g.,grayscale to color, image to semantic labels, edge-map to photograph.</p><p>Years of research in computer vision, image processing, computational photography, and graphics have produced powerful translation systems in the supervised setting, where example image pairs {xi, yi}N i=1 are available. However, obtaining paired training data can be difficult and expensive. For example, only a couple of datasets exist for tasks like semantic segmentation (e.g., [4]), and they are relatively small. Obtaining input-output pairs for graphics tasks like artistic stylization can be even more difficult since the desired output is highly complex, typically requiring artistic authoring. For many tasks, like object transfiguration (e.g., zebra↔horse), the desired output is not even well-defined.</p><p>They therefore seek an algorithm that can learn to translate between domains without paired input-output examples. They assume there is some underlying relationship between the domains — for example, that they are two different renderings of the same underlying scene — and seek to learn that relationship. Although they lack supervision in the form of paired examples, they can exploit supervision at the level of sets: they are given one set of images in domain X and a different set in domain Y : Paired training data (left) consists of training examples {xi, yi} N i=1, where the correspondence between xi and yi exists [22]. they instead consider unpaired training data (right), consisting of a source set {xi} N i=1 (xi ∈ X) and a target set {yj}M j=1 (yj ∈ Y ), with no information provided as to which xi matches which yj .</p><p>They may train a mapping G : X → Y such that the output yˆ = G(x), x ∈ X, is indistinguishable from images y ∈ Y by an adversary trained to classify yˆ apart from y. In theory, this objective can induce an output distribution over yˆ that matches the empirical distribution pdata(y) (in general, this requires G to be stochastic). The optimal G thereby translates the domain X to a domain Yˆ distributed identically to Y .</p><p>However, such a translation does not guarantee that an individual input x and output y are paired up in a meaningful way — there are infinitely many mappings G that will induce the same distribution over yˆ. Moreover, in practice, they have found it difficult to optimize the adversarial objective in isolation: standard procedures often lead to the well known problem of mode collapse, where all input images map to the same output image and the optimization fails to make progress.</p><p>These issues call for adding more structure to their objective. Therefore, they exploit the property that translation should be “cycle consistent”, in the sense that if they translate, e.g., a sentence from English to French, and then translate it back from French to English, they should arrive back at the original sentence. Mathematically, if they have a translator G : X → Y and another translator F : Y → X, then G and F should be inverses of each other, and both mappings should be bijections. they apply this structural assumption by training both the mapping G and F simultaneously, and adding a cycle consistency loss [64] that encourages F(G(x)) ≈ x and G(F(y)) ≈ y. Combining this loss with adversarial losses on domains X and Y yields their full objective for unpaired image-to-image translation. they apply their method to a wide range of applications, including collection style transfer, object transfiguration, season transfer and photo enhancement. they also compare against previous approaches that rely either on hand-defined factorizations of style and content, or on shared embedding functions, and show that their method outperforms these baselines. They provide both PyTorch and Torch implementations. Check out more results at their website.</p><p>The key to GANs’ success is the idea of an adversarial loss that forces the generated images to be, in principle, indistinguishable from real photos. This loss is particularly powerful for image generation tasks, as this is exactly the objective that much of computer graphics aims to optimize. they adopt an adversarial loss to learn the mapping such that the translated images cannot be distinguished from images in the target domain.</p><p><strong>Image-to-Image Translation</strong></p><p>The idea of image-to-image translation goes back at least to Hertzmann et al.’s Image Analogies, who employ a non-parametric texture model on a single input-output training image pair. More recent approaches use a dataset of input-output examples to learn a parametric translation function using CNNs. Their approach builds on the “pix2pix” framework of Isola et al., which uses a conditional generative adversarial network to learn a mapping from input to output images. Similar ideas have been applied to various tasks such as generating photographs from sketches or from attribute and semantic layouts. However, unlike the above prior work, they learn the mapping without paired training examples.</p><p><strong>Unpaired Image-to-Image Translation</strong></p><p>Several other methods also tackle the unpaired setting, where the goal is to relate two data domains: X and Y . Rosales et al. propose a Bayesian framework that includes a prior based on a patch-based Markov random field computed from a source image and a likelihood term obtained from multiple style images. More recently, CoGAN and cross-modal scene networks use a weight-sharing strategy to learn a common representation across domains. Concurrent to their method, Liu et al. extends the above framework with a combination of variational autoencoders and generative adversarial networks. Another line of concurrent work encourages the input and output to share specific “content” features even though they may differ in “style“. These methods also use adversarial networks, with additional terms to enforce the output to be close to the input in a predefined metric space, such as class label space, image pixel space, and image feature space.</p><p>Unlike the above approaches, their formulation does not rely on any task-specific, predefined similarity function between the input and output, nor do they assume that the input and output have to lie in the same low-dimensional embedding space. This makes their method a general-purpose solution for many vision and graphics tasks. they directly compare against several prior and contemporary approaches in Section 5.1.</p><p><strong>Cycle Consistency</strong></p><p>The idea of using transitivity as a way to regularize structured data has a long history. In visual tracking, enforcing simple forward-backward consistency has been a standard trick for decades. In the language domain, verifying and improving translations via “back translation and reconciliation” is a technique used by human translators (including, humorously, by Mark Twain), as well as by machines. More recently, higher-order cycle consistency has been used in structure from motion, 3D shape matching, cosegmentation, dense semantic alignment, and depth estimation. Of these, Zhou et al. and Godard et al. are most similar to their work, as they use a cycle consistency loss as a way of using transitivity to supervise CNN training. In this work, they are introducing a similar loss to push G and F to be consistent with each other. Concurrent with their work, in these same proceedings, Yi et al. independently use a similar objective for unpaired image-to-image translation, inspired by dual learning in machine translation.</p><p>Neural Style Transfer(one of the papers I read) is another way to perform image-to-image translation, which synthesizes a novel image by combining the content of one image with the style of another image (typically a painting) based on matching the Gram matrix statistics of pre-trained deep features. Their primary focus, on the other hand, is learning the mapping between two image collections, rather than between two specific images, by trying to capture correspondences between higher-level appearance structures. Therefore, their method can be applied to other tasks, such as painting→ photo, object transfiguration, etc. where single sample transfer methods do not perform well. They compare these two methods in Section 5.2 of paper.</p><p>Their goal is to learn mapping functions between two domains X and Y given training samples {xi} N i=1 where xi ∈ X and {yj}M j=1 where yj ∈ Y1. They denote the data distribution as x ∼ pdata(x) and y ∼ pdata(y). Their model includes two mappings G : X → Y and F : Y → X. In addition, they introduce two adversarial discriminators DX and DY , where DX aims to distinguish between images {x} and translated images {F(y)}; in the same way, DY aims to discriminate between {y} and {G(x)}. Their objective contains two types of terms: adversarial losses for matching the distribution of generated images to the data distribution in the target domain; and cycle consistency losses to prevent the learned mappings G and F from contradicting each other.</p><p>They apply adversarial losses to both mapping functions. For the mapping function G : X → Y and its discriminator DY , they express the objective as:</p><p>LGAN(G, DY , X, Y ) = Ey∼pdata(y)[log DY (y)] + Ex∼pdata(x) [log(1 − DY (G(x))],(1)</p><p>where G tries to generate images G(x) that look similar to images from domain Y , while DY aims to distinguish between translated samples G(x) and real samples y. G aims to minimize this objective against an adversary D that tries to maximize it, i.e., minG maxDY LGAN(G, DY , X, Y ).</p><p>They introduce a similar adversarial loss for the mapping function F : Y → X and its discriminator DX as well: i.e., minF maxDX LGAN(F, DX, Y, X).</p><p>Adversarial training can, in theory, learn mappings G and F that produce outputs identically distributed as target domains Y and X respectively (strictly speaking, this requires G and F to be stochastic functions). However, with large enough capacity, a network can map the same set of input images to any random permutation of images in the target domain, where any of the learned mappings can induce an output distribution that matches the target distribution. Thus, adversarial losses alone cannot guarantee that the learned function can map an individual input xi to a desired output yi. To further reduce the space of possible mapping functions, they argue that the learned mapping cycle should be able to bring x back to the original image, i.e., x → G(x) → F(G(x)) ≈ x. They call this forward cycle consistency. Similarly, for each image y from domain Y , G and F should also satisfy backward cycle consistency: y → F(y) → G(F(y)) ≈ y. They incentivize this behavior using a cycle consistency loss:</p><p>Lcyc(G, F) = Ex∼pdata(x) [kF(G(x)) − xk1] + Ey∼pdata(y) [kG(F(y)) − yk1]. (2)</p><p>In preliminary experiments, they also tried replacing the L1 norm in this loss with an adversarial loss between F(G(x)) and x, and between G(F(y)) and y, but did not observe improved performance. The behavior induced by the cycle consistency loss can be observed: the reconstructed images F(G(x)) end up matching closely to the input images x.</p><p><strong>Loss Function</strong></p><p>Their full objective is:</p><p>L(G, F, DX, DY ) =LGAN(G, DY , X, Y ) + LGAN(F, DX, Y, X) + λLcyc(G, F), (3)</p><p>where λ controls the relative importance of the two objectives. They aim to solve:</p><p>G∗, F∗ = arg minG,FmaxDx,DY L(G, F, DX, DY ). (4)</p><p>Notice that their model can be viewed as training two “autoencoders”: they learn one autoencoder F ◦ G : X → X jointly with another G◦F : Y → Y . However, these autoencoders each have special internal structures: they map an image to itself via an intermediate representation that is a translation of the image into another domain. Such a setup can also be seen as a special case of “adversarial autoencoders” [34], which use an adversarial loss to train the bottleneck layer of an autoencoder to match an arbitrary target distribution. In their case, the target distribution for the X → X autoencoder is that of the domain Y .</p><p>In Section 5.1.4, they compare their method against ablations of the full objective, including the adversarial loss LGAN alone and the cycle consistency loss Lcyc alone, and empirically show that both objectives play critical roles in arriving at high-quality results. They also evaluate their method with only cycle loss in one direction and show that a single cycle is not sufficient to regularize the training for this under-constrained problem.</p><p><strong>Network Architecture</strong></p><p>Generator architectures</p><ol><li>They adopt the architecture for their generative networks from Johnson et al. who have shown impressive results for neural style transfer and superresolution. This network contains three convolutions, several residual blocks, two fractionally-strided convolutions with stride 1/2, and one convolution that maps features to RGB. They use 6 blocks for 128 × 128 images and 9 blocks for 256×256 and higher-resolution training images.</li><li>Similar to Johnson et al., they use instance normalization.</li><li>Let c7s1-k denote a 7×7 Convolution-InstanceNormReLU layer with k filters and stride 1. dk denotes a 3 × 3 Convolution-InstanceNorm-ReLU layer with k filters and stride 2. Reflection padding was used to reduce artifacts. Rk denotes a residual block that contains two 3 × 3 convolutional layers with the same number of filters on both layers. uk denotes a 3 × 3 fractional-strided-ConvolutionInstanceNorm-ReLU layer with k filters and stride 1/2.</li><li>The network with 6 residual blocks consists of:</li></ol><p>c7s1–64,d128,d256,R256,R256,R256,</p><p>R256,R256,R256,u128,u64,c7s1–3</p><ol><li>The network with 9 residual blocks consists of:</li></ol><p>c7s1–64,d128,d256,R256,R256,R256,</p><p>R256,R256,R256,R256,R256,R256,u128</p><p>u64,c7s1–3</p><p>Discriminator architectures</p><ol><li>For the discriminator networks they use 70 × 70 PatchGANs, which aim to classify whether 70 × 70 overlapping image patches are real or fake. Such a patch-level discriminator architecture has fewer parameters than a full-image discriminator and can work on arbitrarily sized images in a fully convolutional fashion.</li><li>Let Ck denote a 4 × 4 Convolution-InstanceNorm-LeakyReLU layer with k filters and stride 2. After the last layer, they apply a convolution to produce a 1-dimensional output.</li><li>They do not use InstanceNorm for the first C64 layer.</li><li>They use leaky ReLUs with a slope of 0.2.</li><li>The discriminator architecture is: C64-C128-C256-C512</li></ol><p><strong>Training Details</strong></p><p>They apply two techniques from recent works to stabilize their model training procedure:</p><ol><li>First, for LGAN (Equation 1), they replace the negative log likelihood objective by a least-squares loss [35]. This loss is more stable during training and generates higher quality results. In particular, for a GAN loss LGAN(G, D, X, Y ), they train the G to minimize Ex∼pdata(x) [(D(G(x)) − 1)2 ] and train the D to minimize Ey∼pdata(y) [(D(y) − 1)2 ] + Ex∼pdata(x) [D(G(x))2].</li><li>Second, to reduce model oscillation, they follow Shrivastava et al.’s strategy and update the discriminators using a history of generated images rather than the ones produced by the latest generators. They keep an image buffer that stores the 50 previously created images.</li><li>For all the experiments, they set λ = 10 in Equation 3.</li><li>They use the Adam solver with a batch size of 1.</li><li>All networks were trained from scratch with a learning rate of 0.0002.</li><li>In practice, they divide the objective by 2 while optimizing D, which slows down the rate at which D learns, relative to the rate of G.</li><li>They keep the same learning rate for the first 100 epochs and linearly decay the rate to zero over the next 100 epochs.</li><li>Weights are initialized from a Gaussian distribution N (0, 0.02).</li></ol><p>They first compare their approach against recent methods for unpaired image-to-image translation on paired datasets where ground truth input-output pairs are available for evaluation. They then study the importance of both the adversarial loss and the cycle consistency loss and compare their full</p><p>method against several variants. Finally, they demonstrate the generality of their algorithm on a wide range of applications where paired data does not exist. For brevity, they refer to their method as CycleGAN.</p><p>Using the same evaluation datasets and metrics as “pix2pix”, they compare their method against several baselines both qualitatively and quantitatively. The tasks include semantic labels↔photo on the Cityscapes dataset, and map↔aerial photo on data scraped from Google Maps. They also perform ablation study on the full loss function.</p><p><strong>Evaluation</strong></p><p>AMT perceptual studies On the map↔aerial photo task, they run “real vs fake” perceptual studies on Amazon Mechanical Turk (AMT) to assess the realism of their outputs. They follow the same perceptual study protocol from Isola et al., except they only gather data from 25 participants per algorithm they tested. Participants were shown a sequence of pairs of images, one a real photo or map and one fake (generated by their algorithm or a baseline), and asked to click on the image they thought was real. The first 10 trials of each session were practice and feedback was given as to whether the participant’s response was correct or incorrect. The remaining 40 trials were used to assess the rate at which each algorithm fooled participants. Each session only tested a single algorithm, and participants were only allowed to complete a single session. The numbers they report here are not directly comparable to those in [22] as their ground truth images were processed slightly differently 2 and the participant pool should only be used to compare their current method against the baselines (which were run under identical conditions), rather than against [22].</p><p>FCN score</p><p>Although perceptual studies may be the gold standard for assessing graphical realism, they also seek an automatic quantitative measure that does not require human experiments. For this, they adopt the “FCN score” from, and use it to evaluate the Cityscapes labels→photo task. The FCN metric evaluates how interpretable the generated photos are according to an off-the-shelf semantic segmentation algorithm (the fully-convolutional network, FCN,from [33]). The FCN predicts a label map for a generated photo. This label map can then be compared against the input ground truth labels using standard semantic segmentation metrics described below. The intuition is that if they generate a photo from a label map of “car on the road”, then they have succeeded if the FCN applied to the generated photo detects “car on the road”.</p><p>Semantic segmentation metrics</p><p>To evaluate the performance of photo→labels, they use the standard metrics from the Cityscapes benchmark, including per-pixel accuracy, per-class accuracy, and mean class Intersection-Over-Union (Class IOU).</p><p><strong>Baselines</strong></p><p>CoGAN</p><p>This method learns one GAN generator for domain X and one for domain Y , with tied weights on the first few layers for shared latent representations. Translation from X to Y can be achieved by finding a latent representation that generates image X and then rendering this latent representation into style Y .</p><p>SimGAN</p><p>Like their method, Shrivastava et al. uses an adversarial loss to train a translation from X to Y . The regularization term kx − G(x)k1 i s used to penalize making large changes at pixel level. Feature loss + GAN they also test a variant of SimGAN where the L1 loss is computed over deep image features using a pretrained network (VGG-16 relu4 2), rather than over RGB pixel values. Computing distances in deep feature space, like this, is also sometimes referred to as using a “perceptual loss”. BiGAN/ALI Unconditional GANs learn a generator G : Z → X, that maps a random noise z to an image x. The BiGAN and ALI propose to also learn the inverse mapping function F : X → Z. Though they were originally designed for mapping a latent vector z to an image x, they implemented the same objective for mapping a source image x to a target image y.</p><p>pix2pix</p><p>They also compare against pix2pix, which is trained on paired data, to see how close they can get to this “upper bound” without using any paired data.</p><p>For a fair comparison, they implement all the baselines using the same architecture and details as their method, except for CoGAN. CoGAN builds on generators that produce images from a shared latent representation, which is incompatible with their image-to-image network. they use the public implementation of CoGAN instead.</p><p>In Table 4 and Table 5, they compare against ablations of their full loss. Removing the GAN loss substantially degrades results, as does removing the cycle-consistency loss. They therefore conclude that both terms are critical to their results. they also evaluate their method with the cycle loss in only one direction: GAN + forward cycle loss Ex∼pdata(x) [kF(G(x))−xk1], or GAN + backward cycle loss Ey∼pdata(y) [kG(F(y))−yk1] (Equation 2) and find that it often incurs training instability and causes mode collapse, especially for the direction of the mapping that was removed.</p><p>Photo generation from paintings</p><p>For painting→photo, they find that it is helpful to introduce an additional loss to encourage the mapping to preserve color composition between the input and output. In particular, they adopt the technique of Taigman et al. [49] and regularize the generator to be near an identity mapping when real samples of the target domain are provided as the input to the generator: i.e., L identity(G, F) = Ey∼pdata(y)[kG(y) − yk1] + Ex∼pdata(x) [kF(x) − xk1].</p><p>To generate results, they passed images of width 512 pixels with correct aspect ratio to the generator network as input. The weight for the identity mapping loss was 0.5λ where λ was the weight for cycle consistency loss. they set λ = 10. The identity mapping loss helps preserve the color of the input paintings. Without L identity, the generator G and F are free to change the tint of input images when there is no need to.</p><p>For example, when learning the mapping between Monet’s paintings and Flickr photographs, the generator often maps paintings of daytime to photographs taken during sunset, because such a mapping may be equally valid under the adversarial loss and cycle consistency loss.</p><p><strong>Limitations and Discussion</strong></p><p>Although their method can achieve compelling results in many cases, the results are far from uniformly positive. Figure 17 of the paper shows several typical failure cases.</p><ol><li>On translation tasks that involve color and texture changes, as many of those reported above, the method often succeeds.</li><li>They have also explored tasks that require geometric changes, with little success. For example, on the task of dog→cat transfiguration, the learned translation degenerates into making minimal changes to the input. This failure might be caused by their generator architectures which are tailored for good performance on the appearance changes.</li><li>Handling more varied and extreme transformations, especially geometric changes, is an important problem for future work.</li><li>Some failure cases are caused by the distribution characteristics of the training datasets. For example, their method has got confused in the horse → zebra example, because their model was trained on the wild horse and zebra synsets of ImageNet, which does not contain images of a person riding a horse or zebra.</li><li>They also observe a lingering gap between the results achievable with paired training data and those achieved by their unpaired method. In some cases, this gap may be very hard — or even impossible — to close: for example, their method sometimes permutes the labels for tree and building in the output of the photos→labels task. Resolving this ambiguity may require some form of weak semantic supervision. Integrating weak or semi-supervised data may lead to substantially more powerful translators, still at a fraction of the annotation cost of the fully-supervised systems.</li></ol><p>Nonetheless, in many cases completely unpaired data is plentifully available and should be made use of. This paper pushes the boundaries of what is possible in this “unsupervised” setting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9a786aafd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML PAPER: PIX2PIX — TL;DR]]></title>
            <link>https://sneha-ghantasala.medium.com/ml-paper-pix2pix-tl-dr-9df8865a19d7?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9df8865a19d7</guid>
            <category><![CDATA[ml-paper-summary]]></category>
            <category><![CDATA[pix2pix]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 16:07:47 GMT</pubDate>
            <atom:updated>2020-12-27T17:03:30.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML PAPER: PIX2PIX — TL;DR</h3><blockquote>Research Paper: <a href="https://arxiv.org/abs/1611.07004">Image-to-Image Translation with Conditional Adversarial Networks</a></blockquote><blockquote>Paper published — 26th Nov 2018 — Berkeley AI Research (BAIR) Laboratory, UC Berkeley</blockquote><p><em>Disclaimer: These are just notes and lot of the text is taken from the paper.</em></p><p>Earlier papers have focused on specific applications, and it has remained unclear how effective image-conditional GANs can be as a general-purpose solution for image-to-image translation.</p><p><strong>Contributions</strong></p><p>1. Primary contribution is to demonstrate that on a wide variety of problems, conditional GANs produce reasonable results.</p><p>2. Second contribution is to present a simple framework sufficient to achieve good results, and to analyze the effects of several important architectural choices. Code is available at <a href="https://github.com/phillipi/pix2pix">https://github.com/phillipi/pix2pix</a>.</p><p><strong>Related work</strong></p><p>1. Structured losses for image modeling Image-to-image translation problems are often formulated as per-pixel classification or regression</p><p>2. Conditional GANs — They are not the first to apply GANs in the conditional setting. Prior and concurrent works are tailored for a specific application. Their framework differs in that nothing is application specific. This makes their setup considerably simpler than most others.</p><p>3. Their method also differs from the prior works in several architectural choices for the generator and discriminator.</p><p>Unlike past work, for their generator they use a “U-Net”-based architecture, and for their discriminator they use a convolutional “PatchGAN” classifier, which only penalizes structure at the scale of image patches. A similar PatchGAN architecture was previously proposed to capture local style statistics. Here they show that this approach is effective on a wider range of problems, and they investigate the effect of changing the patch size.</p><p><strong>Loss Function</strong></p><p>GANs are generative models that learn a mapping from random noise vector z to output image y, G : z → y. In contrast, conditional GANs learn a mapping from observed image x and random noise vector z, to y, G : {x, z} → y.</p><p>The generator G is trained to produce outputs that cannot be distinguished from “real” images by an adversarially trained discriminator, D, which is trained to do as well as possible at detecting the generator’s “fakes”.</p><p>The objective of a conditional GAN can be expressed as</p><p>LcGAN (G, D) =Ex,y[log D(x, y)]+ Ex,z[log(1 − D(x, G(x, z))],</p><p>where G tries to minimize this objective against an adversarial D that tries to maximize it, i.e. G* = arg minG maxD LcGAN (G, D).</p><p>To test the importance of conditioning the discriminator, they also compare to an unconditional variant in which the discriminator does not observe x:</p><p>LGAN (G, D) =Ey[log D(y)]+ Ex,z[log(1 − D(G(x, z))]. (2)</p><p>Previous approaches have found it beneficial to mix the GAN objective with a more traditional loss, such as L2 distance. The discriminator’s job remains unchanged, but the generator is tasked to not only fool the discriminator but also to be near the ground truth output in an L2 sense. they</p><p>also explore this option, using L1 distance rather than L2 as L1 enctheirages less blurring:</p><p>LL1(G) = Ex,y,z[ky − G(x, z)k1].</p><p>Their final objective is</p><p>G* = arg minGmaxD LcGAN (G, D) + λLL1(G).</p><p>Without z (noise), the net could still learn a mapping from x to y, but would produce deterministic outputs, and therefore fail to match any distribution other than a delta function. Past conditional GANs have acknowledged this and provided Gaussian noise z as an input to the generator, in addition to x. In initial experiments, they did not find this strategy effective — the generator simply learned to ignore the noise — which is consistent with Mathieu et al.. Instead, for their final models, they provide noise only in the form of dropout, applied on several layers of their generator at both training and test time. Despite the dropout noise, they observe only minor stochasticity in the output of their nets. Designing conditional GANs that produce highly stochastic output, and thereby capture the full entropy of the conditional distributions they model, is an important question left open by the present work.</p><p><strong>Network Architecture</strong></p><p>A defining feature of image-to-image translation problems is that they map a high resolution input grid to a high resolution output grid. In addition, for the problems they consider, the input and output differ in surface appearance, but both are renderings of the same underlying structure. Therefore, structure in the input is roughly aligned with structure in the output. They design the generator architecture around these considerations.</p><p>Generator — U-Net</p><p>Many previous solutions to problems in this area have used an encoder-decoder network. In such a network, the input is passed through a series of layers that progressively downsample, until a bottleneck layer, at which point the process is reversed. Such a network requires that all information flow pass through all the layers, including the bottleneck. For many image translation problems, there is a great deal of low-level information shared</p><p>between the input and output, and it would be desirable to shuttle this information directly across the net. For example, in the case of image colorization, the input and output share the location of prominent edges. To give the generator a means to circumvent the bottleneck for information like this, they add skip connections, following the general shape of a “U-Net”. Specifically, they add skip connections between each layer i and layer n − i, where n is the total number of layers. Each skip connection simply concatenates all channels at layer i with those at layer n − i.</p><p>Discriminator — Markovian discriminator (PatchGAN)</p><p>It is well known that the L2 loss — and L1 — produces blurry results on image generation problems. Although these losses fail to encourage high-frequency crispness, in many cases they nonetheless accurately capture the low frequencies. For problems where this is the case, they do not need an entirely new framework to enforce correctness at the low frequencies. L1 will already do.</p><p>This motivates restricting the GAN discriminator to only model high-frequency structure, relying on an L1 term to force low-frequency correctness. In order to model high-frequencies, it is sufficient to restrict their attention to the structure in local image patches. Therefore, they design a discriminator architecture — which they term a PatchGAN — that only penalizes structure at the scale of patches. This discriminator tries to classify if each N×N patch in an image is real or fake. They run this discriminator convolutionally across the image, averaging all responses to provide the ultimate output of D. They demonstrate that N can be much smaller than the full size of the image and still produce high quality results. This is advantageous because a smaller PatchGAN has fewer parameters, runs faster, and can be applied to arbitrarily large images.</p><p><strong>Optimizations, Training Network</strong></p><p>Training phase:</p><p>1. To optimize their networks, they follow the standard approach: they alternate between one gradient descent step on D, then one step on G.</p><p>2. As suggested in the original GAN paper, rather than training G to minimize log(1 − D(x, G(x, z)), they instead train to maximize log D(x, G(x, z)). 3. In addition, they divide the objective by 2 while optimizing D, which slows down the rate at which D learns relative to G.</p><p>4. They use minibatch SGD and apply the Adam solver, with a learning rate of 0.0002, and momentum parameters β1 = 0.5, β2 = 0.999.</p><p>Testing phase:</p><p>At inference time, they run the generator net in exactly the same manner as during the training phase. This differs from the usual protocol in that:</p><p>1. They apply dropout at test time</p><p>2. They apply batch normalization using the statistics of the test batch, rather than aggregated statistics of the training batch. This approach to batch normalization, when the batch size is set to 1, has been termed “instance normalization” and has been demonstrated to be effective at image generation tasks. In their experiments, they use batch sizes between 1 and 10 depending on the experiment.</p><p>Data requirements and Speed</p><p>1. They note that decent results can often be obtained even on small datasets.</p><p>2. Their facade training set consists of just 400 images (see results in paper)</p><p>3. The day to night training set consists of only 91 unique webcams (see results in paper). On datasets of this size, training can be very fast: for example, the results shown in Figure 14 of paper took less than two hours of training on a single Pascal Titan X GPU.</p><p>4. At test time, all models run in well under a second on this GPU.</p><p>Experiments to test generality of conditional GAN</p><p>• Semantic labels↔photo, trained on the Cityscapes dataset.</p><p>• Architectural labels→photo, trained on CMP Facades.</p><p>• Map↔aerial photo, trained on data scraped from Google Maps.</p><p>• BW→color photos.</p><p>• Edges→photo, trained on data from [65] and [60]; binary edges generated using the HED edge detector plus postprocessing.</p><p>• Sketch→photo: tests edges→photo models on human drawn sketches.</p><p>• Day→night.</p><p>• Thermal→color photos.</p><p>• Photo with missing pixels→inpainted photo, trained on Paris StreetView.</p><p><strong>Evaluation metrics</strong></p><p>Evaluating the quality of synthesized images is an open and difficult problem. Traditional metrics such as perpixel mean-squared error do not assess joint statistics of the result, and therefore do not measure the very structure that structured losses aim to capture.</p><p>To more holistically evaluate the visual quality of their results, they employ two tactics.</p><ol><li>First, they run “real vs. fake” perceptual studies on Amazon Mechanical Turk (AMT). For graphics problems like colorization and photo generation, plausibility to a human observer is often the ultimate goal. Therefore, they test their map generation, aerial photo generation, and image colorization using this approach confirming the hypothesis that L1 encourages average, grayish colors. Using a cGAN, on the other hand, pushes the output distribution closer to the ground truth.</li><li>Second, they measure whether or not their synthesized cityscapes are realistic enough that off-the-shelf recognition system can recognize the objects in them. This metric is similar to the “inception score”, the object detection evaluation, and the “semantic interpretability” measures.</li><li>“FCN-score” While quantitative evaluation of generative models is known to be challenging, recent works have tried using pre-trained semantic classifiers to measure the discriminability of the generated stimuli as a pseudo-metric. The intuition is that if the generated images are realistic, classifiers trained on real images will be able to classify the synthesized image correctly as well. To this end, they adopt the popular FCN-8s architecture for semantic segmentation, and train it on the cityscapes dataset. They then score synthesized photos by the classification accuracy against the labels these photos were synthesized from.</li></ol><p><strong>Results</strong></p><p>FCN scores suggest:</p><p>1. Patch size of 70 * 70 produce best results.</p><p>2. Loss function with cGAN + L1 produces best results.</p><p>3. Unet architecture of Generator produces better results than encoder-decoder architecture.</p><p><strong>Conclusion</strong></p><ol><li>Conditional GANs appear to be effective on problems where the output is highly detailed or photographic, as is common in image processing and graphics tasks. What about vision problems, like semantic segmentation, where the output is instead less complex than the input? To begin to test this, they train a cGAN (with/without L1 loss) on cityscape photo→labels. The paper reports qualitative results, and quantitative classification accuracies. Interestingly, cGANs, trained without the L1 loss, are able to solve this problem at a reasonable degree of accuracy. To their knowledge, this is the first demonstration of GANs successfully generating “labels”, which are nearly discrete, rather than “images”, with their continuous valued variation. Although cGANs achieve some success, they are far from the best available method for solving this problem: simply using L1 regression gets better scores than using a cGAN, as shown in Table 6 of the paper. They argue that for vision problems, the goal (i.e. predicting output close to the ground truth) may be less ambiguous than graphics tasks, and reconstruction losses like L1 are mostly sufficient.</li><li>The results in this paper suggest that conditional adversarial networks are a promising approach for many image-to-image translation tasks, especially those involving highly structured graphical outputs. These networks learn a loss adapted to the task and data at hand, which makes them applicable in a wide variety of settings.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9df8865a19d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML PAPER: PROGRESSIVE GANs — TL;DR]]></title>
            <link>https://sneha-ghantasala.medium.com/ml-paper-progressive-gans-tl-dr-f89c7d4b282e?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89c7d4b282e</guid>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[ml-paper-summary]]></category>
            <category><![CDATA[progressive-gan]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 15:59:48 GMT</pubDate>
            <atom:updated>2020-12-27T17:04:59.708Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML PAPER: PROGRESSIVE GANs — TL;DR</h3><blockquote>Research paper: “<a href="https://arxiv.org/abs/1710.10196">PROGRESSIVE GROWING OF GANS FOR IMPROVED QUALITY, STABILITY, AND VARIATION</a>”</blockquote><blockquote>Paper published — 26th Feb 2018— by Nvidia</blockquote><p><em>Disclaimer: These are just notes and lot of the text is taken from the paper.</em></p><p>They describe a new training methodology for generative adversarial networks. The key idea is to grow both the generator and discriminator progressively: starting from a low resolution, they add new layers that model increasingly fine details as training progresses. This both speeds the training up and greatly stabilizes it, allowing it to produce images of unprecedented quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eEFYRviz4PoD_fkk" /><figcaption>Image Taken from the Research Paper</figcaption></figure><ol><li>Total trainable params in generator: 23.1M, Total trainable params in discriminator: 23.1M</li><li>Both networks consist mainly of replicated 3-layer blocks that are introduced one by one during the course of the training. The last Conv 1 × 1 layer of the generator corresponds to the toRGB block, and the first Conv 1 × 1 layer of the discriminator similarly corresponds to fromRGB. They start with 4 × 4 resolution and train the networks until they have shown the discriminator 800k real images in total. They then alternate between two phases: fade in the first 3-layer block during the next 800k images, stabilize the networks for 800k images, fade in the next 3-layer block during 800k images, etc.</li><li>Their latent/noise vectors correspond to random points on a 512-dimensional hypersphere, and they represent training and generated images in [-1,1].</li><li>Activation functions: leaky ReLU with leakiness 0.2 in all layers of both networks, except for the last layer that uses linear activation</li><li>No batch normalization, layer normalization, or weight normalization in either network, but they perform pixelwise normalization of the feature vectors after each Conv 3×3 layer in the generator</li><li>Initialization — all bias parameters to zero and all weights according to the normal distribution with unit variance. However, they scale the weights with a layer-specific constant at runtime.</li><li>They inject the across-minibatch standard deviation as an additional feature map at 4 × 4 resolution toward the end of the discriminator</li><li>The upsampling and downsampling operations correspond to 2 × 2 element replication and average pooling, respectively</li><li>Optimizer — Adam (Kingma &amp; Ba, 2015) with α = 0.001, β1 = 0, β2 = 0.99, and epsilon=10−8</li><li>Do not use any learning rate decay or rampdown</li><li>For visualizing generator output at any given point during the training, they use an exponential running average for the weights of the generator with decay 0.999.</li><li>They use a minibatch size 16 for resolutions 4*4–128*128 and then gradually decrease the size according to 256*256 → 14, 512*512 → 6, and 1024*1024 → 3 to avoid exceeding the available memory budget</li><li>Loss function — WGAN-GP loss, but unlike Gulrajani et al. (2017), they alternate between optimizing the generator and discriminator on a per-minibatch basis, i.e., they set ncritic = 1</li><li>Additionally, they introduce a fourth term into the discriminator loss with an extremely small weight to keep the discriminator output from drifting too far away from zero. To be precise, it sets new L = L + episilon_driftEx∈Pr[square(D(x))], where epsilon_drift =0.001.</li><li>The results of this network are independent of loss functions</li><li>To meaningfully demonstrate their results at high output resolutions, they need a sufficiently varied high-quality dataset. However, virtually all publicly available datasets previously used in GAN literature are limited to relatively low resolutions ranging from 32*32 to 480*480. To this end, they created a high-quality version of the CELEBA dataset consisting of 30000 of the images at 1024 × 1024 resolution.</li><li>Trained the network on 8 Tesla V100 GPUs for 4 days, after which they no longer observed qualitative differences between the results of consecutive training iterations. Their implementation used an adaptive minibatch size depending on the current output resolution so that the available memory budget was optimally utilized.</li><li>In order to demonstrate that their contributions are largely orthogonal to the choice of a loss function, they also trained the same network using LSGAN loss instead of WGAN-GP loss.</li><li>The best inception scores for CIFAR10 (10 categories of 32 × 32 RGB images) they are aware of are 7.90 for unsupervised and 8.87 for label conditioned setups (Grinblat et al., 2017). The large difference between the two numbers is primarily caused by “ghosts” that necessarily appear between classes in the unsupervised setting, while label conditioning can remove many such transitions. When all of their contributions are enabled, they get 8.80 in the unsupervised setting.</li><li>They find that LSGAN is generally a less stable loss function than WGAN-GP, and it also has a tendency to lose some of the variation towards the end of long runs. Thus they prefer WGAN-GP, but have also produced high-resolution images by building on top of LSGAN.</li><li>They need one additional hack with LSGAN that prevents the training from spiraling out of control when the dataset is too easy for the discriminator, and the discriminator gradients are at risk of becoming meaningless as a result. They adaptively increase the magnitude of multiplicative Gaussian noise in discriminator as a function of the discriminator’s output. The noise is applied to the input of each Conv 3 × 3 and Conv 4 × 4 layer. There is a long history of adding noise to the discriminator, and it is generally detrimental for the image quality (Arjovsky et al., 2017) and ideally one would never have to do that, which according to their tests is the case for WGAN-GP (Gulrajani et al., 2017). The magnitude of noise is determined as 0.2 · max(0,ˆdt − 0.5)2, where ˆdt = 0.1d + 0.9ˆdt−1 is an exponential moving average of the discriminator output d. The motivation behind this hack is that LSGAN is seriously unstable when d approaches (or exceeds) 1.0.</li><li>Creating the CELEBA-HQ dataset — They start with a JPEG image from the CelebA in the-wild dataset. They improve the visual quality through JPEG artifact removal using a convolutional autoencoder trained to remove JPEG artifacts in natural images and increases resolution using an adversarially-trained 4x super-resolution network. They then extend the image through mirror padding and Gaussian filtering to produce a visually pleasing depth-of-field effect. Finally, they use the facial landmark locations to select an appropriate crop region and perform high-quality resampling to obtain the</li><li>They perform the above processing for all 202599 images in the dataset, analyze the resulting 1024 ×1024 images further to estimate the final image quality, sort the images accordingly, and discard all but the best 30000 images. They use a frequency-based quality metric that favors images whose power spectrum contains a broad range of frequencies and is approximately radially symmetric. This penalizes blurry images as well as images that have conspicuous directional features due to, e.g., visible halftoning patterns. They selected the cutoff point of 30000 images as a practical sweet spot between variation and image quality, because it appeared to yield the best results. final image at 1024 × 1024 resolution.</li></ol><p>24. CIFAR10 RESULTS — no data augmentation used</p><p>25. Datasets trained/tested on — CELEBA-HQ, LSUN, CIFAR10, MNIST-1K</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89c7d4b282e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML PAPER: NEURAL STYLE TRANSFER — TL;DR]]></title>
            <link>https://sneha-ghantasala.medium.com/ml-paper-neural-style-transfer-tl-dr-b2bafa5ceaa?source=rss-872faa985ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2bafa5ceaa</guid>
            <category><![CDATA[ml-research-paper-summary]]></category>
            <category><![CDATA[style-transfer-paper]]></category>
            <category><![CDATA[neural-style-transfer]]></category>
            <dc:creator><![CDATA[Sneha Ghantasala]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 15:54:46 GMT</pubDate>
            <atom:updated>2020-12-27T17:06:08.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML PAPER: NEURAL STYLE TRANSFER — TL;DR</h3><blockquote>Research paper: “<a href="https://arxiv.org/abs/1508.06576">A Neural Algorithm of Artistic Style</a>” by Leon A. Gatys, et. al published on September 2, 2015.</blockquote><p><em>Disclaimer: These are just notes and lot of the text is taken from the paper.</em></p><p>The paper describes and formulates Neural Style Transfer. Its main takeaway is an algorithmic understanding of how neural representations can independently capture the content and style of an image. It has described a method for synthesizing images that mix content and style from different sources. This independence has been mathematically formulated in the loss function which is the sum of both the content loss and style loss. The paper has described the style of an image as the general texture and has referenced this definition.</p><p>The paper has combined the following ideas described in various other papers elegantly:</p><p>1. Using trained VGG networks (trained for object recognition) to get encodings for images for content comparisons between images.</p><p>2. Using existing visualization techniques to visualize the information in intermediate layers by reconstructing the image from feature maps of that layer.</p><p>3. Using existing ideas and formulae for calculating the style of an image.</p><p>4. Relating the method of style computations to how neurons in the biological eye work.</p><p>The way an image is generated, as described by the paper, is as follows:</p><p>1. Initialize the generated image to a white noise image.</p><p>2. Improve the generated image’s content by comparing the activations of the content image and the generated image (of a chosen layer in the network) by passing these images separately through a trained VGG-19 network (A CNN which has very high accuracy rates for object recognition) and changing the pixel values using gradient descent (Content Loss function).</p><p>3. Improve the generated image’s style by minimizing the difference in gram matrices of the generated and style images. Gram matrices are feature correlations between the different filter responses of a layer in the CNN. The paper mentions that we could take a weighted sum of this loss for different layers for computing the Style Loss function. The style of the image is improved in every iteration using gradient descent as well.</p><p>4. The overall cost function is regulated by two parameters — alpha (α), beta (β) — and the ratio α/β is the emphasis on matching the content of the content image and the style of the style image.</p><p>The paper states that for image synthesis, replacing the max-pooling operation by average pooling improved the gradient flow and obtained slightly more appealing results. But there were no examples or metrics presented for the same.</p><p>Overall, the paper provides a fascinating tool to study the perception and neural representation of style and content-independent image appearance in general.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2bafa5ceaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>