<?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 Dinesh Ramasamy on Medium]]></title>
        <description><![CDATA[Stories by Dinesh Ramasamy on Medium]]></description>
        <link>https://medium.com/@iitmdinesh?source=rss-793255970350------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S7Lg_RVvI7Qn0fBc3Tl5LA.png</url>
            <title>Stories by Dinesh Ramasamy on Medium</title>
            <link>https://medium.com/@iitmdinesh?source=rss-793255970350------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:16:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iitmdinesh/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[LSH for Vector Search]]></title>
            <link>https://medium.com/@iitmdinesh/lsh-for-vector-search-8fbeb34d4526?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fbeb34d4526</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[retrieval]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 11:22:15 GMT</pubDate>
            <atom:updated>2023-09-28T20:53:11.353Z</atom:updated>
            <content:encoded><![CDATA[<p>It is well known that locality sensitive hashing (LSH) can be used for approximate nearest neighbor search (ANN) or vector search. Here we present how one actually constructs and uses LSH for cosine-similarity based vector search.</p><p>The basic idea is to take (normalized) random projections and then threshold them at some value in the range 0 ≤ threshold &lt; 1. Then we just take inner product of the thresholded random projections. Choosing threshold = 0 is known as <a href="https://www.cs.princeton.edu/courses/archive/spring04/cos598B/bib/CharikarEstim.pdf">SimHash</a> and is well-studied in literature. We present an extension that uses threshold &gt; 0 and therefore promotes higher sparsity which in turn makes the search algorithm faster. This also gives more room for parallelization, but at the cost of accuracy for items that are not very similar to the query (low cosine similarity), which we are anyways less interested in normally.</p><p>The threshold can be related to the sparsity (0 &lt; p ≤ 0.5) of the index through the dimensionality of the embedding (d) and the CDF of the standard normal distribution (see code below).</p><p>We now study the accuracy impact of choosing different sparsity factors (p) via examples. Suppose p = 0.5 (same setting as regular SimHash), we get the following scatter graph between true and LSH cosine similarities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MhJvaAFUCFJwWbYPv5Pew.png" /><figcaption>Scatter graph between actual and LSH cosine similarities for p = 0.5 (SimHash) is almost linear</figcaption></figure><p>Similarly when we set p = 0.025, we get the following scatter graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Obd8UwY2BCv-bXra6PCrMw.png" /><figcaption>Scatter graph between actual and LSH cosine similarities for p = 0.025 is less linear than SimHash (p=0.5), but the sparisty allows us to use more LSH projections thereby increasing recall (not shown here)</figcaption></figure><p>One can construct an LSH index using posting lists (like in regular search indices) in the following manner:</p><pre>from typing import Optional<br><br>import math<br>from operator import itemgetter<br><br>import torch<br>import torch.nn.functional as F<br><br>from scipy.special import ndtri<br><br><br>class LSHIndex:<br>    def __init__(self, d: int, p: float = 0.025):<br>        self.d = d<br>        self.p = p<br>        self.threshold = ndtri(1 - p) / math.sqrt(d)<br>        np = int(d / p)<br>        self.proj = F.normalize(torch.randn((d, np // 2)), p=2.0, dim=0)<br>        self.posting_lists = None<br>    <br>    def build_index(self, corpus: torch.Tensor):<br>        corpus = F.normalize(corpus, p=2.0, dim=-1)<br>        index_ = corpus @ self.proj<br>        index = torch.cat([index_ &gt; self.threshold, index_ &lt; -self.threshold], dim=-1)<br>        self.posting_lists = {}<br>        for i in range(index.size(1)):<br>            self.posting_lists[i] = index[:, i].nonzero().squeeze(1).tolist()<br>    <br>    def search(self, query: torch.Tensor, top_k: Optional[int] = None):<br>        &quot;&quot;&quot;<br>        Brute force complexity is size of corpus (n * d) times p (&lt;&lt; 1), <br>        which is already low, but with lots of room for parallelization<br>        &quot;&quot;&quot;<br>        query = F.normalize(query, p=2.0, dim=-1)<br>        projs = query @ self.proj<br>        terms = torch.cat([projs &gt; self.threshold, projs &lt; -self.threshold], dim=-1).nonzero().squeeze(1).tolist()<br>        # heavily parallelizable as len(terms) is approximately equal to d in this setting<br>        score = {}<br>        for term in terms:<br>            posting_list = self.posting_lists[term]<br>            # length of each postings list = p * size of corpus<br>            for doc_id in posting_list:<br>                score[doc_id] = score.setdefault(doc_id, 0) + 1<br>        <br>        result = [doc_id for doc_id, _ in sorted(score.items(), key=itemgetter(1), reverse=True)]<br>        <br>        if top_k is not None:<br>            result = result[:top_k]<br>        <br>        return result</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fbeb34d4526" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KFAdam: A Kalman filter based optimizer for de-noising SGD]]></title>
            <link>https://medium.com/@iitmdinesh/kfadam-a-kalman-filter-based-optimizer-for-de-noising-sgd-e87c8456e88d?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/e87c8456e88d</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 20:28:49 GMT</pubDate>
            <atom:updated>2023-09-17T15:01:02.235Z</atom:updated>
            <content:encoded><![CDATA[<p>Stochastic Gradient Descent (SGD) uses “<em>noisy”</em> estimates of the gradient to take steps towards the optimum. The steps typically are small and the full-batch gradient (the actual gradient) does not change too much between steps. In this case, one can smooth the gradient using past values of the gradient. One of the most parameter efficient ways to do this is via a single tap IIR filter (a.k.a EMA filter). This approach is also known as adding “momentum” to SGD.</p><pre>momemtum = (1-beta) * momemtum + beta * gradient<br>param = param - lr * momemtum</pre><p>This approach is the main idea behind most optimizers including the popular Adam algorithm. Most modern optimizers like Adam also use adaptive step sizes. They normally scale the learning rate by the inverse square root of an EMA average (or sum) of gradient squares. To be concrete here is the update equation for Adam optimizer</p><pre>STEP 1: momemtum = (1-beta1) * momemtum + beta1 * gradient<br>STEP 2: energy = (1-beta2) * energy + beta2 * gradient * gradient<br>STEP 3: param = param - lr * momemtum / (sqrt(energy) + eps)</pre><p>Adam is an ad-hoc rule that has been found to work well in practice. The game of using first and second order 1-tap IIR moments to estimate time varying quantities like gradients has been well studied in signal processing literature and is known as the Kalman Filter. Here we ask the following question?</p><blockquote>What if you can deploy a bank of Kalman filters to estimate the smoothed gradients? How can you use the estimated gradients in a neural network optimizer?</blockquote><p>We first present the optimizer before diving into the standard Kalman filter:</p><pre>STEP 1: estimate, estimate_variance = kalman_filter(gradient)<br>STEP 2: param = param - lr * estimate / (sqrt(estimate_variance + estimate ** 2) + eps)</pre><p>The term estimate / sqrt(estimate_variance + estimate ** 2) is the same as the Adam optimizer step size strategy.</p><p>The 1D Kalman filter with known process_variance and measurement_variance is fairly straightforward and is given below:</p><pre>prediction_variance = estimate_variance + process_variance<br>kalman_gain = prediction_variance / (eps + prediction_variance + measurement_variance)<br>innovation = gradient - estimate<br>estimate = prediction + kalman_gain * innovation<br>estimate_variance = (1.0 - kalman_gain) * prediction_variance</pre><p>We used the above Kalman filter based Adam-like optimizer with lr = 1e-4 and eps = 1e-6 and compared it against standard Adam optimizer with lr = 1e-4, betas = [0.9, 0.95] and eps = 1e-6 for training a <a href="https://medium.com/@iitmdinesh/recommender-systems-inspired-by-large-language-models-5693d55f683a">RecSys LLM</a> transformer model (<a href="https://arxiv.org/abs/2205.04507">PinnerFormer</a>-like model) and saw a 7% improvement in in-batch recall @ 50:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuFb_EleTcx97Ts516vHAg.png" /><figcaption>10% relative gain in hit rate at 50 for the KFAdam optimizer over the Adam optimizer on the RecSys LLM retrieval task</figcaption></figure><p>We give the PyTorch implementation for KFAdam for completeness in <a href="https://github.com/iitmdinesh/kf_adam/blob/main/kf_adam.py">https://github.com/iitmdinesh/kf_adam/blob/main/kf_adam.py</a></p><p>Note that the Kalman filtering is performed somewhat independently for each parameter. The filters however are tied to one another via their variance estimates for each parameter group. We also use the techniques in <a href="http://article.nadiapub.com/IJCA/vol10_no10/6.pdf">this article</a> to estimate the measurement and process variances on a parameter group level.</p><p>Finally, it is worth noting that the KFAdam optimizer needs 50% more memory than the traditional Adam optimizer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e87c8456e88d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LSH based sampling-bias correction for retrieval]]></title>
            <link>https://medium.com/@iitmdinesh/lsh-based-sampling-bias-correction-for-retrieval-e28fb12caf97?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28fb12caf97</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 23:19:29 GMT</pubDate>
            <atom:updated>2023-08-29T17:07:41.815Z</atom:updated>
            <content:encoded><![CDATA[<p>Retrieval models are employed to quickly generate candidates for more nuanced downstream processing in different settings like retrieval-augmented generation (RAG) and candidate generation for recommender systems to name a few. They work by embedding documents and queries into the same <em>n</em>-dimensional space <em>S</em>.</p><p>Normally one trains these models using in-batch negatives, which refers to the technique of using positive documents for other queries in the same mini-batch as negative documents for the query under consideration. Furthermore it is common-place to use contrastive loss on all available in-batch negatives as the loss function. The code snippet below shows how one typically trains a retrieval model [see <a href="https://github.com/tensorflow/recommenders/blob/v0.7.3/tensorflow_recommenders/tasks/retrieval.py#L160">TensorFlow Recommenders</a> for a reference implementation].</p><pre>temperature = 0.05<br>query_model = QueryModel(...).to(device)<br>document_model = DocumentModel(...).to(device)<br><br>batch = {...}<br><br>query_embedding = F.normalize(query_model(batch), p=2.0, dim=-1)<br>document_embedding = F.normalize(document_model(batch), p=2.0, dim=-1)<br><br>batch_size = query_embedding.size(0)<br><br>logits = query_embedding @ document_embedding.T / temperature<br>labels = torch.arange(0, batch_size, dtype=torch.int64, device=device)<br><br>loss = F.cross_entropy(logits, labels)</pre><p>Since popular query-document pairs (often asked question-answers for example) appear frequently in the training data, the corresponding documents appear as negatives often in the contrastive loss as well. But, the aim of the above loss function is to approximate the full softmax on the complete document corpus. In that ideal case, each document appears as a negative the same (=1) number of times as any other document. This disparity between the actual loss function and the ideal loss function is known to hurt the performance of the learnt retrieval model.</p><h3>Sampling-bias / log-Q correction</h3><p>In recommendation system literature, there is a well known method to correct this “bias.” This sampling-bias correction technique, also known as log-Q correction, is described in <a href="https://research.google/pubs/pub48840">this google paper</a>. The basic idea is to get a good approximation of the soft-max denominator (aka partition function) using the documents in the mini-batch:</p><pre>q = query_embedding<br>d_k = k-th document embedding<br>d_0 = correct document embedding<br><br>partition_function<br>= sum over the document corpus k(exp(&lt;q, d_k&gt; / T)<br>= exp(&lt;q, d_0&gt; / T) + sum over the negative document corpus(exp(&lt;q, d_k&gt; / T * Pr[d_k in mini-batch] / Pr[d_k in mini-batch])<br>~= exp(&lt;q, d_0&gt; / T) + sum over the minibatch negatives(exp(&lt;q, d_k&gt; / T) / Pr[d_k in mini-batch]<br>= exp(&lt;q, d_0&gt; / T) + sum over the minibatch negatives(exp(&lt;q, d_k&gt; / T - log(Pr[d_k in mini-batch]))</pre><p>This is the derivation of the <a href="https://research.google/pubs/pub50257">log-Q correction formula</a> and it utilizes the simple formula for the first moment. The updated training code looks like:</p><pre>eps = 1e-6<br>batch_size = query_embedding.size(0)<br><br>logits = query_embedding @ document_embedding.T / temperature<br>labels = torch.arange(0, batch_size, dtype=torch.int64, device=device)<br><br>log_candidate_sampling_prob = batch[&#39;log_candidate_sampling_prob&#39;].reshape(1, -1).repeat(batch_size, 1)<br># need to set the correction for the positive label to 0<br>log_candidate_sampling_prob.fill_diagonal_(0)<br><br>loss = F.cross_entropy(logits - log_candidate_sampling_prob, labels)</pre><p>This gives gains when the learnt embeddings are evaluated on the full corpus (using any standard ANN algorithm like <a href="https://arxiv.org/abs/1603.09320">HNSW</a> if the corpus is large). Now moving on to how one can estimate the <em>log_candidate_sampling_prob</em> column<em>.</em></p><h4>Estimating candidate sampling probability</h4><p>The standard approach is to estimate unigram probability of the document in the training corpus. If this probability is say <em>p </em>and the mini-batch size is <em>N</em>, the candidate sampling probability can be easily approximated using the formula: 1-(1-<em>p</em>)^<em>N.</em></p><p>Another popular approach is to estimate <em>log_candidate_sampling_prob</em> in a <a href="https://research.google/pubs/pub48840">streaming fashion using count-min sketch</a> (on the <em>document_id </em>column in the mini-batch).</p><pre>class StreamingLogQCorrectionModule(nn.Module):<br>    def __init__(<br>            self,<br>            num_buckets: int,<br>            hash_offset: int,<br>            alpha: float,<br>            p_init: float,<br>    ):<br>        super().__init__()<br>        self.num_buckets = num_buckets<br>        self.hash_offset = hash_offset<br>        self.alpha = alpha<br>        self.register_buffer(&#39;b&#39;, (1.0 / p_init) * torch.ones((num_buckets,), dtype=torch.float32))<br>        self.register_buffer(&#39;a&#39;, torch.zeros((num_buckets,), dtype=torch.long))<br><br>    def forward(self, document_ids: torch.LongTensor) -&gt; torch.Tensor:<br>        h = self.hash_fn(document_ids.view(-1))<br>        return - self.b[h].log().reshape(*document_ids.shape)<br><br>    def hash_fn(self, document_ids: torch.LongTensor) -&gt; torch.LongTensor:<br>        return (document_ids + self.hash_offset) % self.num_buckets<br><br>    def train_step(self, document_ids: torch.LongTensor, batch_idx: int) -&gt; None:<br>        h = self.hash_fn(document_ids).unique()<br>        self.b[h] = (1 - self.alpha) * self.b[h] + self.alpha * (batch_idx - self.a[h]).float()<br>        self.a[h] = batch_idx</pre><p>One typically cascades a bunch of these estimators like so:</p><pre>class CascadedStreamingLogQCorrectionModule(nn.Module):<br>    def __init__(<br>            self,<br>            num_buckets: int,<br>            hash_offsets: Tuple[int, ...],<br>            alpha: float,<br>            p_init: float,<br>    ):<br>        super().__init__()<br>        self.models = nn.ModuleList([<br>            StreamingLogQCorrectionModule(num_buckets, offset, alpha, p_init)<br>            for offset in hash_offsets<br>        ])<br><br>    def forward(self, document_ids: torch.LongTensor) -&gt; torch.Tensor:<br>        result = torch.empty((0,), device=document_ids.device)<br>        for i, mod in enumerate(self.models):<br>            if i == 0:<br>                result = mod(document_ids)<br>            else:<br>                result = torch.minimum(result, mod(document_ids))<br>        return result<br><br>    def train_step(self, document_ids: torch.LongTensor, batch_idx: int) -&gt; None:<br>        for mod in self.models:<br>            mod.train_step(document_ids, batch_idx)</pre><p>We should feed the <em>document_id</em> column and the batch index to the train_step method to update the running statistics of the log of the candidate sampling probability and <em>then</em> retrieve the log of the candidate sampling probability by calling the above cascaded streaming log-Q correction probability estimator module.</p><h3>Issues with log-Q correction</h3><p>What happens when the document corpus is very large? What if the document embeddings are not free parameters (like latent embeddings)? What if the document embeddings are the output of a content model like a LLM’s hidden state or a “sentence-transformer?” The log-Q correction values take a very large negative, approximately constant value for all documents. This hurts the log-approximation so much so that the model with no log-Q correction tends to perform better than the one with log-Q correction.</p><p>So how do we fix this? We utilize the fact that in such settings, the document embeddings are constrained to live on the <em>n</em>-dimensional space (typically the <em>n</em>-dimensional unit-sphere). There are only so many “approximately-unique” embeddings on the <em>n</em>-dimensional unit-sphere, especially for reasonably small sized <em>n</em>. So as far as the contrastive loss is concerned, we are grossly over-estimating the log-Q correction factor on the partition function if we use the regular log-Q correction formula. So we propose to use the position of the document embeddings on the unit-sphere to estimate the log-Q correction instead of using the document-id based estimation of the log-Q correction factor.</p><h3>Document embedding based log-Q correction</h3><p>We use the same CascadedStreamingLogQCorrectionModule to estimate the log-Q correction factor. However instead of using the <em>document_id</em> column as input to this estimator, we use the <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing">Locality Sensitive Hash</a> (LSH) of the document embedding to estimate the log-Q correction factor.</p><p>The LSH (of different resolutions) for the <em>n</em>-dimensional unit-sphere can be calculated using the following module with appropriate values for <em>n_proj</em> and <em>num_bins</em>:</p><pre>class LocalitySensitiveHashingModule(nn.Module):<br>    def __init__(self, emb_dim: int, n_proj: int, num_bins: int):<br>        super().__init__()<br>        self.register_buffer(<br>            &#39;projection_mat&#39;,<br>            F.normalize(torch.randn((emb_dim, n_proj)), p=2.0, dim=0),<br>            persistent=True,<br>        )<br>        resolution = 2.0 / num_bins<br>        self.register_buffer(<br>            &#39;grid&#39;,<br>            torch.linspace(-1, 1, num_bins + 1)[:-1] + 0.5 * resolution,<br>            persistent=True,<br>        )<br>        self.num_bins = num_bins<br><br>    def forward(self, x: torch.Tensor) -&gt; torch.Tensor:<br>        z = F.normalize(x, p=2.0, dim=-1) @ self.projection_mat<br>        z = torch.bucketize(z, self.grid).long()<br>        result = torch.empty((0,), device=x.device, dtype=torch.long)<br>        for i, t in enumerate(z.unbind(dim=-1)):<br>            if i == 0:<br>                result = t<br>            else:<br>                result = result * (1 + self.num_bins) + t<br>        return result</pre><p>This approach may result in even better ANN evaluation results on the whole corpus than the standard log-Q correction using <em>document_id</em>. It is not clear how the training dynamics evolve as the document model can also be trained along with the query model. In such cases, the memory parameter <em>alpha</em> in CascadedStreamingLogQCorrectionModule may need to be carefully tuned.</p><h3>References</h3><ul><li><a href="https://github.com/tensorflow/recommenders/blob/v0.7.3/tensorflow_recommenders/tasks/retrieval.py#L160">TensorFlow Recommenders</a></li><li><a href="https://research.google/pubs/pub48840">Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations</a></li><li><a href="https://research.google/pubs/pub50257">Mixed Negative Sampling for Learning Two-tower Neural Networks in Recommendations</a></li><li><a href="https://en.wikipedia.org/wiki/Count%E2%80%93min_sketch">Count-min sketch</a></li><li><a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing">Locality-sensitive hashing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28fb12caf97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with large vocabularies in Recommender Systems]]></title>
            <link>https://medium.com/@iitmdinesh/dealing-with-large-vocabularies-in-recommender-systems-bece00d2158?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/bece00d2158</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 16:49:07 GMT</pubDate>
            <atom:updated>2023-08-18T20:19:49.411Z</atom:updated>
            <content:encoded><![CDATA[<p>Most models use embedding tables to represent categorical features as vectors. Recommender Systems are no different: They need these tables to convert categorical features into vectors. But recommender systems need to operate with categorical features of very large vocabularies like user and item ID features. One of the most well-known ways to handle such large vocabularies is to train models with large embedding tables. This inflates the model size and demands a lot of work on making training and serving infrastructure work.</p><p>In this post, we describe how one can stay away from large RecSys models without compromising on the resulting model quality. We start by hashing IDs in an almost collision-free manner (Note that we may want all features to live in the same space. So we use feature names as seed to distinguish between two different features taking the same value).</p><pre>def hash_feature(feature_value: str, feature_name: str):<br>    seed = xxhash.xxh32(feature_name, 0).intdigest()<br>    return xxhash.xxh64(feature_value, seed).intdigest() - 2 ** 63</pre><p>We can then map these to embeddings using a different embedding tables or even a single embedding table (as the feature names have been used as seeds in the hash function) using techniques like <a href="https://arxiv.org/abs/1909.02107">QR</a>, <a href="https://arxiv.org/abs/2108.02191">ROBE</a>, etc., We prefer the following generalization of QR using bit-shift operations which is loosely inspired by <a href="https://arxiv.org/abs/2207.10731">this follow-up</a> paper from the authors of ROBE which we call K-Shift embedding:</p><pre>class KShiftEmbedding(nn.Module):<br>    def __init__(<br>            self,<br>            num_embeddings: int,<br>            emb_dim: int,<br>            num_shifts: int = 8,<br>            normalize_output: bool = True,<br>            sparse: bool = False,<br>    ):<br>        &quot;&quot;&quot;<br>        :param num_embeddings: Number of rows in the embedding table<br>        :param emb_dim: dimensionality of the embedding table<br>        :param num_shifts: Number of random access ops (k-shift ops / bit shift ops) =&gt; 2 shifts is comparable to<br>            QR embedding<br>        :param normalize_output: whether to normalize the output embeddings<br>        :param sparse: whether to use sparse gradients or not<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.emb = nn.Embedding(num_embeddings, emb_dim, sparse=sparse)<br>        self._num_embeddings = num_embeddings<br>        self._num_shifts = num_shifts<br>        self._num_bits = 64<br>        self._normalize_output = normalize_output<br><br>    def forward(self, id_: torch.LongTensor) -&gt; torch.Tensor:<br>        &quot;&quot;&quot;<br>        :param id_: any long in -2 ^ 63 to 2 ^ 63 - 1<br>        :return: embedding corresponding to the long<br>        &quot;&quot;&quot;<br>        tensors = []<br>        for col_idx in range(self._num_shifts):<br>            idx = self.get_row_idx(id_, col_idx)<br>            tensors.append(self.emb(idx))<br>        x = torch.stack(tensors, dim=-1).sum(dim=-1)<br>        if self._normalize_output:<br>            x = F.normalize(x, p=2.0, dim=-1)<br>        else:<br>            x = x / math.sqrt(self._num_shifts)<br>        return x<br><br>    # Some op to give pseudo-random multiple access to the embedding table<br>    def get_row_idx(self, x: torch.LongTensor, col_idx: int):<br>        if col_idx != 0:<br>            # closely mirrors bit rotation<br>            x = (x &lt;&lt; col_idx) | (x &gt;&gt; (self._num_bits - col_idx))<br>        return torch.remainder(x, self._num_embeddings)</pre><p>The embeddings thus derived can then be consumed by a model in the same form as they were before.</p><p>We can also use this module to memorize hashed ID to content embedding mappings. This allows us to keep an ID to content embedding mapping inside each model so that feature pipelines are not overloaded with content embeddings (which might change). More precisely we learn a model in the following way:</p><pre># content_embedding_df, columns hashed_id, embedding<br>expansion_factor = 1.15<br>num_shifts = 16<br>batch_size = 2 ** 18<br>emb_dim = 32<br>epochs = 500<br><br>x, y = torch.from_numpy(content_embedding_df[&#39;hashed_id&#39;].values).unsqueeze(1), <br>    F.normalize(torch.from_numpy(np.stack(content_embedding_df[&#39;embedding&#39;].values, axis=0)), p=2.0, dim=-1)<br>dataset = torch.utils.data.TensorDataset(x, y)<br>dataloader = torch.utils.data.DataLoader(<br>    dataset, <br>    batch_size=batch_size,<br>    shuffle=True,<br>)<br><br>model = nn.Sequential(<br>    KShiftEmbedding(<br>        int(expansion_factor * x.size(0)), <br>        emb_dim, <br>        num_shifts=num_shifts, <br>        normalize_output=True,<br>    ),<br>    nn.Linear(emb_dim, y.size(1), bias=False),<br>)<br>optim = torch.optim.Adagrad(<br>    model.parameters(),<br>    lr=5e-1,<br>)<br>criterion = nn.MSELoss()<br><br>for epoch in range(epochs):<br>    for input_this, target_this in dataloader:<br>        pred_this = F.normalize(model(input_this).squeeze(1), p=2.0, dim=-1)<br>        loss = criterion(pred_this, target_this)<br>        optim.zero_grad()<br>        loss.backward()<br>        optim.step()</pre><p>Its worth noting that we can “compress” embedding tables by setting expansion_factor &lt; 1, though we have not studied the space-savings versus accuracy tradeoff carefully. We can also compress in the PCA sense by setting emb_dim &lt; y.size(1), which we leave for further study as well.</p><p>We can also use an MLP cascaded on top of a smaller dimensional KShiftEmbedding model (say 4-dim) to learn OOV mappings using random IDs as negatives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bece00d2158" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LSH as a feature extractor]]></title>
            <link>https://medium.com/@iitmdinesh/lsh-as-a-feature-extractor-f3e39046f2d2?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3e39046f2d2</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 13:13:58 GMT</pubDate>
            <atom:updated>2023-08-14T23:46:43.996Z</atom:updated>
            <content:encoded><![CDATA[<p>Locality Sensitive Hashing (LSH) is typically used for approximate nearest neighbor (ANN) operations (vector search). The properties of LSH that make it very useful for vector search can also be exploited in neural network models that take vectors as input (for example content signals like audio, video and text embeddings in various settings). This is especially relevant in LLM settings where one wants to use one modality embeddings as “soft-prompts” for the LLM.</p><p>Typically manifolds that are input to a model in a specific domain are complicated (not i.i.d). This complexity makes it very hard to disentangle these manifolds using multi-layered perceptrons which are compute intensive operations. A classic trick to learn complex mappings is to memorize outcomes rather than learn functions. How do we memorize vector mappings? The obvious answer is to use embeddings, right? However, we need discrete objects to compute embeddings and vectors are not discrete. So how do we go about using embeddings for vector inputs? Well again the answer seems obvious: Hash the vectors — with the caveat that nearby points must remain “nearby” after hashing. This is exactly what LSH does. So we propose to use embedding models stacked on top of LSH ops as shallow feature extractors.</p><p>The choice of LSH algorithm and the manner in which the LSH buckets are converted into embeddings is very important. We present an algorithm that is only direction aware (ignores magnitudes of vectors, but this can be easily fixed) and is based on <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing#Stable_distributions">this simple LSH algorithm</a>:</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br><br>class CosineVectorEmbedding(nn.Module):<br>    &quot;&quot;&quot;<br>    LSH based vector indexer for highly non-linear ops<br>    &quot;&quot;&quot;<br><br>    def __init__(self, inp_dim: int, emb_dim: int, n_proj: int = 16, num_bins: int = 20):<br>        super().__init__()<br>        self.register_buffer(<br>            &#39;projection_mat&#39;,<br>            F.normalize(torch.randn((inp_dim, n_proj)), p=2.0, dim=0),<br>            persistent=True,<br>        )<br>        resolution = 2.0 / num_bins<br>        self.register_buffer(<br>            &#39;grid&#39;,<br>            torch.linspace(-1, 1, num_bins + 1)[:-1] + 0.5 * resolution,<br>            persistent=True,<br>        )<br>        self.register_buffer(<br>            &#39;pos_offset&#39;,<br>            ((num_bins + 1) * torch.arange(0, n_proj, dtype=torch.long)).long().reshape(-1, 1, 1),<br>            persistent=True,<br>        )<br>        self.emb = nn.EmbeddingBag(<br>            (num_bins + 1) * n_proj, <br>            emb_dim, <br>            mode=&#39;sum&#39;,<br>        )<br>        self.emb_dim = emb_dim<br>        self.n_proj = n_proj<br><br>    def forward(self, x):<br>        bs, seq_len, emb_dim = x.size()<br>        z = F.normalize(x, p=2.0, dim=-1) @ self.projection_mat<br>        z = torch.bucketize(z, self.grid).transpose(0, -1)<br>        z = (z + self.pos_offset).transpose(0, -1).contiguous()<br>        return self.emb(z.view(-1, self.n_proj)).reshape(bs, seq_len, self.emb_dim)</pre><p>To illustrate its effectiveness we show this can be used to train a <a href="https://medium.com/@iitmdinesh/recommender-systems-inspired-by-large-language-models-5693d55f683a">RecSys LLM</a> with input content embeddings that are 32 dimensional. We use a cascade of independent low-to-high resolution LSH embeddings (inp_dim = 32, emb_dim = 512, n_proj = 32, num_bins = (1, 2, 4, 8, 12, 16, 20)) and add their outputs. We compare this with using a simple projector (i.e., nn.Linear(32, 512)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRqeZwHkMhy4qVcOTsa89Q.png" /><figcaption>Val in-batch recall@50 as a function of number of user sequences seen. Blue (LSH) and orange (Linear).</figcaption></figure><p>Clearly, we see that CosineVectorEmbedding is a far better feature extractor than a simple linear transform (which is of course more parameter and compute efficient).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3e39046f2d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommender Systems inspired by Large Language Models]]></title>
            <link>https://medium.com/@iitmdinesh/recommender-systems-inspired-by-large-language-models-5693d55f683a?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/5693d55f683a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 01:05:48 GMT</pubDate>
            <atom:updated>2023-08-20T01:52:43.516Z</atom:updated>
            <content:encoded><![CDATA[<p>Recommender systems are designed to match users with items. Typically they are organized into two stages: (i) Retrieval (aka Candidate Generation) and (ii) Ranking as described in this classic YouTube <a href="https://research.google/pubs/pub45530/">paper</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecZ2RJ8sBdej1wWSYuBUbg.png" /><figcaption>Overview of a general recommender system architecture from YouTube paper in RecSys 2016</figcaption></figure><p>They rely heavily on feature engineering and digest a large number of features (in the order of thousands) per impression. This places a huge burden on training and serving infrastructure.</p><p>The nature of the problem dictates many feature pipelines and feature groups (i.e., collections of related features): For example, at the minimum one typically needs a user feature group, a few context feature groups and an item feature group. Furthermore, we need many more cross-feature groups (think how often the item was served during the 11AM — 12PM time window as opposed to the 6AM — 7AM time window; this is an item-context feature). Each feature group in turn typically contains multiple rolling window aggregation of events (like 1h, 6h, 1d, 7d, 14d, 30d, etc). Setting these feature groups for training and provisioning feature stores for serving is non-trivial. Ensuring the correctness of numerous pipelines backing these systems is a challenge in itself. Typically ML practitioners build features on intuition. It is very expensive to run ablation studies and isolate the useful features in each feature group. This contributes to quick feature bloat. Feature bloat and mismatch impacts cost and quality (latency, accuracy, etc) of recommender systems.</p><p>This is not too different from how one used to work with Language Models in the past: The general approach was to engineer many features (think <em>n-grams, entity extractors, etc</em>) and then hand them off to models that tease out information from these features. However, we have moved on to looking at a long sequence of text using transformer models and they work very well without any tailored feature engineering.</p><blockquote>Can we take inspiration from language models to make feature engineering minimal for recommender systems?</blockquote><p>We believe that it is possible and will save a lot of repetitive wasted effort in feature engineering. To do this we need to materialize all the metadata that was used to design the original features as input to the “RecSys LLM” in the form of user-level time-ordered aggregations (arrays). In typical settings, one would need a separate array for item IDs (since they are used as sparse features), arrays for context like location &amp; time and finally arrays for outcomes (like whether the item was liked, or the item was bought, etc) as all of these are typically used in feature aggregation. One can even input a sequence of content embeddings of the items. To keep the model general, one should not use user IDs in this LLM formulation. These feature sequences should be appropriately converted to embeddings and acted upon by a Causal Transformer Encoder. Such an architecture can mine features and feature-crosses through transformer layers.</p><blockquote>What are the challenges in building such an LLM?</blockquote><p>For scenarios like short-video recommendations the number of interesting events (typically positive interactions) can easily exceed thousands if the look back window for feature aggregation is 30 days (very typical). So feature fetching is not easy in the serving path. But, it is a solvable problem. Instead of retrieving 1000s of features, we now need to retrieve arrays of sizes in the 1000s for active users. We can combat this to an extent by limiting the “context window” to say 768. The transformer models built using this kind of features will also be somewhat slow, as they need to operate on long context windows (cost grows quadratically with window size).</p><p>But the nice thing is we can run the expensive part of the model (the causal transformer encoder) just once per user and reuse the cached results for all items that need to be ranked as part of each request (Of course this applies to the retrieval model as well as it anyway needs to run only once per request).</p><blockquote>How is this different from sequential recommendation models like BERT4Rec etc?</blockquote><p>From a high-level the ideas are similar. However sequential recommender models focus on the in-session setting and do not look at long contexts. Barring some early work like <a href="https://arxiv.org/abs/1808.09781">SASRec</a>, recent sequential recommender models like <a href="https://arxiv.org/abs/1904.06690">BERT4Rec</a> are not causal and hence may not be well suited for most settings. Most relevant to “RecSys LLM” proposed here is the offline <a href="https://arxiv.org/abs/2205.04507">Pinnerformer</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKGvCjfnWPLmJIEmVsyIYQ.png" /><figcaption>Pinnerformer architecture from Pinterest</figcaption></figure><blockquote>How can one pre-train such an RecSys LLM?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CDY4BIeb_zCEJF5hVhp0Q.png" /><figcaption>Pre-training a Recommender System LLM for retrieval task</figcaption></figure><p>While the basic ideas like causal targets and causal transformer encoder backbone are the same as training any LLM, there are some notable differences as explained below:</p><ul><li>The item ID space (analogous to tokenizer vocabulary) is typically very large (compared to ~40K for LLAMA-2 the active ID space for short form videos can be in the many millions). Rather than using a separate embedding for each unique ID, we encourage that you use QR/ROBE embeddings (or even better invent your own simple parameter sharing scheme that relies on some form of hashing like <a href="https://medium.com/@iitmdinesh/dealing-with-large-vocabularies-in-recommender-systems-bece00d2158">KShift</a>). This means that one does not need expensive and hard to maintain string indexer (like <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.StringIndexerModel.html">this one</a> in spark ml).</li><li>The output layer of the model cannot be logits that predict the next ID exactly for the same reason (large vocabulary, no string indexer, etc). We encourage the use of embeddings to represent the next ID and use contrastive loss between the model output sequence and the input item embedding sequence (detached) to ensure the model learns to predict the next ID accurately. Furthermore one can easily remove “accidental hits” [<a href="https://github.com/tensorflow/recommenders/blob/v0.7.3/tensorflow_recommenders/layers/loss.py#L114">link</a> for original form of this idea in TFRS] in this setting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLDWG8YFv6859qEcIcpb7A.png" /><figcaption>Special in-batch negatives loss for sequences</figcaption></figure><ul><li>We suggest adding content embedding sequences as inputs to the model to effectively deal with low-distribution content. To learn highly non-linear ops, we found it useful to use a cascade of increasing resolution LSH ops (non-learnable) followed by embedding layers (learnable) to align content embeddings with latent embeddings (see <a href="https://medium.com/@iitmdinesh/lsh-as-a-feature-extractor-f3e39046f2d2">this post</a> for more details on LSH embeddings)</li><li>Label sequences, embedding sequences and context sequences that have been input to the model can also be predicted in a causal manner to further improve model accuracy</li><li>Using left padding and reverse positional bias seems to help with predicting the next item</li></ul><p>The resulting model is an RecSys LLM model. If serving such a model in production settings is hard, we could batch-predict with the above “query” model to generate long-term user embeddings at a regular cadence and then use these long term user embeddings and recent interactions for more responsive retrieval and ranking models. The item model can be used to generate fine-grained embeddings of items as well. This scenario is studied in the Pinterest paper <a href="https://arxiv.org/abs/2306.00248">TransAct</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KA_emQ4ZkWSS_gn7ESgoQA.png" /><figcaption>Pinterest TransAct usage for home feed</figcaption></figure><p>In certain settings like e-commerce, where the number of orders in say a 6-month look back window is typically small, one may be able to also train an end-to-end retrieval and ranking model on top of this pre-trained model in one go and use it as is in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5693d55f683a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sparse transformers]]></title>
            <link>https://medium.com/@iitmdinesh/sparse-transformers-922e010bbd27?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/922e010bbd27</guid>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 02:05:26 GMT</pubDate>
            <atom:updated>2023-08-14T23:26:49.946Z</atom:updated>
            <content:encoded><![CDATA[<p>Transformer complexity grows quadratically with sequence length. Is there an easy way to reduce this dependency on sequence length? We try to answer this question using the following angle:</p><blockquote>Can we leverage the fact that a transformer encoder layers are typically stacked to form a deep transformer model?</blockquote><p>To see how depth can help us in reducing the dependency on the sequence length (or “width”) of a transformer encoder model, we need remind ourselves that a transformer encoder layer is a fully-connected graph where each edge is defined via dot-product between queries and keys. Stacking such fully connected layers means the final transformer encoder is also a fully connected graph. We now ask the following questions:</p><blockquote>Is it possible to sparsify this fully-connected graph at each stage and still maintain fully-connectedness on the end-to-end transformer encoder? Can we do this in a manner so that we can reduce the memory and compute footprint of the overall transformer encoder?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvjNawM9ZyKYQp7M6SttrA.png" /><figcaption>Can we induce sparsity at each layer and still ensure fully-connectedness for the overall transformer?</figcaption></figure><p>Firstly we remind ourselves that the compute complexity and memory footprint of a transformer encoder that operates on a B × L × E tensor is O(B(L²E + LE²)), where B is the batch size, L is the sequence length and E is the embedding dimensionality. Let us specifically focus on the setting where L &gt;&gt; E.</p><p>Now, let us consider the following sparse transformer architecture: We denote {0, 1, 2, …, L-1} by the set I. Let S be a random subset of I of size p × L, where 0 ≤ p ≤ 1. For positions i ∉ S, we set the output y(i) as x(i) + x(i) @ W, where x(i) is the input to the transformer and W is a learnable square matrix. For positions i ∈ S, we stack them up into a B × (pL) × E sized tensor and pass it through a fully connected transformer encoder layer. Assuming that L ≫ E, we have reduced the compute complexity and memory footprint of the transformer encoder layer by a factor p². Now we ask the question:</p><blockquote>How small can p be in relation to the depth D and width L of the transformer encoder for the graph induced by this sparse transformer to still be connected?</blockquote><p>Two positions i and j can talk to each other in a layer iff i and j both belong to the set Sₖ corresponding to the layer 0 ≤ k &lt; D. This can happen with probability p². So the positions i and j can talk to each other over the whole encoder iff 1-(1-p²)^D is large. Now setting p = sqrt(k/ D) for some k, we have probability of two positions talking as 1-(1–k/D)^D ≈ 1-exp(-p²D) for sufficiently large D.</p><p>Now there are L choose 2 ≈ L²/2 pairs of positions and for all of them to talk to each other, we need to ensure that L²exp(-p²D)/2 &lt; δ (for some small δ &lt;&lt; 1). So we can set</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*XXQbF8fVKSvLPDTs_YAjOw.png" /><figcaption>Scaling of sparsity with width L and depth D of sparse transformer</figcaption></figure><p>Putting numbers for <a href="https://huggingface.co/tiiuae/falcon-40b">falcon-40b</a> (L = 2048, D = 60) and setting δ = 0.1, we get p ≈ 53%, which means we can get an approximately 4X compute / memory savings by using simple sparse transformer. Now moving to the implementation:</p><pre>from typing import Optional<br><br>import numpy as np<br>import torch<br>import torch.nn as nn<br><br><br>class SparseTransformerEncoderLayer(nn.Module):<br>    def __init__(self,<br>                 mod: nn.TransformerEncoderLayer, <br>                 sparsity_factor: float, <br>                 n_embd: int,<br>                 max_block_size: int,<br>                 seed: Optional[int] = None):<br>        super().__init__()<br>        self.mod = mod<br>        self.null_connector = nn.Linear(n_embd, n_embd)<br>        self.sparsity_factor = sparsity_factor<br>        n_non_zeros = int(sparsity_factor * max_block_size)<br>        gen = np.random.Generator(np.random.PCG64(seed=seed)) if seed is not None else np.random.default_rng()<br>        full_mask = torch.tensor(gen.permutation(max_block_size), dtype=torch.long)<br>        self.register_buffer(<br>            &#39;input_mask_idx&#39;, <br>            full_mask[:n_non_zeros].sort().values, <br>            persistent=True,<br>        )<br>        self.register_buffer(<br>            &#39;input_mask_not_idx&#39;, <br>            full_mask[n_non_zeros:].sort().values, <br>            persistent=True,<br>        )<br>  <br>    def forward(self, <br>                x: torch.Tensor, <br>                src_mask: Optional[torch.Tensor] = None):<br>        T = x_orig.size(-2)<br>        idx = self.input_mask_idx[self.input_mask_idx &lt; T]<br>        if idx.size(0) &lt;= 1:<br>            # No interaction in this layer. Just return a perturbed identity<br>            return x_orig + self.null_connector(x_orig)<br>        x = x_orig[..., idx]<br>        src_mask = src_mask[..., idx, :][..., idx] if src_mask is not None else None<br>        x = self.mod(x, src_mask=src_mask)<br>        x_final = torch.zeros_like(x_orig)<br>        x_final[:, idx] = x<br>        # No interaction for these indexes. Just return a perturbed identity<br>        not_idx = self.input_mask_not_idx[self.input_mask_not_idx &lt; T]<br>        x_final[:, not_idx] = x_orig[:, not_idx] + self.null_connector(x_orig[:, not_idx])<br>        return x_final</pre><p>We see that by writing a small wrapper around the <a href="https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html">nn.TransformerEncoderLayer</a> class, we are able to reduce the compute &amp; memory footprint of a transformer encoder model (the architecture used by most generative models) by about 4X. This is somewhat different from the <a href="https://openai.com/research/sparse-transformer">sparse transformer architecture</a> proposed by OpenAI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922e010bbd27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving away from weight tuning for Multi-Task Learning models]]></title>
            <link>https://medium.com/@iitmdinesh/moving-away-from-weight-tuning-for-multi-task-learning-models-eecf75cc9ebc?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/eecf75cc9ebc</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[multi-task-learning]]></category>
            <category><![CDATA[multitask-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 18:00:03 GMT</pubDate>
            <atom:updated>2023-04-27T16:17:49.699Z</atom:updated>
            <content:encoded><![CDATA[<p>Multi-task learning (MTL) models are widely used in different settings like Large Language Models, Recommender Systems, Computer Vision, etc. The definition of an MTL model is one which has multiple outputs. These outputs have corresponding loss functions, which produce losses that are typically multiplied by different weights and added together. The performance of these models on each of the tasks depends greatly on these chosen weights and a great deal of computational (hyper-parameter optimization) effort goes in finding a combination of weights so that the performance of all the tasks is “good enough.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYRREzoi2UciKqzANxbxZg.png" /><figcaption>MTL model example with three tasks</figcaption></figure><p>These weights play an important role because some of the tasks might be very easy on average within a batch (for example sparse labels in binary classification tasks) and have very small gradients. Such tasks tend to perform very poorly in an MTL setting as the network converges to a point that is not favorable for them.</p><p>As an alternative to tuning weights via expensive hyper-parameter optimization, researchers have proposed methods to reduce the importance of weights in an MTL setting or remove them altogether. For example the authors of “Gradient Surgery for Multi-Task Learning” [<a href="https://arxiv.org/abs/2001.06782">paper</a>] suggest that one explicitly keeps track of gradients from each of the losses separately (multiple loss.backward() calls, which is expensive during training) and project out conflicting gradients from each of the tasks for the shared parameters. Another <a href="https://research.facebook.com/publications/metabalance-improving-multi-task-recommendations-via-adapting-gradient-magnitudes-of-auxiliary-tasks/">paper</a> from Meta proposes to look at the gradients corresponding to individual tasks and scale them up or down appropriately. This also requires that one make multiple loss.backward() calls during training.</p><p>Here we propose a simple solution that closely mirrors the above mentioned approaches: just normalize the gradients from each of the tasks where they are passed to the backbone network. We propose to do this without keeping track of individual gradients from each of the losses.</p><p>The main ingredient of the proposed approach is a torch autograd function that scales gradients during backward without impacting activations during forward:</p><pre>class _NormalizeGradients(torch.autograd.Function):<br>    &quot;&quot;&quot;<br>    Used to normalize gradients at any intermediate layer (especially in an MTL setting)<br>    Usage:<br>    if your code looks like:<br>        for output_name, mod in self.output_mlps.items():<br>            output[output_name] = mod(shared_representation)<br>    you may replace it with this simple hook to normalize gradients flowing into &quot;shared_representation&quot;<br>        for output_name, mod in self.output_mlps.items():<br>            output[output_name] = mod(normalize_gradients(shared_representation))<br>    &quot;&quot;&quot;<br>    @staticmethod<br>    def forward(ctx, input):<br>        return input<br><br>    @staticmethod<br>    def backward(ctx, grad_output):<br>        grad_input = None<br>        if ctx.needs_input_grad[0]:<br>            grad_input = grad_output / (torch.norm(grad_output) + 1e-6)<br>        return grad_input<br><br><br>normalize_gradients = _NormalizeGradients.apply</pre><p>Suppose one has a network that has the following backbone:</p><pre>class MTLModel(nn.Module):<br>    def __init__(self, ...):<br>        ...<br>        self.shared_model = ...<br>        self.task_specific_models = nn.ModuleDict({<br>            ...<br>        })<br>        ...<br><br>    def foward(self, inputs: torch.Tensor) -&gt; Dict[str, torch.Tensor]:<br>        shared_representation = self.shared_model(inputs)<br>        outputs = {}<br>        for task, mod in self.task_specific_models.items():<br>            outputs[task] = mod(shared_representation)<br>        return outputs</pre><p>and is trained like so (assuming that all tasks are binary classification tasks):</p><pre>model = MTLModel(...)<br>optim = torch.optim.Adam(model.parameters())<br>for batch, targets in dataloader:<br>    outputs = model(batch)<br>    loss = sum(F.binary_cross_entropy_with_logits(outputs[task], targets[task]) for task in outputs)<br>    loss.backward()<br>    optim.step()<br>    optim.zero_grad()</pre><p>The change we need to make to improve performance in this MTL setting is the following:</p><pre>class MTLModelWithGradientNormalization(nn.Module):<br>    def __init__(self, ...):<br>        ...<br>        self.shared_model = ...<br>        self.task_specific_models = nn.ModuleDict({<br>            ...<br>        })<br>        ...<br><br>    def foward(self, inputs: torch.Tensor) -&gt; Dict[str, torch.Tensor]:<br>        shared_representation = self.shared_model(inputs)<br>        outputs = {}<br>        for task, mod in self.task_specific_models.items():<br>            outputs[task] = mod(normalize_gradients(shared_representation))<br>        return outputs</pre><p>This would ensure that the gradients that are passed into the shared model are of equal magnitude from the different tasks and one does not need to fudge around with the loss weights (i.e., one can sum(losses) instead of weighting the losses).</p><p>Note: The resulting model is neither scriptable nor traceable. But this can be easily fixed by just adding an if statement. Also it may be necessary to use scale invariant optimizers like Adam when modifying gradients like this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eecf75cc9ebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SNRAdam: Improving the Adam Optimizer]]></title>
            <link>https://medium.com/@iitmdinesh/snradam-improving-the-adam-optimizer-95919f9e6e17?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/95919f9e6e17</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 03:14:04 GMT</pubDate>
            <atom:updated>2023-04-25T00:52:28.218Z</atom:updated>
            <content:encoded><![CDATA[<p>Optimizers are essential tools in the modeling stack. One of the most widely used optimizers is the Adam optimizer introduced by Kingma and Ba [<a href="https://arxiv.org/abs/1412.6980">paper</a>]. This optimizer keeps track of running averages of the gradient (aka momentum term) and the second moment (aka energy term) of the gradient using exponential moving average (EMA) filters and uses the square-root of the energy term to normalize the momentum term before taking a step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzbV1oVOXPYDM5oBe7Q-sA.png" /><figcaption>Implementation of Adam from <a href="https://pytorch.org/docs/stable/generated/torch.optim.Adam.html">PyTorch documentation</a></figcaption></figure><p>This seems like a good idea, right? For one it looks like a diagonal approximation of second order optimization and two, when the gradients are noisy, the denominator (square root of the energy term) is large relative to the numerator (momentum term) and steps are small. On the other hand when gradients are consistent, the denominator is approximately equal to the numerator, and we take constant sized steps equal to the learning rate γ. That’s why this optimizer is the de facto choice among ML researchers and practitioners.</p><p>Many variations of the Adam optimizer have been proposed and studied (see AdamW from <a href="https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html">PyTorch docs</a> and optimizers like QHAdam from the <a href="https://github.com/jettify/pytorch-optimizer/blob/master/torch_optimizer/qhadam.py">torch_optimizer package</a>). Here, we propose a variation that does not deviate from Adam significantly for noisy “recent” gradients but greatly amplifies the actual step size for parameters with a consistent “recent” gradient history (how recent depends on the EMA parameters β1 and β2).</p><p>Our modification is simple, yet effective: We replace the EMA filter of the gradient energy term with an EMA filter of the gradient variance term. This means final update equation θ(t) = θ(t-1) - γ * sqrt(SNR) * sign(momentum), where SNR refers to the signal-to-noise ratio of the “recent” gradient history (SNR is a term borrowed from signal processing literature and refers to the ratio of the average of the power in the noiseless signal to the variance of the noise in the signal). So parameters with a high SNR, i.e., with consistent “recent” gradient histories will see a much larger step size (as large as infinity if the gradient is constant) than those that have noisy “recent” gradient histories (or low gradient SNRs). The implementation of this optimizer is simple and is given below for completeness.</p><pre>from typing import Tuple<br><br>import torch<br>from torch.optim.optimizer import Optimizer<br><br><br>class SNRAdam(Optimizer):<br>    r&quot;&quot;&quot;Implements the SNRAdam optimization algorithm, which uses std deviation for the denominator rather than<br>    sqrt(energy) term used in conventional Adam. Why is this a good idea? If gradient stddev for a param is small, we<br>    should take larger steps as it means the gradient is consistent over time.<br><br>    Arguments:<br>        params: iterable of parameters to optimize or dicts defining<br>            parameter groups<br>        lr: learning rate (default: 1e-3)<br>        betas: coefficients used for computing<br>            running averages of gradient and its variance (default: (0.9, 0.999))<br>        eps: term added to the denominator to improve<br>            numerical stability (default: 1e-8)<br>        weight_decay: weight decay (L2 penalty) (default: 0)<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>            self,<br>            params,<br>            lr: float = 1e-3,<br>            betas: Tuple[float, float] = (0.9, 0.999),<br>            weight_decay: float = 0.0,<br>            eps: float = 1e-8,<br>    ):<br>        if lr &lt;= 0.0:<br>            raise ValueError(&#39;Invalid learning rate: {}&#39;.format(lr))<br>        if eps &lt; 0.0:<br>            raise ValueError(&#39;Invalid epsilon value: {}&#39;.format(eps))<br>        if not 0.0 &lt;= betas[0] &lt; 1.0:<br>            raise ValueError(<br>                &#39;Invalid beta parameter at index 0: {}&#39;.format(betas[0])<br>            )<br>        if not 0.0 &lt;= betas[1] &lt; 1.0:<br>            raise ValueError(<br>                &#39;Invalid beta parameter at index 1: {}&#39;.format(betas[1])<br>            )<br>        if weight_decay &lt; 0:<br>            raise ValueError(<br>                &#39;Invalid weight_decay value: {}&#39;.format(weight_decay)<br>            )<br><br>        defaults = {<br>            &#39;lr&#39;: lr,<br>            &#39;betas&#39;: betas,<br>            &#39;weight_decay&#39;: weight_decay,<br>            &#39;eps&#39;: eps,<br>        }<br>        super().__init__(params, defaults)<br><br>    def step(self, closure=None):<br>        &quot;&quot;&quot;Performs a single optimization step.<br><br>        Arguments:<br>            closure: A closure that reevaluates the model and returns the loss.<br>        &quot;&quot;&quot;<br>        loss = None<br>        if closure is not None:<br>            loss = closure()<br><br>        for group in self.param_groups:<br>            lr = group[&#39;lr&#39;]<br>            beta1, beta2 = group[&#39;betas&#39;]<br>            weight_decay = group[&#39;weight_decay&#39;]<br>            eps = group[&#39;eps&#39;]<br><br>            for p in group[&#39;params&#39;]:<br>                if p.grad is None:<br>                    continue<br><br>                d_p = p.grad.data<br>                if d_p.is_sparse:<br>                    raise RuntimeError(<br>                        &#39;SNRAdam does not support sparse gradients, &#39;<br>                        &#39;please consider SparseAdam instead&#39;<br>                    )<br><br>                state = self.state[p]<br><br>                if weight_decay != 0:<br>                    p.data.mul_(1 - lr * weight_decay)<br><br>                if len(state) == 0:<br>                    state[&#39;iter_&#39;] = 1<br>                    state[&#39;exp_avg&#39;] = torch.zeros_like(<br>                        p.data, memory_format=torch.preserve_format<br>                    )<br>                    state[&#39;exp_avg_sq&#39;] = torch.zeros_like(<br>                        p.data, memory_format=torch.preserve_format<br>                    )<br>                iter_ = state[&#39;iter_&#39;]<br>                exp_avg = state[&#39;exp_avg&#39;]<br>                if iter_ == 1:<br>                    d_sub_p_sq = d_p - exp_avg<br>                else:<br>                    d_sub_p_sq = d_p - exp_avg.mul(1.0 / (1 - beta1 ** (iter_ - 1)))<br>                d_sub_p_sq.mul_(d_sub_p_sq)<br><br>                exp_avg_sq = state[&#39;exp_avg_sq&#39;]<br><br>                exp_avg.mul_(beta1).add_(d_p, alpha=1.0 - beta1)<br>                exp_avg_sq.mul_(beta2).add_(d_sub_p_sq, alpha=1.0 - beta2)<br><br>                p.data.addcdiv_(exp_avg.mul(1.0 / (1 - beta1 ** iter_)),<br>                                exp_avg_sq.mul(1.0 / (1 - beta2 ** iter_)).sqrt() + eps, value=-lr)<br>                state[&#39;iter_&#39;] += 1<br><br>        return loss</pre><p>We ran experiments using a simple 100K parameter Vision Transformer model (loosely inspired by this <a href="https://medium.com/mlearning-ai/vision-transformers-from-scratch-pytorch-a-step-by-step-guide-96c3313c2e0c">medium post</a>) on the MNIST dataset with batch size 4096 over 20 epochs with learning rate 1e-3. The results point towards quick convergence for the proposed optimizer when compared to the Adam optimizer (we plot one of the runs but noticed the same behavior consistently for this model and dataset combination):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSL-N4qfs_Bhqs1L9DCumw.jpeg" /><figcaption>Training loss converges quickly for SNRAdam when compared to Adam</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASZ-9VD4aM5ugC6U2i-ufA.jpeg" /><figcaption>Validation loss converges quickly for SNRAdam when compared to Adam</figcaption></figure><p>In order to disentangle the source of the gains, we make the batch size = ∞ and compare the two algorithms. This shows whether the gains come from (i) correcting for the stochastic in “stochastic” gradient descent i.e., batch size being smaller than the full dataset size or (ii) the noise in the gradient coming from the optimization trajectory (the gradient descent portion). We see that the gains come from compensating for (ii):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEz3CUK1qJRApwKRcNCJJQ.jpeg" /><figcaption>Comparison of the two algorithms for batch-size = dataset size (train)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sS3TLhxquj9T4pKZkkEp6g.jpeg" /><figcaption>Comparison of the two algorithms for batch-size = dataset size (validation)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95919f9e6e17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastEmbed: How to compute efficient high dimensional PCA embeddings?]]></title>
            <link>https://medium.com/@iitmdinesh/fastembed-how-to-compute-efficient-high-dimensional-pca-embeddings-a6902bee5f76?source=rss-793255970350------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6902bee5f76</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Dinesh Ramasamy]]></dc:creator>
            <pubDate>Mon, 29 Jul 2019 16:10:21 GMT</pubDate>
            <atom:updated>2019-07-29T16:26:45.099Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a summary of the paper <a href="http://papers.nips.cc/paper/5992-compressive-spectral-embedding-sidestepping-the-svd">FastEmbed</a> [<a href="https://bitbucket.org/dineshkr/fastembed">python</a>] [<a href="https://bitbucket.org/dineshkr/fastembedspark">pyspark</a>]</p><p>SVD / PCA is a commonly used embedding technique for low dimensional datasets. The question we answer here is “How do you scale SVD / PCA to high dimensional datasets like social networks?”</p><h3>So what are SVD / PCA embeddings?</h3><p>We first construct a matrix <strong>M </strong>(with each row being an entry of the dataset). Then we call a standard SVD routine to obtain its decomposition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*da0vPdTB3E-Xgni0" /></figure><p>Using this <em>K</em>-dimensional decomposition, we obtain a <em>K</em>-dimensional embedding as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*A6dkf7Qa7UdU4tfb" /></figure><p>where the singular value weighting function <em>f</em>(.) is a hyper-parameter. The rows of this <em>K</em>-dimensional matrix are the embeddings of the rows of the input dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*Fuq-c57wHM5KzQVK" /></figure><h3>So why are SVD / PCA embeddings a good idea?</h3><p>Two main reasons why we use the SVD are dimensionality reduction and noise rejection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*hMQbs3JDjRL4IBlG" /></figure><p>Let’s look at graphs for another reason — Let <em>A</em> denote the adjacency matrix of the graph and <em>D</em> a diagonal matrix with the degree of each node on the diagonal. Then <em>L</em>=<em> D - A</em> is known as the graph Laplacian. The eigenvectors of this matrix reveals good cuts of the graph (partitions of the graph which intersect as few edges as possible).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*uLnU_a_GN4jNLJe2" /></figure><h3>So what is stopping us from using SVD / PCA for high dimensional datasets?</h3><p>The number of eigenvectors needed for high dimensional datasets also grows: For example, we expect a larger graph to have more clusters of densely connected nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*GC2sjMl15bmU_aEX" /></figure><p>This manifests itself as the need to compute more eigenvectors. Given that the data matrix <strong>M</strong> also grows with graph size, this means standard matrix factorization algorithms cannot solve the problem. Furthermore, these algorithms require that the entire matrix fit in one machine (which is not always the case).</p><h3>How do we get around these limitations?</h3><p>We ask the following question: Is there any thing that the SVD /PCA does beyond what we discussed so far?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*4DZqjJyIEB-0VNPQ" /></figure><p>The answer is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*i6UR-AWQ_180ynUM" /></figure><p>and we do not need this “compression” benefit of SVD / PCA for inference. Here is the summary of a typical workflow using the SVD for a <em>m </em>by <em>n</em> data matrix <strong>M</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*new3rDZjDn_jPJeZ" /></figure><p>Now that we have identified this, we ask the following question — How can we retain the benefits of SVD for inference while making it fast to compute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*jWr0QP-At7lEQo-0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HJ_g8IuWncJT1pXf" /></figure><p>The algorithm is as simple as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*IvPLaLNtqbcs4h6p" /></figure><h3>Results: Graph clustering</h3><p>A common task is to cluster the vertices of the graph so that related vertices belong to the same cluster — Illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*G1wY5JpjLGz3ZTJM" /></figure><p>A measure of the quality of the cluster is the <a href="https://en.wikipedia.org/wiki/Modularity_(networks)">network modularity score</a>. One can use embeddings to convert the vertices of the graph to vectors and then apply <em>k</em>-means to cluster the embeddings. Lets see how FastEmbed performs for this graph clustering task:</p><p><a href="https://snap.stanford.edu/data/amazon0302.html">Dataset</a>: Amazon co-purchasing network — directed graph of size 262,111 nodes and 1,234,877 edges (converted to undirected graph for this analysis)</p><p>We take a 40 dimensional embedding and cluster the graph using <em>k</em>-means with <em>k</em>=100:</p><ul><li>Standard eigen decomposition (PCA) with 40 dimensions <strong>modularity 0.26 (~45 minutes)</strong></li><li><a href="https://cs.stanford.edu/~jure/pubs/node2vec-kdd16.pdf">node2vec</a> (40 dimensional with default parameters) <strong>modularity 0.83 (~20 minutes)</strong></li><li>FastEmbed with <em>f</em>(λ) = 1 if abs(λ) &gt; 0.98 else 0<strong><br></strong>on Normalized Adjacency Matrix <strong>modularity 0.80 (~1 minute)</strong></li></ul><p>Note: Normalized Adjacency Matrix is n(u, v) = w(u, v) / sqrt(d(u) d(v)), where d(u) = sum(v) (w(u, v))</p><p>For more details refer the paper <a href="http://papers.nips.cc/paper/5992-compressive-spectral-embedding-sidestepping-the-svd">FastEmbed</a> [<a href="https://bitbucket.org/dineshkr/fastembed">python</a>] [<a href="https://bitbucket.org/dineshkr/fastembedspark">pyspark</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6902bee5f76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>