<?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 fishingalone on Medium]]></title>
        <description><![CDATA[Stories by fishingalone on Medium]]></description>
        <link>https://medium.com/@newhardwarefound?source=rss-9fa54ceff5fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4OfLpIoAiK3F1ZL5.jpg</url>
            <title>Stories by fishingalone on Medium</title>
            <link>https://medium.com/@newhardwarefound?source=rss-9fa54ceff5fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:22:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@newhardwarefound/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[Synthesize RAG evaluation sets]]></title>
            <link>https://medium.com/@newhardwarefound/synthesize-rag-evaluation-sets-6677cfc9dd58?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6677cfc9dd58</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[rag-evaluation]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 22:59:20 GMT</pubDate>
            <atom:updated>2025-06-24T23:07:11.760Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InNljL2Ozp5E2Hzdsqfbew.jpeg" /></figure><h4>How ragas generates synthetic questions using knowledge graph</h4><p>Our research into RAG quality evaluation led us to <a href="https://docs.ragas.io/en/stable/">ragas</a>, an open source library that can synthesize questions. However, ragas’ poor documentation hinders customization and undermines confidence in the tool. This article aims to clarify how ragas generates synthetic questions.</p><h3>Knowledge graph</h3><p>The knowledge graph is initialized with individual nodes, each containing a document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i3-FydYqpYu_ly8v" /></figure><p>These documents are chunked in a heading-aware manner. Ragas employs LLM to extract all level-2/3 headings from the document. The document is then split along the boundary of headings, with adjustments made to respect the token limits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zTT5rtR3k6Mws3gt" /></figure><p>Chunks are filtered based on the ease with which questions can be generated from them.</p><h3>Link graph nodes</h3><p>Finally, knowledge graph edges are constructed to link related documents and chunks. For documents, ragas prompts an LLM to summarize them and utilizes an embedding model to generate embeddings of these summaries. Document nodes are linked based on the cosine similarity of these summary embeddings.</p><p>For chunks, ragas prompts an LLM to extract entities from them and link chunks using the following algorithm:</p><ol><li>Given entities from 2 arbitrary chunks</li><li>Remove “noisy” entities that appear in almost all chunks</li><li>Assemble entities into N pairs</li><li>Calculate string similarity (Jaro-Winkler by default) on each pair, output true if the similarity exceeds a threshold and false otherwise</li><li>Link the 2 chunks if #(true)/N &gt; threshold</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*spoQvPtfbUiVllzj" /></figure><h3>Persona &amp; Scenario</h3><p>Questions are asked by people under certain circumstances. Before generating synthetic questions, ragas presents LLMs with realistic question-asking “scenarios”. According to ragas, a scenario is defined by 4 elements</p><ul><li>persona: an inquirer with a backstory</li><li>chunk(s) that the inquirer has questions about, i.e. knowledge graph node(s)</li><li>style: “misspelled queries”, “poor grammar”, “perfect grammar”, “web search like queries”</li><li>length: short, medium, long</li></ul><p>One can feed pre-crafted personas to Ragas. Alternatively, it can generate backstories for inquirers based on document summaries. The documents are clustered by cosine similarity of their summary embeddings, and an LLM is then prompted to generate personas using a representative summary from each cluster.</p><p>Ragas iterates through chunks and generate synthetic questions based on chunk/entity and randomly sampled combinations of persona/style/length.</p><h3>Multi-hop &amp; Abstract questions</h3><p>The preceding discussion focused on generating “single-hop” questions, which can be fully answered using information from a single document chunk. For this purpose, a knowledge graph — particularly its edges — is not required.</p><p>However, many questions are “multi-hop”, which requires cross-referencing information from different parts of a document to be answered. Ragas can generate 2-hop questions by taking 2 linked (as defined in the above section) chunks. LLM is then asked to generate questions using information from both chunks.</p><p>Ragas also supports generating multi-hop abstract questions. Instead of entities, it tries to extract “themes” (or “concepts”) from chunks and then combines them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6677cfc9dd58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a session-based recommender with graph neural networks]]></title>
            <link>https://medium.com/@newhardwarefound/build-an-session-based-recommender-with-graph-neural-networks-c42b5310baa1?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c42b5310baa1</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 18:20:22 GMT</pubDate>
            <atom:updated>2024-11-20T17:02:55.836Z</atom:updated>
            <content:encoded><![CDATA[<h4>a PyTorch Geometric implementation</h4><h3>Session-based recommender</h3><p>A session-based recommender (SBR) anticipates a user’s next choice based solely on what he already chooses in the current session. Without reliance on user information, SBR is particularly useful in situations where users prefer anonymity. It can further serve as basis for developing personalized recommenders.</p><p>In my previous <a href="https://medium.com/@newhardwarefound/transformer-based-sequential-recommender-part-1-efc887fdbca8">post</a>, I shared my experience developing an SBR with large language models. Recently I stumbled upon the potential of graph neural networks for building SBR. My experiment shows that GNN-based SBRs can deliver performance on par with LLM-based ones with less than 1/10th of parameter count.</p><h3>Session graph</h3><p>Let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*gPvYX42iS0eCn5H0MzC53Q.png" /></figure><p>be the set of all unique items users can pick. Each session</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*F6k0tzKdNFDR-UAfx6-sIg.png" /></figure><p>is a sequence of items in chronological order. We model any session as a directed graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*Y7OOVnCwHMKV89-msjwcnw.png" /></figure><p>where each vertex represents an item and each edge links an item to the next immediate item in the session.</p><p>We can combine several sessions together and draw a session graph for a batch of sessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*LR2-yq76caxtIoc2D5Posg.png" /><figcaption>modified from a diagram in paper “Self-Supervised Graph Co-Training for Session-based Recommendation”</figcaption></figure><h3>Graph Neural Networks</h3><p>Graph neural networks model each vertex as a d-dimensional vector (also called embedding). Embeddings are initialized to random numbers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*ADFOayf9GkX2sqWnd0rOLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euT-baeXrZU2Vox2x2XEzw.png" /><figcaption>Modified from <a href="https://syedarizvi.com/blog/2024/gnn-basics/">https://syedarizvi.com/blog/2024/gnn-basics/</a></figcaption></figure><p>A graph neural network layer outputs new embeddings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*NOqlIJgfDHJq8RmCd1WQbw.png" /></figure><p>by updating each vertex’s embedding with its neighbors’ embeddings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*OJDiqU4DUbIXSp3gzPj_gw.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*uX9wK8g6qX-9L4XWRtrgOQ.png" /></figure><p>is the neighborhood of vertex v.</p><p>Different aggregate rules yield different graph neural network models. In this problem, we use the graph attention networks GATv2Conv implemented by torch geometrics. Without going into too much detail, the graph attention network takes a weighted sum of neighbor embeddings whose weights are dynamically adjusted, followed by a non-linearity.</p><p>Here is an implementation</p><pre># based on Ruihong Qiu&#39;s implementation @ https://github.com/userbehavioranalysis/SR-GNN_PyTorch-Geometric<br>class GNNModel(nn.Module):<br>    &quot;&quot;&quot;<br>    Args:<br>        hidden_size: the number of units in a hidden layer.<br>        n_node: the number of items in the whole item set for embedding layer.<br>    &quot;&quot;&quot;<br>    def __init__(self, hidden_size, n_node):<br>        super(GNNModel, self).__init__()<br>        self.hidden_size, self.n_node = hidden_size, n_node<br>        self.embedding = nn.Embedding(self.n_node, self.hidden_size)<br>        self.gated = GATv2Conv(in_channels=self.hidden_size, out_channels=self.hidden_size, dropout=0.01)<br>        self.e2s = Embedding2Score(self.hidden_size)<br>        self.reset_parameters()<br>        <br>    def reset_parameters(self):<br>        stdv = 1.0 / math.sqrt(self.hidden_size)<br>        for weight in self.parameters():<br>            weight.data.uniform_(-stdv, stdv)<br><br>    def forward(self, data):<br>        x, edge_index, batch = data.x - 1, data.edge_index, data.batch<br><br>        embedding = self.embedding(x).squeeze()<br>        hidden2 = self.gated(embedding, edge_index)<br>        <br>  <br>        return self.e2s(hidden2, self.embedding, batch)</pre><h3>Session embedding</h3><p>We create an embedding for each session by weight summing the embeddings of items within the session. The weights are dynamically adjusted with an LLM-style gated linear unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*pQhUriQIOv2_YZww9ZF9Mg.png" /></figure><p>Here is where my approach differs from that in the paper “Session-based Recommendation with Graph Neural Networks”. The paper uses the same weight for all elements within an item embedding, which is less flexible than what I do above. To reach state-of-art performance, the paper also accentuates the last item by concatenating the last item embedding with the weight sum. The technique does not yield performance boost in my experiment.</p><h3>Predict the next item</h3><p>To predict the next item, a straightforward approach is linearly project the session embedding into the item space</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*_nqVC40ZWZH2hDbKTn0e2w.png" /></figure><p>like how it is typically done in large language models. However I find the approach underperforming the inner product approach, where a similarity score is calculated between session embedding and all item embeddings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*J1pWCI5GRwOjGZLenF0FzA.png" /></figure><p>In the end, we take softmax of similarity scores and calculate cross entropy as loss.</p><p>Here is an implementation</p><pre># based on Ruihong Qiu&#39;s implementation @ https://github.com/userbehavioranalysis/SR-GNN_PyTorch-Geometric<br>class Embedding2Score(nn.Module):<br>    def __init__(self, hidden_size):<br>        super(Embedding2Score, self).__init__()<br>        self.hidden_size = hidden_size<br>        self.W_2 = nn.Linear(self.hidden_size, self.hidden_size)<br>        self.W_3 = nn.Linear(self.hidden_size, self.hidden_size)<br>        <br>    def forward(self, session_embedding, all_item_embedding, batch):<br>        sections = torch.bincount(batch)<br>        <br>        alpha = torch.sigmoid(self.W_2(session_embedding))<br>        s_g_whole = alpha * session_embedding    # |V|_i * hidden_size<br>        s_g_split = torch.split(s_g_whole, tuple(sections.cpu().numpy()))    # split whole s_g into graphs G_i<br>        s_g = tuple(torch.sum(embeddings, dim=0).view(1, -1) for embeddings in s_g_split)<br>        s_h = self.W_3(torch.cat(s_g, dim=0))<br>        <br>        z_i_hat = torch.matmul(s_h, all_item_embedding.weight.transpose(1, 0))<br>        <br>        return z_i_hat</pre><figure><a href="https://buymeacoffee.com/newhardwarf"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c42b5310baa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conformalized Quantile Regression with xgboost 2.0]]></title>
            <link>https://medium.com/@newhardwarefound/conformalized-quantile-regression-with-xgboost-2-0-e70bbc939f6b?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e70bbc939f6b</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Wed, 22 May 2024 18:42:04 GMT</pubDate>
            <atom:updated>2024-06-06T22:08:45.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*jR_4LIHBB0_9CSUj8e_EVQ.jpeg" /></figure><h4>A hands on tutorial on producing confidence intervals</h4><p>Point estimates don’t tell the whole story. To make better real life decisions, we need to quantify the uncertainty in the predictions, which are usually done by quantile regression. We will present the shortcomings of quantile regression and a simple technique to ameliorate the drawbacks by going through an example regression problem.</p><h4>Dataset</h4><p>We choose UCI’s Communities &amp; Crime <a href="https://archive.ics.uci.edu/dataset/183/communities+and+crime">dataset</a> as our example problem. The dataset is used to predict violent crime rate in different communities. Here is the preprocessing script.</p><pre>import pandas as pd<br>import numpy as np<br><br># https://github.com/vbordalo/Communities-Crime/blob/master/Crime_v1.ipynb<br>attrib = pd.read_csv(&#39;./communities_attributes.csv&#39;, delim_whitespace = True)<br>data = pd.read_csv(&#39;./communities.data&#39;, names = attrib[&#39;attributes&#39;])<br>data = data.drop(columns=[&#39;state&#39;,&#39;county&#39;,<br>                          &#39;community&#39;,&#39;communityname&#39;,<br>                          &#39;fold&#39;], axis=1)<br>        <br>data = data.replace(&#39;?&#39;, np.nan)<br>        <br># Impute mean values for samples with missing values        <br>from sklearn.impute import SimpleImputer<br>        <br>imputer = SimpleImputer(missing_values = np.NaN, strategy = &#39;mean&#39;)<br>        <br>imputer = imputer.fit(data[[&#39;OtherPerCap&#39;]])<br>data[[&#39;OtherPerCap&#39;]] = imputer.transform(data[[&#39;OtherPerCap&#39;]])<br>data = data.dropna(axis=1)<br>X = data.iloc[:, 0:-1].values<br>y = data.iloc[:, -1].values<br><br>from sklearn.model_selection import train_test_split<br><br># divide the dataset into test and train based on the test_ratio parameter<br>x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)</pre><h4>Quantile Regression</h4><p>We can produce “confidence intervals” using quantile regression. Instead of the common MSE loss, quantile regression tries to minimize the <em>pinball loss</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/0*T5o2C9uNkIpzD52L" /></figure><p>where N is the length of dataset, y_i the ground truth for the i-th training data, \hat{y}_i the prediction for the i-th training data, \alpha the quantile within [0,1], and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*B3N3BEb_zVVlyZsU" /></figure><p>When \alpha=0.5, the pinball loss is reduced to MAE. When \alpha is not equal to 0.5, the pinball loss places asymmetric weights on overestimates and underestimates. The smaller the quantile \alpha, the closer the estimate \hat{y}_i will get to the lower end of the training dataset.</p><p>It used to take some effort to adapt xgboost for pinball loss before 2.0. The new QuantileDMatrix introduced in 2.0 standardizes the implementation. Here is the training script</p><pre>import xgboost as xgb<br><br>def train_xgboost_model(x_train, y_train, x_test, y_test, alpha):<br>  evals_result = {}<br><br>  Xy_train = xgb.QuantileDMatrix(x_train, y_train)<br>  Xy_test = xgb.QuantileDMatrix(x_test, y_test, ref=Xy_train)<br><br>  booster = xgb.train(<br>        {<br>            # Use the quantile objective function.<br>            &quot;objective&quot;: &quot;reg:quantileerror&quot;,<br>            &quot;tree_method&quot;: &quot;hist&quot;,<br>            &quot;quantile_alpha&quot;: alpha,<br>            # Let&#39;s try not to overfit.<br>            &quot;learning_rate&quot;: 0.04,<br>            &quot;max_depth&quot;: 6,<br>        },<br>        Xy_train,<br>        num_boost_round=64,<br>        early_stopping_rounds=2,<br>        evals=[(Xy_train, &quot;Train&quot;), (Xy_test, &quot;Test&quot;)],<br>        evals_result=evals_result,<br>    )<br>  return booster<br><br>alpha = np.array([0.05, 0.5, 0.95])<br>booster = train_xgboost_model(x_train, y_train, x_test, y_test, alpha)<br># only inplace_predict can work with QuantileDMatrix<br>scores = booster.inplace_predict(x_test)<br># dim 1 is the quantiles<br>assert scores.shape[0] == x_test.shape[0]<br>assert scores.shape[1] == alpha.shape[0]<br><br>y_lower = scores[:, 0]  # alpha=0.05<br>y_med = scores[:, 1]  # alpha=0.5, median<br>y_upper = scores[:, 2]  # alpha=0.95</pre><h4>Drawback of quantile regression</h4><p>We get lower/upper estimates for the test dataset. Can we dust off our hands and claim problem solved? Not so fast.</p><p>Let’s do a quick check on what percentage of the test dataset falls within the “confidence intervals” produced by plain quantile regression.</p><pre>coverage = (y_test &gt;= y_lower) &amp; (y_test &lt;= y_upper)<br>np.sum(coverage) / len(y_test)<br># 0.56</pre><p>Our confidence interval is [0.05, 0.95]. It is supposed to contain 90% of the data. In reality however, merely <strong>56%</strong> of the test dataset falls within the “confidence intervals”. <strong>The quantile \alpha we choose in the pinball loss conflicts with what we expect it to mean.</strong></p><h4>Conformalized Quantile Regression</h4><p>CQR can help us solve the problem. As the first step, we set aside a portion of the training dataset as the <em>calibration set</em>. Then we train a quantile regression model on the non-calibration set and evaluate <em>conformal scores</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*WQDun9VwIXRU1pfq" /></figure><p>on the calibration set, where \hat{y}_\alpha(x)/\hat{y}_{1-\alpha}(x) are lower/upper estimates derived in the quantile regression model and the score s how far the calibration data is outside the “confidence interval” (negative means inside the interval, positive outside). Last we expand the confidence intervals by the (1–2\alpha) empirical quantile of the conformal scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*OcjNLegoJ97UuNPv4IWc5Q.png" /></figure><p>Here is the script for CQR</p><pre>x_train_c, x_calib, y_train_c, y_calib = train_test_split(x_train, y_train, test_size=0.2)<br><br>alpha = np.array([0.05, 0.95])<br>booster = train_xgboost_model(x_train_c, y_train_c, x_test, y_test, alpha)<br>scores_calib = booster.inplace_predict(x_calib)<br>y_lower = scores_calib[:, 0]  # alpha=0.05<br>y_upper = scores_calib[:, 1]  # alpha=0.95<br>conformity = np.maximum(y_lower-y_calib, y_calib-y_upper)<br>qhat = np.ceil(0.9*(1+1.0/len(x_calib)))<br>shift = np.quantile(conformity, qhat, interpolation=&#39;higher&#39;)<br><br>scores_test = booster.inplace_predict(x_test)<br>y_lower = scores_test[:, 0] - shift  # alpha=0.05<br>y_upper = scores_test[:, 1] + shift # alpha=0.95</pre><p>We can check our coverage and it’s ~9%, right within the 10% limit.</p><h4>Visualization</h4><p>Number comparisons are boring. To highlight the improvement made by CQR even more, let’s visualize the dataset in 2 different ways.</p><p>First, we can plot the target variable (y-axis) against the data index (x-axis). The blue dots stand for the ground truth (sorted to declutter the picture). The orange bars stand for the lower/upper estimates for each data. A data falls within the “confidence interval” if a blue dot is contained within an orange bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*IlwAlt-96-FJjl0W3HANqA.png" /><figcaption>Quantile Regression</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*2P0wuklkTGm0M7mciMlX_g.png" /><figcaption>Conformalized Quantile Regression</figcaption></figure><p>Here is the script to generate the graph</p><pre>ind = np.argsort(y_test)<br><br>import matplotlib.pyplot as plt<br><br>ax = plt.subplot()<br>ax.scatter(np.linspace(0, len(y_test), len(y_test)), y_test[ind])<br>ax.fill_between(np.linspace(0, len(y_test), len(y_test)), y_lower[ind], y_upper[ind], alpha=0.8)</pre><p>Second, we can plot the predicted target variable (y-axis) against the ground truth (x-axis). We add error bar to each data to show its lower/upper estimates. The error bars not containing the diagonal line are marked red, otherwise blue. The red dots are those that fall outside the “confidence intervals”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*vdR1LHQ-Tiq-ol7RrB5oaA.png" /><figcaption>Quantile Regression</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*U31OVEhsoP66HmesZ8aRpA.png" /><figcaption>Conformalized Quantile Regression</figcaption></figure><p>Here is the script to generate the graph</p><pre>error_range = np.vstack([y_med-y_lower, y_upper-y_med])<br># Surprise! xgboost can produce higher lower estimates than upper estimates occasionally<br>error_range[error_range &lt; 0] = 0<br><br>import matplotlib.pyplot as plt<br><br>ax = plt.subplot()<br>ax.errorbar(y_test[coverage], y_med[coverage], yerr=error_range[:, coverage], capsize=5, marker=&quot;o&quot;, elinewidth=1, linewidth=0, errorevery=10)<br>ax.errorbar(y_test[~coverage], y_med[~coverage], yerr=error_range[:, ~coverage], capsize=5, marker=&quot;o&quot;, elinewidth=1, linewidth=0, color=&quot;red&quot;, errorevery=1)<br>ax.set_xlim(-0.05, 1.05)<br>ax.set_ylim(0, 1.2)<br>ax.set_xlabel(&#39;True&#39;)<br>ax.set_ylabel(&#39;Predicted&#39;)<br><br>lims = [<br>        np.min([ax.get_xlim(), ax.get_ylim()]),  # min of both axes<br>        np.max([ax.get_xlim(), ax.get_ylim()]),  # max of both axes<br>    ]<br>ax.plot(lims, lims, &#39;--&#39;, alpha=0.75, color=&quot;black&quot;, label=&quot;x=y&quot;)</pre><h4>Epilogue</h4><p>There is much more to CQR than what has been covered in this tutorial. Asides from regression problems, CQR can be applied to classification problems (&amp; other problems) just as easily.</p><p>CQR enjoys a rigorous mathematics foundation. It can be proven that coverage converges at a rate of O(\sqrt(n)) where n is the size of the calibration set. Please check <a href="https://arxiv.org/pdf/2107.07511">here</a> for more details.</p><p>You might find the idea of sacrificing a portion training data for calibration distasteful. Jackknife mixes CQR with cross validation to make full use of the training dataset.</p><figure><a href="https://buymeacoffee.com/newhardwarf?new=1"><img alt="" src="https://cdn-images-1.medium.com/max/545/0*Wf6poyzKim4OxFtk.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e70bbc939f6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SHAP explained with +-×÷]]></title>
            <link>https://medium.com/@newhardwarefound/shap-explained-with-simple-arithmetic-24efd393f4a2?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/24efd393f4a2</guid>
            <category><![CDATA[shapley-values]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 04:55:59 GMT</pubDate>
            <atom:updated>2024-03-06T16:57:31.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*ne0-8Hg5koxw2EMdBoV7ag.png" /></figure><h4>&amp; 0 game theory/causal inference/probability theory jargon</h4><p>I’ve read many articles about SHAP. Either they are too full of jargons to be readable or entirely focused on applications. In this article, I will explain the ideas and intuition behind SHAP in as short a paragraph as rigorousness allows. The relationship between interventional &amp; observational SHAP, SHAP &amp; partial dependence plot will also be explained.</p><h4>Defining formula</h4><p>Model f has a set of explanatory variables (or features) N. To single out the impact of feature i, we define <em>SHAP</em> value as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*5pPEctR2JmBP-s0X64YSQA.png" /></figure><p>The formula looks at the impact feature i makes when combined with different features S. Assign equal weight to each permutation (or ordering) of all features and normalize the sum of weights to 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*Sfdf6JVME-4J7qLmuOJQjg.png" /></figure><p>The weight is the largest when S contains nearly all the features or very few features. In presence of very few other features, feature i’s contribution stands out and needs to get more weight. When a lot of other features take the same values, a large difference in model outcome must be caused by feature i and needs to get more weight.</p><h4>Intervention on input</h4><p>Now let’s look at how to define f_x so that the model outcome attributable to a subset S can be separated from the rest. Define an <em>intervention</em> on model input x by a <em>background sample</em> x^b for subset S.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*ji3-zfL9wLq0x3-ntVbiJQ.png" /></figure><p>where j is the index for each component in the vector input x. Essentially, the intervention substitutes part of x for the corresponding part of the background sample and leaves the rest untouched.</p><p>The background sample is a vector that has the same dimension with model input. It can be taken as a random sample from the training dataset. We can tentatively define</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*JKDoXzHy6wp8-3XPquEs4g.png" /></figure><p>but an arbitrary choice of the background sample can sway the result too much. To represent the training data distribution better, we can take a random subset D of the training dataset and define as the average of the model outcome of the intervened input</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*8v1cFIdqM3qGlBW6nuGvDg.png" /></figure><p>That completes the definition of the SHAP value of feature i at x.</p><p>A nice property SHAP has is that the sum of SHAP across all features is equal to the model outcome relative to its average</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*y_902-ptPikHVHc5KhI0OA.png" /></figure><p>where T is the training dataset. Different from Gini or permutation importance, SHAP explains model outcome rather than model accuracy.</p><p>The global feature importance of feature i for model f can then defined as the average of absolute SHAP values across the training data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*vEjt6P3LLuRlxE0yYTr29g.png" /></figure><h4>Example 1: linear function</h4><p>Let’s hand compute the SHAP value of a bivariate linear function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*xS7iF669TzyLqThWDVrEkg.png" /></figure><p>where w_1 and w_2 are the coefficients for feature 1 &amp; 2.</p><p>The SHAP value of feature 1, according to definition, is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*ngg878Ehfk8m9V86LsfY8w.png" /></figure><p>Intervening on the full set is no intervention at all, resulting in the model outcome at input x=(x_1, x_2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*CGJmPhYYyQngXozzFY0--Q.png" /></figure><p>In the case of an empty set, it’s the average of the model outcome on background samples</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*7R2lQM8_C1w17CWPPcF5Ng.png" /></figure><p>One can calculate the other 2 terms and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*Kgk5m3ExK3jJ8Z60W8XkIQ.png" /></figure><p>The global feature importance of feature 1 is w_1 times the mean absolute deviance of the first component in the training dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*wiL0BgFd15Lo-Hd6tB58dg.png" /></figure><p>where we choose D=T.</p><h4>Example 2: tree</h4><p>Let’s hand compute the SHAP value of a tree function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*H766O17MET7cMHwQMdUR1Q.png" /></figure><p>The tree function takes value 1 when u&lt;2, v&gt;4 and 0 otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*UXDlb1zK9uOI1_jUMvgzFA.png" /></figure><p>We calculate the SHAP value of feature 1 at an arbitrary input</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*BCQfouLB7wA8sk9UgDnZUw.png" /></figure><h4>Observational SHAP</h4><p>The definition above is called <em>interventional SHAP</em> and is the most widely used one. There is an alternative definition of f_x in the literature.</p><p>Define the <em>projection </em>of vector x upon a feature subset S as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*zlKcI8Qbgw4TvF4M2IuI8Q.png" /></figure><p>where we remove the vector dimensions that are not part of S.</p><p>With a set of training data whose projection matches that of the model input x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*iJFPOcmyvkzt7sOEDZInnw.png" /></figure><p>we can define f_x as the average of the model outcome on it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*XD-ellCX7kESlHCuBXp57w.png" /></figure><p>The observational approach has an advantage that no out-of-vocabulary synthetic data will ever be used in the calculation. It is a concern when your model does not generalize well to unseen data.</p><p>The approach’s drawback is also quite obvious. In reality, the size of |H| might be too small, reduces f_x(S) to f(x) and every SHAP value becomes 0.</p><p>Observational SHAP is shown to distribute weights between correlated features. Interventional SHAP is not known to do so. Whether it’s desired or not depends on concrete applications.</p><p>Notice that all KernelExplainer, SampleExplainer &amp; TreeExplainer (regardless of the feature_perturbation option) in the shap package uses <strong>interventional </strong>SHAP, not observational SHAP.</p><h4>Relationship with Individual Conditional Expectation (ICE) Plot/Partial Dependence Plot (PDP)</h4><p>The sklearn.inspection module provides an implementation of partial dependence plot/individual conditional expectation plot, which is a way to visualize a feature’s impact on the model outcome.</p><p>In an ICE plot, each line represents a training data x. We modify the i-th feature value of x to theta and leave the other components untouched</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*3Bzuhs8xu8zdMTtmu2qNsw.png" /></figure><p>Varying theta on the x-axis, we plot the changing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/88/1*mSCAgK1E-xB2opugN9z3Ig.png" /></figure><p>on the y-axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAkIAt9fazHUjcXXUIaLVA.jpeg" /></figure><p>The partial dependence plot is the average of ICE lines</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*O1_tgEZ_RnGcA6_CgacefQ.png" /></figure><p>across the training dataset. The PDP-based feature importance of feature i is defined as the variance of f_x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*Y3v1uSsWnPtjniJ-833DoA.png" /></figure><p>In comparison with SHAP, the PDP-based feature importance does not consider any feature interaction.</p><h3>If you like this post…</h3><p>Support me with a coffee!</p><figure><a href="https://www.buymeacoffee.com/newhardwarf?new=1"><img alt="" src="https://cdn-images-1.medium.com/max/545/0*klMK5dCuIaBSu9nc.png" /></a></figure><h4>Reference</h4><p>“<a href="https://arxiv.org/abs/2207.07605">Algorithms to estimate Shapley value feature attributions</a>”</p><p><a href="https://pacmedhealth.medium.com/explainability-for-tree-based-models-which-shap-approximation-is-best-6df78bc5d086">Comparison between Observational and Interventional TreeSHAP</a></p><p>Huyh Chen’s blog post: <a href="https://hughchen.github.io/its_blog/index.html">https://hughchen.github.io/its_blog/index.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24efd393f4a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear classifier in modem]]></title>
            <link>https://medium.com/@newhardwarefound/linear-classifier-in-modem-71fef1fe08df?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/71fef1fe08df</guid>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[history-of-technology]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 22:56:09 GMT</pubDate>
            <atom:updated>2024-01-20T17:11:13.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*opYepMbGB7F7Rg2IrQ1ZVA.gif" /></figure><h4>an early application of FIR filter, or Autoregression model</h4><p>No one can ever forget the high-pitched screeching made by dial-up modem. It’s the sound of one’s virtual gate to the world opening. It’s the sound of one’s money getting sucked away by greedy ISPs. Unbeknownst to a lot of data science practitioners, it is also the sound of a linear classifier (great-grandfather of now popular neural networks) in training.</p><p>Modem transmitter encodes data in a format amenable to physical transmission before sending them. Among various formats, one is <em>pulse amplitude modulation</em> (PAM). Pulses are emitted at regular interval. Amplitudes, e.g. in discrete levels ±3, ±1, of each pulse represent the numbers to be sent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*EhoCDzfz12hXikCErqE2hg.jpeg" /></figure><p>Unfortunately, electrical signals get distorted after traveling thousands of miles of telephone wires. In a phenomenon known as <em>Inter-Symbol Interference</em>, individual signals are smeared out during transmission, causing neighboring signals to overlap. The smushed signals make it hard for modem receiver to decipher. To make matter worse, distortion varies with channel and time. ISI is the main obstacle to achieving high data transmission rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*eavuXp7YDOx5NfSuKMZa5Q.png" /></figure><p>In 1965, Bell Labs proposed an automated procedure to compensate for ISI on the receiving end. During each handshake, modem transmitter sends M predetermined symbols y[n], which are received as x[n] by modem receiver. To recover real symbols, we linearly combine k preceding symbols received</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*7_VDTIOVkhBH-wQriuYJgg.png" /></figure><p>where w_k are the weights to be optimized against the MSE error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*rw4-xjOLt-mfPYgSkJK_0g.png" /></figure><p>Written in matrix notation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*saiHU_yq1vTWjboT9dfwWg.png" /></figure><p>the overdetermined linear system has an Moore-Penrose inverse solution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*DBl5VJ-ozyAiKOGDlFtWkg.png" /></figure><p>Known as <em>autocorrelation matrix</em> in time series literature, X^TX is a Toeplitz matrix and can be inversed fast with <em>Levinson-Durbin recursion</em>. The analytic solution is called <em>Yule-Walker estimates</em>. The algorithm is too expensive to implement on early modems.</p><p>Instead, engineers adopt the gradient descent method to iteratively approximate the theoretical optimal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*IdlV5TFaZiui_rk1Vo1ieA.png" /></figure><p>where mu is a step size.</p><p>Full gradient descent method is still too expensive. Recall that stochastic gradient descent method allows us to make an update with any single data point. Here we can do the similar by reducing the formula to the special case M=N, where we simply update the weights by adding a product of 3 terms: step size, last error and the received symbols.</p><p>In 1984, the Yule-Walker estimates were implemented as <em>Linear Predictive Coding</em> to compress voice signals for wireless communication (e.g. GSM, Skype’s SILK, even Zoom).</p><blockquote>Every cell phone solves 10 linear equations in 10 unknowns every 20 milliseconds. — T. Dutoit</blockquote><p>Apparently, each short slice of voice can be modeled as a sum of AR(10) and a pulse train.</p><h4>Reference</h4><p><a href="https://www.windytan.com/2012/11/the-sound-of-dialup-pictured.html">Here</a> is a more detailed explanation of the handshake process of dial up modem. The training step happens in Phase 3 10.1.3.6 and lasts 288 symbols.</p><p><a href="http://www.isle.illinois.edu/speech_web_lg/coursematerials/ece401/fa2020/slides/lec17.pdf">Here</a> is an excellent overview of LPC10 for voice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71fef1fe08df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image registration by Discrete Fourier Transform]]></title>
            <link>https://medium.com/@newhardwarefound/pattern-matching-by-discrete-fourier-transform-163823bcaa60?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/163823bcaa60</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 15:29:19 GMT</pubDate>
            <atom:updated>2024-01-18T00:10:36.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*t-eQj-Jusv3McXWdJY42sw.png" /></figure><h4>or how an optical mouse works</h4><p>Have you ever wondered how an optical mouse works? Back in the good old days, ball mouse was the only kind available. It is intuitive to understand how balls track hand movement. Around 00s came optical mouse and I couldn’t help staring at the small patch of red light where balls once were.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*PxdhPgJweQx6sjCbQB5WOQ.jpeg" /></figure><p>It turns out that optical mouse is equipped with a crude camera (e.g. 18 x 18 B&amp;W photodiode array) taking pictures at high speed. The mouse deduces the speed and direction by comparing the location of the same surface texture in pictures taken at successive times. It’s too slow to do comparison pixel by pixel though. A maths technique called <em>Discrete Fourier Transform</em> helps speed up the process.</p><p>In fact, discrete Fourier transform is such a popular pattern matching technique that you probably see or use several times every day. Another common application would be automotive radar.</p><p>In this article, I am going to do a numpy demo of the technique and show the maths behind it.</p><h4>Phase Correlation</h4><p>Let’s think from scratch. The problem is to find the offsets in x &amp; y direction so that a given image overlays perfectly with the other one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*3fOQyJuCXHm7faoFIN4XMg.jpeg" /></figure><p>The simplest algorithm would be try aligning the top left pixel in image 1 with every pixel in image 2 and see which one yields the best match. Match perfectness can be defined quantitatively as inner product between the 2 images (viewed as flattened 1d vectors). A larger inner product indicates a better match because it is only maximized when a vector dot products with itself. The time complexity of the above algorithm is O(M²) (M is the number of pixels).</p><p>We can do better than that by solving the problem in the Fourier domain. Let’s define the discrete Fourier transform of a row of N pixels x[n] as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*MHnOHgeOo0L_NxWzFmwlUg.png" /></figure><p>The famous convolution theorem states that the convolution of two rows x[n], y[n]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*tBvGS-ki8MR4BkM5NUMJQA.png" /><figcaption>index k-n understood as modulo N</figcaption></figure><p>is simply multiplication in the Fourier domain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*LdrUbtE6e9WYHSnxYi8Taw.png" /></figure><p>Notice that convolution is really similar to cross correlation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*jhaDgkB1JtofneaD5BlESg.png" /></figure><p>the only difference being y[k-n] and y[n-k]. It turns out we only need to conjugate once to get the Fourier transform of cross correlation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*y2rw8G4hoQCt3PUC_WBP5w.png" /></figure><p>We can apply the inverse discrete Fourier transform to recover the row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*QjUDS0yfdiUg2xvexDN3Zg.png" /></figure><p>In the end, we check each n to find the maximum. Only 1D version is presented above but 2D is quite similar. The time complexity is O(MlogM) due to the magic of fast Fourier transform algorithm.</p><p>With the help of numpy, the algorithm can be concisely implemented as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0ZvDT5_zNVcdSL-3azjhzQ.png" /></figure><pre>import numpy as np<br><br>def phase_correlation(a, b):<br>    R = np.fft.fft2(a) * np.fft.fft2(b).conj()<br>    r = np.abs(np.fft.ifft2(R))<br>    return r</pre><h4>Experiment</h4><p>Let’s say we have a following picture on our desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*3TFePKFFWU4zhqk-JFpeDA.png" /></figure><p>An optical mouse captures the red and yellow rectangular area with some noises at successive moments. Now it has to figure out how much movement has happened between the two moments.</p><pre>import cv2<br>import numpy as np<br><br>img = cv2.imread(&#39;unnamed.jpg&#39;)<br><br>width, height = 1000, 1000<br>x1, y1= 300, 300<br>x2, y2 = x1+height, y1+width<br># synthetic displacement<br>dist_x, dist_y = 90, 110<br><br>def add_noise(img):<br>    # add gaussian noise<br>    gauss = np.random.normal(0, 10, img.shape)<br>    return img + gauss.reshape(img.shape)<br><br>before_shift = add_noise(img[x1:x2, y1:y2, -1])<br>after_shift = add_noise(img[x1+dist_x:x2+dist_x, y1+dist_y:y2+dist_y, -1])</pre><p>The phase correlation algorithm outputs the correct shift.</p><pre>corr = phase_correlation(before_shift, after_shift)<br>np.unravel_index(np.argmax(corr, axis=None), corr.shape)</pre><p>The shift-correlation can be visualized as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*rK_h1DpmlOEyycllyvWMmw.png" /></figure><p>The coordinates of the highest peak are exactly equal to the shift we applied in the beginning.</p><h4>Rotation</h4><p>Now that we have solved the displacement problem, let’s consider a more challenging problem. Given an image and its rotated version, how do we determine the angular movement?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*99R-BP-eu-BxgSMAcRtIfg.png" /></figure><p>Polar system is better suited than cartesian for dealing with rotation. We plot the images in a polar system centered on the image center. Here we face a challenge that regularly spaced grid points in a polar system don’t map exactly to those in the cartesian system. Luckily scipy’s map_coordinates offers an approximation by spline interpolation.</p><pre>from scipy.ndimage import map_coordinates<br><br>def get_polar(img, shape):<br>    # Adapted from https://github.com/polakluk/fourier-mellin/blob/master/script.py<br>    anglesMap = np.zeros(shape, dtype=np.float64)<br>    # each column has 0 in its first row and -pi in its last row<br>    anglesVector = np.linspace(0, 2.0*np.pi, 360, endpoint=False)<br>    # initialize it by columns using the same vector<br>    anglesMap.T[:] = anglesVector<br>    # create matrix with radii<br>    radiusMap = np.zeros(shape, dtype=np.float64)<br>    # each line contains a vector with numbers from  in (0, cols) to power logBase<br>    radiusVector = np.arange(shape[1], dtype=np.float64)<br>    # initialize it by rows using the same vector<br>    radiusMap[:] = radiusVector<br>    # calculate x coordinates (source: https://en.wikipedia.org/wiki/Log-polar_coordinates)<br>    x = radiusMap * np.sin(anglesMap) + img.shape[0] // 2 <br>    # calculate y coordinates (source: https://en.wikipedia.org/wiki/Log-polar_coordinates)<br>    y = radiusMap * np.cos(anglesMap) + img.shape[1] // 2 <br>    # initialize final image<br>    output = np.zeros(shape)<br>    # use spline interpolation to map pixels from original image to calculated coordinates<br>    map_coordinates(img, [x, y], output=output)<br>    return output</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*LrQ6FZapVgdSH35o4Ew6-A.png" /></figure><p>We can clearly see that in polar system, the rotated image is simply a displaced copy of the original in y (or \theta) direction.</p><p>To determine the exact displacement is a solved problem! We apply the phase correlation algorithm to determined the rotated angle.</p><pre>output_1 = get_polar(before_rotated, (360, 700))<br>output_2 = get_polar(after_rotated, (360, 700))<br>corr = phase_correlation(output_1, output_2)<br>shape = corr.shape<br># Locate maximum<br>maxima = np.unravel_index(np.argmax(corr), shape)<br><br>midpoints = np.array([np.fix(axis_size / 2) for axis_size in shape])<br><br>shifts = np.stack(maxima).astype(np.float64)<br>shifts[shifts &gt; midpoints] -= np.array(shape)[shifts &gt; midpoints]<br><br>print(shifts)</pre><h4>Reference</h4><p><a href="https://web.mit.edu/~gari/teaching/6.555/lectures/ch_DFT.pdf">Here</a> contains self-contained rigorous proofs for the discrete Fourier transforms used in this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163823bcaa60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack M-209 cipher with data science]]></title>
            <link>https://medium.com/@newhardwarefound/crack-m-209-cipher-with-data-science-c393ac9f862d?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c393ac9f862d</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[history-of-technology]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 17:07:10 GMT</pubDate>
            <atom:updated>2024-01-05T04:01:57.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*E8AKW9QlTzRQyGzgCEF9Dw.jpeg" /><figcaption>German’s first decrypted message</figcaption></figure><h4>A tale of Pearson correlation, PCA and classical cryptology</h4><h4>Introduction</h4><p>During WW2 and the Korean war, M-209 was US Army’s tactical cipher machine. Over <strong>14,000</strong> M-209s were manufactured and deployed on battlefields. Postwar investigations revealed that the German were able to read 10–20% M-209-encrypted traffic. How they did it remained classified until at least 1998. Curiously, Robert Morris &amp; Denis Ritchie, fathers of Unix, discovered a different method in 1978, the publication of which got suppressed by NSA at the time. In this article, we are going to revisit their methods from a modern perspective.</p><p>Before getting into deciphering, we need to have a good understanding of ciphering. M-209 enciphers by hiding plaintext under random numbers. Knowledge of how the machine generates random number is the key to codebreaking.</p><h4>M-209 pseudorandom algorithm</h4><p>M-209 generates pseudorandom numbers from interaction between the <em>pin setting</em> and the <em>lug setting</em>. More precisely, the i-th pseudorandom number is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*M1pldBJN94rnoaltuKuodQ.png" /></figure><p>The pin setting PIN is 6 boolean arrays of lengths N=[26, 25, 23, 21, 18, 17].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*LXfFpJzkD8NTic3Nu_29-A.jpeg" /><figcaption>pin setting, letter=True, -=False</figcaption></figure><p>The lug setting LUG is a 27 by 6 boolean matrix. Each row contains at most 2 trues. The 6 lug columns correspond to the 6 pin arrays mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*a3WDSegti7mKuns_6ud-qQ.jpeg" /><figcaption>lug setting</figcaption></figure><p>For example, the 1st pseudorandom number is the number of lug rows (at most 27) which has at least 1 true that coincides with a true at the same position in the 1st pin row. In our example, the 1st pin row sets 1,2,3,6 true. There are 18 trues in those lug columns, of which 2 are in the same row. Therefore the 1st pseudorandom number is 17.</p><p>For the 2nd pseudorandom number, advance to the next pin row (cycle back to the 1st row if it reaches the last row in some columns) and repeat the tally of the lug rows. So on and so forth.</p><p>M-209 pseudorandom number enjoys a period of 26 x 25 x 23 x 21 x 18 x 17 = 10⁸, pretty solid for pre-computer era. See the appendix for details on how M-209 implements the algorithm mechanically.</p><h4>Recover the pin setting</h4><p>Due to operational complexity, the US Army only rotates the pin setting and the lug setting on a daily schedule. Physical capture of schedule printouts allowed the German troops to read some months’ traffic entirely.</p><p>The German cryptanalysts however were able to recover settings from ciphertext alone. In the following, we assume the pseudorandom numbers are known (For details on how to uncover the pseudorandom numbers, please search known plaintext attack) and focus on recovering the rightmost pin setting (of length 17).</p><p>The rightmost pin is either true or false. Depending on its status, the pin makes different contributions to pseudorandom numbers, 0 when false and positive when true. The number distribution generated by true rightmost pins varies significantly from false ones. We should be able to discern different pin status by comparing histograms of the pseudorandom numbers generated from different pins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*kbRyd6ZnUqbpp6eInShaAQ.png" /></figure><p>Since the rightmost pin has a cycle of 17, we write the pseudorandom numbers in rows of 17 and take histogram of the numbers in each column. The German method then calculates the Pearson correlation between the 17 histograms. Positive correlation means the 2 pins share the same status. Negative means the opposite.</p><p>To demonstrate the German method, we synthetize M-209 pseudorandom numbers using the pycipher <a href="https://github.com/jameslyons/pycipher/blob/master/pycipher/m209.py">implementation</a> with the pin setting</p><pre>[1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0]</pre><p>Write code as described above</p><pre>from m209 import M209<br><br>cipher = M209(wheel_starts=&#39;BLOGER&#39;)<br>with open(&#39;./hamlet.txt&#39;, &#39;r&#39;) as f:<br>    plain = f.read()<br><br>#encipher hamlet<br>secret = cipher.encipher(plaintext)<br><br>#uncover random numbers<br>ran = [(cipher.a2i(secret[i]) + cipher.a2i(plain[i]))%26 for i in range(len(secret))]<br><br>#write in a table of 17 columns and truncate<br>import numpy as np<br>table = np.array(ran)[:-12].reshape((-1, 17))<br><br>#take histogram for each column<br>stats = np.array([np.histogram(table[:, i], bins=np.arange(27))[0] for i in range(17)])<br><br>#calculate correlation<br>corr = np.corrcoef(stats)<br><br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>sns.heatmap(corr, cmap=&quot;Blues&quot;)<br>plt.show()</pre><p>We can read the pin setting directly from the histogram correlation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*_UadaNG1fLlodHv-RzvBZg.png" /><figcaption>Each row/column represents a pin. Pins in the same color area share the same status.</figcaption></figure><p>As an alternative, Robert Morris &amp; Denis Ritchie applied PCA on the histograms and discovered that the pin setting can also be recovered from the principal eigenvector of the covariance matrix.</p><pre>from numpy import linalg as LA<br><br>s,v,d = LA.svd(stats @ stats.T)<br>(np.sign(s[:,0]-np.average(s[:,0])) + 1)/2</pre><h4>Morris’ attack</h4><p>What about the lug setting and other pin settings?</p><p>Morris describes in his paper a method of bimodal means. Take average of each column (exclude 0 and 1 because they can be 26, 27 under modulo 26 and could skew the statistics)</p><pre>means = [col[col&gt;=2].mean() for col in table.T]</pre><p>and we will see that the averages of true and false pins form a bimodal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*z3Cw3gqi1A3eEDqCz_rHsw.png" /></figure><p>The difference between the 2 peaks is roughly the number of true lugs. The pins in the smaller (in terms of the average number) peak are false. Those in the larger peak are true. Pins can fall in between and we might have to venture guesses and backtrack a few times.</p><p>Once the lug count is known, we can take out the effect of a pin completely by subtracting the pseudorandom numbers by the lug count wherever the pin is true. Repeat the process for all pin arrays and we break M-209!</p><h4>Appendix. Crash course on M-209 mechanism</h4><p>The 2 components in M-209, <em>drum</em> (or cage) and <em>wheels</em> (or rotors), work together to generate pseudorandom numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*qO1Sz6KX4fn04BRH4WeVRw.jpeg" /><figcaption>lugs, bars and drum</figcaption></figure><p>The drum has 27 horizontal <em>bars</em> (numbered 1–27) on its circumference. On each bar, 2 moveable <em>lugs</em> can be set to any 2 of the 8 fixed positions. Out of the 8 positions, 6 are <em>active</em>, numbered 1–6, and the other 2 are <em>inactive</em>, numbered 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*iXvGb7S8ZR-8LywwoeQ8QQ.jpeg" /><figcaption>pins and wheels, position JSMKMB</figcaption></figure><p>There are 6 wheels (corresponding to the 6 active positions on bars) in the front. Each wheel has a number of <em>pins</em> on its rim which can be independently pushed left (<em>ineffective</em>) or right (<em>effective</em>). From left to right, the wheel has 26, 25, 23, 21, 18, 17 pins. Each pin is numbered A-Z. The wheel position is thus encoded as 6 letters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*gDCCocDPHqDx3HTCYX7k5w.jpeg" /><figcaption>guide arm</figcaption></figure><p>When (de)ciphering, the drum revolves 1 cycle and each of the bar passes above the top row of 6 pins. When an effective pin coincides with a lug, the guide arm will push the bar left. The pseudorandom number is then the number of times (modulo 26) the bar is pushed left. In the end, all the wheels advance by one letter.</p><h4>References</h4><p>All the pictures of M-209 in this article come from Jean-François BOUCHAUDY’s <a href="http://www.jfbouch.fr/crypto/m209/index.html">blog</a>.</p><p><a href="https://drive.google.com/drive/folders/0B_oIJbGCCNYeMGUxNzk0NWQtNzNhZi00YWVjLWI1NmItMzc2YWZiZGNjNjQ5?resourcekey=0-Makh6wUd1KjCFQZ8_Rvp-A">TICOM DF-120</a> contains a description of the German method on <a href="https://chris-intel-corner.blogspot.com/2012/06/american-m-209-cipher-machine.html">Christos’ blog</a></p><p>Denis Ritchie’s <a href="https://www.bell-labs.com/usr/dmr/www/crypt.html">account </a>of NSA suppression</p><p>Robert Morris and Denis Ritchie’s <a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=716f8269834cda52f6353150dc42b651bd90e148">paper</a></p><p>Robert Morris’ separate <a href="https://www.tandfonline.com/doi/abs/10.1080/0161-117891853126">paper</a></p><p>Barker’s “<a href="https://www.ahazu.com/papers/lanaki/lesson21.php">Cryptanalysis of the Hagelin Cryptograph</a>”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c393ac9f862d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QLORA with Llama 2]]></title>
            <link>https://medium.com/@newhardwarefound/qlora-with-llama-2-ca1b4bcf26f0?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1b4bcf26f0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 22:20:27 GMT</pubDate>
            <atom:updated>2024-03-03T17:26:10.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WhyLdm1yo29jp8vx.png" /></figure><h4>A step-by-step guide to bitsandbytes on a GPU machine</h4><p>Llama 2 has been out for months. Still haven’t tried it due to limited GPU resource? This guide will walk you through how to run inference &amp; fine-tune with Llama2 on an old GPU.</p><h4>Run inference with quantized Llama 2</h4><p>The 1st step is gain access to the model. Visit <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads">Meta website</a> and accept the license and user policy. Then visit <a href="https://huggingface.co/meta-llama">meta-llama (Meta Llama 2)</a> and request access to the model weights on huggingface. Copy your huggingface hub token as explained <a href="https://huggingface.co/docs/hub/security-tokens">here</a>.</p><p>The 2nd step is to set up the Python environment as detailed in the appendix.</p><p>The 3rd step is to download the model+tokenizer and load the model into GPU in 4/8/16 bit quantized format.</p><pre># Code from taprosoft&#39;s github: https://github.com/taprosoft/llm_finetuning/blob/efa6df245fee4faf27206d84802d8f58d4b6e77d/inference.py#L20<br>from transformers import (AutoModelForCausalLM,<br>    BitsAndBytesConfig,<br>    LlamaTokenizer)<br>import torch<br>import os<br><br>os.environ[&quot;HUGGING_FACE_HUB_TOKEN&quot;] = &quot;{{your_huggingface_hub_token}}&quot;<br><br>def load_hf_model(<br>    base_model,<br>    mode=8,<br>    gradient_checkpointing=False,<br>    device_map=&quot;auto&quot;,<br>):<br>    kwargs = {&quot;device_map&quot;: device_map}<br>    if mode == 8:<br>        kwargs[&quot;quantization_config&quot;] = BitsAndBytesConfig(<br>            load_in_8bit=True,<br>            llm_int8_threshold=0.0,<br>        )<br>    elif mode == 4:<br>        kwargs[&quot;quantization_config&quot;] = BitsAndBytesConfig(<br>            load_in_4bit=True,<br>            bnb_4bit_use_double_quant=True,<br>            bnb_4bit_quant_type=&quot;nf4&quot;,<br>            bnb_4bit_compute_dtype=torch.float16,<br>        )<br>    elif mode == 16:<br>        kwargs[&quot;torch_dtype&quot;] = torch.float16<br><br>    model = AutoModelForCausalLM.from_pretrained(base_model, **kwargs)<br><br>    # setup tokenizer<br>    tokenizer = LlamaTokenizer.from_pretrained(base_model)<br><br>    tokenizer.pad_token_id = 0  # unk. we want this to be different from the eos token<br>    tokenizer.padding_side = &quot;left&quot;  # Allow batched inference<br>    return model, tokenizer<br><br>model, tokenizer = load_hf_model(<br>    &quot;meta-llama/Llama-2-7b-chat-hf&quot;,<br>    mode=4,<br>    gradient_checkpointing=False,<br>    device_map=&#39;auto&#39;)</pre><p>The last step is try inference.</p><pre>from transformers import GenerationConfig<br><br>sequences = [&quot;&lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt; You are a helpful assistant. &lt;&lt;/SYS&gt;&gt;\<br>Extract the place names from the given sentence. [\INST]\n\<br>The capital of the United States is Washington D.C.&quot;]<br><br>inputs = tokenizer(sequences, padding=True, return_tensors=&quot;pt&quot;).to(&#39;cuda&#39;)<br><br>outputs = model.generate(<br>    **inputs, <br>    generation_config=GenerationConfig(<br>        do_sample=True,<br>        max_new_tokens=512,<br>        top_p=0.99,<br>        temperature=1e-8,<br>    )<br>)<br><br>print(tokenizer.decode(outputs[0], skip_special_tokens=True))</pre><h4>Fine tune quantized Llama 2</h4><p>Bitsandbytes falls into a general category of quantization schema called Post-training quantization (PTQ). In theory, there is no way to continue training such a quantized model. LORA offers a rescue by adding a low-rank matrix (called “adapter”) to each linear layer in Llama2. During fine-tuning, we only tune the adapter weights while keeping the original weights untouched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uMImec3XQrVFor4V.png" /><figcaption>Lora (credit: <a href="https://arxiv.org/abs/2106.09685">paper</a>)</figcaption></figure><p>The 1st step is to load the dataset. The dataset has only 2 columns: input &amp; output.</p><pre>from datasets import load_dataset<br>dataset = load_dataset(&#39;csv&#39;, data_files=&quot;./attributes.csv&quot;)</pre><p>The 2nd step is to set up the data collator, which formats, tokenizes and groups the fine tune dataset into batches.</p><pre># Code from taprosoft&#39;s github<br>from dataclasses import dataclass, field<br>import transformers<br>import torch<br>import copy<br>from typing import Dict, Sequence<br>from torch.nn.utils.rnn import pad_sequence<br><br>IGNORE_INDEX = -100<br><br>@dataclass<br>class DataCollatorForCausalLM(object):<br>    tokenizer: transformers.PreTrainedTokenizer<br>    source_max_len: int<br>    target_max_len: int<br>    train_on_source: bool<br>    predict_with_generate: bool<br><br>    def __call__(self, instances: Sequence[Dict]) -&gt; Dict[str, torch.Tensor]:<br>        # Extract elements<br>        sources = [f&quot;{self.tokenizer.bos_token}{example[&#39;input&#39;]}&quot; for example in instances]<br>        targets = [f&quot;{example[&#39;output&#39;]}{self.tokenizer.eos_token}&quot; for example in instances]<br>        # Tokenize<br>        tokenized_sources_with_prompt = self.tokenizer(<br>            sources,<br>            max_length=self.source_max_len,<br>            truncation=True,<br>            add_special_tokens=False,<br>        )<br>        tokenized_targets = self.tokenizer(<br>            targets,<br>            max_length=self.target_max_len,<br>            truncation=True,<br>            add_special_tokens=False,<br>        )<br>        # Build the input and labels for causal LM<br>        input_ids = []<br>        labels = []<br>        for tokenized_source, tokenized_target in zip(<br>            tokenized_sources_with_prompt[&#39;input_ids&#39;],<br>            tokenized_targets[&#39;input_ids&#39;]<br>        ):<br>            if not self.predict_with_generate:<br>                input_ids.append(torch.tensor(tokenized_source + tokenized_target))<br>                if not self.train_on_source:<br>                    labels.append(<br>                        torch.tensor([IGNORE_INDEX for _ in range(len(tokenized_source))] + copy.deepcopy(tokenized_target))<br>                    )<br>                else:<br>                    labels.append(torch.tensor(copy.deepcopy(tokenized_source + tokenized_target)))<br>            else:<br>                input_ids.append(torch.tensor(tokenized_source))<br>        # Apply padding<br>        input_ids = pad_sequence(input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id)<br>        labels = pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX) if not self.predict_with_generate else None<br>        data_dict = {<br>            &#39;input_ids&#39;: input_ids,<br>            &#39;attention_mask&#39;:input_ids.ne(self.tokenizer.pad_token_id),<br>        }<br>        if labels is not None:<br>            data_dict[&#39;labels&#39;] = labels<br>        return data_dict<br><br>data_collator = DataCollatorForCausalLM(<br>        tokenizer=tokenizer,<br>        source_max_len=280,<br>        target_max_len=512,<br>        train_on_source=False,<br>        predict_with_generate=False,<br>)</pre><p>The 3rd step is to write several helper methods.</p><pre>import bitsandbytes as bnb<br>import torch<br>import peft<br><br># COPIED FROM https://github.com/artidoro/qlora/blob/main/qlora.py<br>def print_trainable_parameters(model, use_4bit=False):<br>    &quot;&quot;&quot;<br>    Prints the number of trainable parameters in the model.<br>    &quot;&quot;&quot;<br>    trainable_params = 0<br>    all_param = 0<br>    for _, param in model.named_parameters():<br>        num_params = param.numel()<br>        # if using DS Zero 3 and the weights are initialized empty<br>        if num_params == 0 and hasattr(param, &quot;ds_numel&quot;):<br>            num_params = param.ds_numel<br><br>        all_param += num_params<br>        if param.requires_grad:<br>            trainable_params += num_params<br>    if use_4bit:<br>        trainable_params /= 2<br>    print(<br>        f&quot;all params: {all_param:,d} || trainable params: {trainable_params:,d} || trainable%: {100 * trainable_params / all_param}&quot;<br>    )<br><br><br># COPIED FROM https://github.com/artidoro/qlora/blob/main/qlora.py<br>def find_all_linear_names(model):<br>    lora_module_names = set()<br>    for name, module in model.named_modules():<br>        if isinstance(module, bnb.nn.Linear4bit):<br>            names = name.split(&quot;.&quot;)<br>            lora_module_names.add(names[0] if len(names) == 1 else names[-1])<br><br>    if &quot;lm_head&quot; in lora_module_names:  # needed for 16-bit<br>        lora_module_names.remove(&quot;lm_head&quot;)<br>    return list(lora_module_names)<br><br><br>def create_peft_model(model, gradient_checkpointing=True, bf16=True):<br>    from peft import (<br>        get_peft_model,<br>        LoraConfig,<br>        TaskType,<br>        prepare_model_for_kbit_training,<br>    )<br>    from peft.tuners.lora import LoraLayer<br><br>    # prepare int-4 model for training<br>    model = prepare_model_for_kbit_training(<br>        model, use_gradient_checkpointing=gradient_checkpointing<br>    )<br>    if gradient_checkpointing:<br>        model.gradient_checkpointing_enable()<br><br>    # get lora target modules<br>    modules = find_all_linear_names(model)<br>    print(f&quot;Found {len(modules)} modules to quantize: {modules}&quot;)<br><br>    peft_config = LoraConfig(<br>        r=64,<br>        lora_alpha=16,<br>        target_modules=modules,<br>        lora_dropout=0.1,<br>        bias=&quot;none&quot;,<br>        task_type=TaskType.CAUSAL_LM,<br>    )<br><br>    model = get_peft_model(model, peft_config)<br><br>    # pre-process the model by upcasting the layer norms in float 32 for<br>    for name, module in model.named_modules():<br>        if isinstance(module, LoraLayer):<br>            if bf16:<br>                module = module.to(torch.bfloat16)<br>        if &quot;norm&quot; in name:<br>            module = module.to(torch.float32)<br>        if &quot;lm_head&quot; in name or &quot;embed_tokens&quot; in name:<br>            if hasattr(module, &quot;weight&quot;):<br>                if bf16 and module.weight.dtype == torch.float32:<br>                    module = module.to(torch.bfloat16)<br><br>    model.print_trainable_parameters()<br>    return model</pre><p>The last step to start fine tuning.</p><pre>from transformers import (<br>    AutoModelForCausalLM,<br>    AutoTokenizer,<br>    set_seed,<br>    BitsAndBytesConfig,<br>    Trainer,<br>    TrainingArguments,<br>)<br><br># create peft config<br>model = create_peft_model(<br>    model, gradient_checkpointing=False, bf16=False<br>)<br><br># Define training args<br>output_dir = &quot;.&quot;<br>training_args = TrainingArguments(<br>    output_dir=output_dir,<br>    per_device_train_batch_size=1,<br>    bf16=False,  # Use BF16 if available<br>    learning_rate=2e-4,<br>    num_train_epochs=3,<br>    optim=&quot;paged_adamw_8bit&quot;, #&quot;adamw_torch&quot; if not mode = 4,8<br>    gradient_checkpointing=False,<br>    # logging strategies<br>    logging_dir=f&quot;{output_dir}/logs&quot;,<br>    logging_strategy=&quot;steps&quot;,<br>    logging_steps=10,<br>    remove_unused_columns=False,<br>)<br><br>    # Create Trainer instance<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset[&#39;train&#39;],<br>    data_collator=data_collator,<br>)<br><br># Start training<br>trainer.train()<br><br># Save the model<br>trainer.save_model(&#39;./pretrained_model&#39;)</pre><p>The parameter <em>per_device_train_batch_size</em> is critical since it determines the amount of memory consumption. The bigger <em>per_device_train_batch_size</em> is, the faster the training will finish; the smaller the lower probability of an OOM error.</p><p>Huggingface trainer saves a checkpoint in a directory named “checkpoint-xxx” every 500 (default) steps. We can run</p><pre>trainer.train(resume_from_checkpoint=&#39;./checkpoint-500&#39;)</pre><p>to resume an interrupted training process.</p><p>Notice that the trainer here saves only LORA adapter’s weights, not the original Llama 2 weights. How do we run inference with the fine-tuned model?</p><pre>from peft import PeftModel<br><br># model is the quantized model loaded using load_hf_model in a previous step<br>model = PeftModel.from_pretrained(model, &#39;./pretrained_model&#39;)</pre><p>Don’t get distracted by peft’s merge_and_unload() method during the process. It would be great if we can load model+adapter in one stroke but it simply does not work as of the writing of this article.</p><h3>If you like this post…</h3><p>Support me with a coffee!</p><figure><a href="https://www.buymeacoffee.com/newhardwarf"><img alt="" src="https://cdn-images-1.medium.com/max/545/1*7Pq-C6d0si0t4vv-j8TGqg.png" /></a></figure><h4>Appendix. Install bitsandbytes on an old GPU machine</h4><p>It takes me a while to figure out how to make bitsandbytes work on my machine. The instructions in the <a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes">huggingface blog</a> are too sketchy.</p><p>Before we begin, bitsandbytes has 2 pre-requisites: i. the operating system has to be Linux and ii. the GPU has to be released after Dec 2017, for example V100 in my case.</p><p>The 1st step is to install pytorch (GPU) with the right CUDA. Find nvidia version by running</p><pre>nvidia-smi</pre><p>in command line. In my case, it’s 11.4. Install the corresponding 11.x (if your nvidia-smi returns 12.1, use 12.x) CUDA version of pytorch.</p><pre>pip install torch==2.0.1 --extra-index-url https://download.pytorch.org/whl/cu117</pre><p>The 2nd step is to install the huggingface libraries.</p><pre>pip install transformers<br>pip install peft<br>pip install accelerate</pre><p>The 3rd step is to install CUDA 11.7 with <a href="https://github.com/TimDettmers/bitsandbytes/blob/main/compile_from_source.md">help</a> from the library author.</p><pre>wget https://raw.githubusercontent.com/TimDettmers/bitsandbytes/main/cuda_install.sh<br># Syntax cuda_install CUDA_VERSION INSTALL_PREFIX EXPORT_TO_BASH<br>#   CUDA_VERSION in {110, 111, 112, 113, 114, 115, 116, 117, 118, 120, 121}<br>#   EXPORT_TO_BASH in {0, 1} with 0=False and 1=True <br><br># For example, the following installs CUDA 11.7 to ~/local/cuda-11.7 and exports the path to your .bashrc<br>bash cuda_install.sh 117 ~/local 1 </pre><p>The last step is to compile and install bitsandbytes.</p><pre>git clone https://github.com/timdettmers/bitsandbytes.git<br>cd bitsandbytes<br># pytorch 2.0 requires cuda 11.7<br>CUDA_HOME=~/local/cuda-11.7 CUDA_VERSION=117 make cuda11x_nomatmul<br>python setup.py install</pre><p>We can check the installation errors by running</p><pre>python -m bitsandbytes</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1b4bcf26f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning is the new training]]></title>
            <link>https://medium.com/@newhardwarefound/fine-tuning-is-the-new-training-b38de5967d98?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b38de5967d98</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Thu, 25 May 2023 15:24:42 GMT</pubDate>
            <atom:updated>2023-05-25T15:24:42.113Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fine-tuning for a pair classification task TwitterSemEval2015</h4><p>LLM embeddings are a blessing. They save NLP practitioners from the trouble of starting from scratch every time. The following is my journey trying to extract the last bit of juice out of LLM embeddings by fine-tuning.</p><h4>Pair classification task</h4><p>In <a href="https://github.com/cocoxu/SemEval-PIT2015">TwitterSemEval2015</a>, we are tasked with solving a pair classification problem. The dataset has 3 columns: text_1, text_2, label. Label is 1 if text_1 is semantically similar to text_2 and 0 otherwise. There are 2 datasets, one training, the other testing. We use Average Precision (ie. Area Under the Precision-Recall curve) to measure models’ performance.</p><h4>Unsupervised methods</h4><p>In unsupervised methods, we ignore the training dataset, convert texts into embeddings and calculate the cosine similarity.</p><p>According to <a href="https://huggingface.co/spaces/mteb/leaderboard">MTEB leaderboard</a>, sentence-t5-xl scores the highest in the task while the commercial text-embedding-ada-002 ranks much lower. My experiment does not support that. Even though text-embedding-ada-002 still scores lower, the two are quite close.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0cfa88b29815a6e676bb9717949ce74/href">https://medium.com/media/c0cfa88b29815a6e676bb9717949ce74/href</a></iframe><h4>Fine-tune ada 1: add a linear transformation</h4><p>OpenAI offers a fine-tuning solution <a href="https://github.com/openai/openai-cookbook/blob/main/examples/Customizing_embeddings.ipynb">here</a> (essentials buried in section 7). The solution modifies the ada embeddings by multiplying a matrix, which is chosen to minimize the mean squared error between actual labels and cosine similarity of modified embeddings.</p><p>After several attempts at hyperparameter tuning (batch_size=32, learning_rate=100, max_epochs=6, dropout_fraction=0), the average precision can be bumped up to 0.8660.</p><h4>Fine-tune ada 2: add a skip connection layer</h4><p>I share your suspicision that the linear layer is not be powerful enough. I adapt the above code to use <a href="https://quaterion-models.qdrant.tech/_modules/quaterion_models/heads/skip_connection_head.html#SkipConnectionHead">SkipConnectionHead</a>. The code is a bit long and I put it in the appendix. This time we only get 0.8605.</p><h4>Fine-tune sentencetransformer</h4><p>Fine-tuning sentencetransformer is much easier but it takes a while for the code to finish. After all, we are playing with a 2.5GB LLM. In the end, it did not raise the precision any further.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f5ea4f09a1525f35700fbc2c717a658/href">https://medium.com/media/4f5ea4f09a1525f35700fbc2c717a658/href</a></iframe><h4>Appendix</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b9fd145fbd48c3fb1df6a43d972a58e/href">https://medium.com/media/3b9fd145fbd48c3fb1df6a43d972a58e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b38de5967d98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LDA can help bust Lance Armstrong]]></title>
            <link>https://medium.com/analytics-vidhya/how-logistic-regression-could-help-bust-lance-armstrong-8d8ac4d6ea12?source=rss-9fa54ceff5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d8ac4d6ea12</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[fishingalone]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 04:04:37 GMT</pubDate>
            <atom:updated>2024-01-09T05:37:42.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*RcJzfWMg66ne7fFT.jpg" /></figure><h4>scikit’s Linear Discriminant Analysis in practice</h4><p>In 2005, French anti-doping agency retroactively tested Lance Armstrong’s urine sample taken in 1999 Tour de France. They found in the sample <em>recombinant erythropoietin</em> (rEPO), a banned substance that boosts red blood cell production and enhances athletes’ endurance as a result. Subsequent investigations uncovered an elaborate doping scheme and led to the downfall of the legendary 7-time Tour winner. Less well known is the role that data science techniques played in the case.</p><h4>Background</h4><p>Human kidney secretes EPO naturally. The hormone regulates red blood cell production and plays an important role in human adaptation to oxygen-deprived conditions at high altitude. In the 90s, the recombinant technology was successfully developed to splice the human EPO DNA into mice’s gene and allows us to harvest EPO from transgenic mice cells. Invented as an anemia drug, rEPO was abused by athletes even before it hit the market. For around 10 years, no practical detection method could tell natural endogenous EPO apart from exogeneous rEPO.</p><p>The golden age of rEPO doping ended with the advent of isoelectric focusing (IEF). IEF essentially subjects purified urine samples to gel electrophoresis under a pH gradient. Due to small differences in surface charges, rEPO samples exhibit different band patterns from natural EPO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*P4l5u75XOVuCaXajoIcTQw.png" /><figcaption>From [1]</figcaption></figure><p>In the picture, the 2nd sample from left (with label “uEPO”) is the pattern of natural EPO. Dark bands outside the endogenous area (pH range of 3.7–4.7) indicate artificial EPO doping. However, normal patterns vary wildly and this is where data science can play a role.</p><h4>Data preparation &amp; EDA</h4><p>In a 2007 study, 116 rEPO positive urine samples were acquired from volunteers who agreed to be administered rEPO. Additional 131 negative samples were acquired as control group.</p><p>Band 0 was identified using a chemical method. Spreading towards two ends, bands in basic areas are numbered 1 through 6 and those in acidic areas 1 through 9. Darkness of the 16 bands is recorded for each sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*sYL2TqQvziFyPvasHU5NfA.png" /><figcaption>From [2]</figcaption></figure><p>Thanks to Jean Thioulouse’ generosity, the dataset was recently made available for public access. There are 2 files: <em>Reference table</em> containing sample data, <em>Reference samples class</em> containing labels (1 positive, 2/3 negative).</p><pre>import pandas as pd<br># Read dataset and preprocessing<br>samples = pd.read_csv(&#39;TabRef.txt&#39;, sep=&#39; &#39;)<br>labels = pd.read_csv(&#39;TabClass.txt&#39;, header=None, names=[&#39;label&#39;])<br>labels.index = range(1, 248)<br>dataset = samples.join(labels)<br>dataset.loc[dataset[&#39;label&#39;]==3, &#39;label&#39;] = 2<br># remove the 4 rows of duplicates<br>dataset.drop_duplicates(inplace=True)<br><br># Normalize the data<br>dataset_norm = dataset.iloc[:, :-1]<br>dataset.iloc[:, :-1] = dataset_norm.div(dataset_norm.sum(axis=1), axis=0)<br><br># Draw box and whisker plots<br>data = pd.melt(dataset, id_vars=[&#39;label&#39;], value_vars=dataset.columns[:-1])<br><br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>sns.boxplot(x=&#39;variable&#39;, y=&#39;value&#39;, data=data, hue=&#39;label&#39;, palette=&#39;pastel&#39;, fliersize=0, gap=.2)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*92gItAYj-ZXGlHTIl9KhZg.png" /></figure><p>There are significant differences between doping and control groups in band 3,2,0,-1,-2.</p><h4>Fisher’s LDA complicated by multicollinearity</h4><p>Jean Thioulouse’ paper originally used <em>Linear Discriminant Analysis</em> (LDA). Fisher’s LDA (2-class) tries to project all data to 1d in such a way that the projections of the 2 classes are maximally separated. More precisely, denote the N data points x, the k classes of data points C_k &amp; the projection vector v. The projected class mean and variance are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*eaRjypxWReBLpcsYz614ww.png" /></figure><p>Fisher’s LDA maximizes the difference between class means while minimizing the within-class variances</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*IXglAvicuEgEMW9aCh_EYw.png" /></figure><p>We are not going to get into details of how to solve the above problem. Scikit has a ready-to-use lda implementation. We set the solver parameter as eigen to apply Fisher’s LDA. However it did not work. Nothing has ever worked on the 1st attempt!</p><pre>from sklearn.discriminant_analysis import LinearDiscriminantAnalysis<br><br>X = dataset.iloc[:, :-1]<br>y = dataset.iloc[:, -1]<br>model = LinearDiscriminantAnalysis(n_components=1, solver=&#39;eigen&#39;)<br>model.fit(X, y)</pre><p>The error message says</p><blockquote><strong>LinAlgError</strong>: The leading minor of order 16 of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.</blockquote><p>It turns out our dataset has multi-collinearity, which becomes obvious when we see a small negative eigenvalue in the covariance matrix.</p><pre>import seaborn as sns<br>import numpy as np<br><br>d = np.hstack([dataset.iloc[:, :5], dataset.iloc[:, 5:]])<br>s = np.cov(d[:, :-1].T)<br>s_viz = s.copy()<br>np.fill_diagonal(s_viz, 0)<br>sns.heatmap(s_viz, cmap=&#39;coolwarm&#39;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*S3GXYiJMzJFv0khgiK9Xcw.png" /></figure><p>After deleting data of band B2, we fit the LDA model again and the histogram of 1d projections is bimodal</p><pre>plt.hist(dataset[: , :-1] @ model.scalings_[:, 0].T)<br>plt.xlabel(&#39;Projection Value&#39;)<br>plt.ylabel(&#39;Occurence&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*fhLsnwUsh5sqzQdqkKa_IA.png" /></figure><p>Once projection vector v is determined, we can classify unseen data by determining whether its projection is closer to \mu_1 or \mu_2. In other words, the decision boundary is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*2VSoSXw6hdtFy0uwhNs70g.png" /></figure><h4>Gaussian LDA</h4><p>Fisher’s LDA above does not make any assumptions about the dataset distribution. There is actually a stronger flavor of LDA that classifies data based on normality assumptions.</p><p>Again we are not going into details. The k-th discriminant function for Gaussian LDA</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*E3_0Q--x2KUdy-MEp5Lq5g.png" /></figure><p>where \Sigma_k is the covariance matrix for the k-th class, measures the Mahalanobis distance between x and the k-th class means \mu_k. To assign x to class k, we select the k with the largest \delta_k (the smallest distance). In a sense, Gaussian LDA is nearest neighbor algorithm.</p><p>We can compare the performance of LDA to logistic regression via stratified 5-fold cross validation.</p><pre>from sklearn.model_selection import StratifiedKFold<br>from sklearn.discriminant_analysis import LinearDiscriminantAnalysis<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score, precision_score, recall_score<br><br>X = dataset[:, :-1]<br>y = dataset[:, -1]<br>skf = StratifiedKFold(n_splits=5)<br>score = 0.0<br><br>for _, (train_index, test_index) in enumerate(skf.split(X, y)):<br>    model = LinearDiscriminantAnalysis(n_components=1) # LogisticRegression(penalty=&#39;none&#39;)<br>    model.fit(X[train_index], y[train_index])<br>    score += accuracy_score(y[test_index], model.predict(X[test_index]))<br><br>print(score / 5.0)</pre><p>LDA’s accuracy of 0.996 beats logistic regression’s 0.975.</p><h4>References</h4><p>[1] <a href="https://www.wada-ama.org/sites/default/files/2023-02/td2022epo_v1.0_final_eng.pdf">WADA Technical Document — TD2022EPO</a></p><p>[2] <a href="https://lbbe-shiny.univ-lyon1.fr/Reproducible_Research/E.Lasne.2007/">Detection of recombinant human erythropoietin in urine for doping analysis: Interpretation of isoelectric profiles by discriminant analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d8ac4d6ea12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-logistic-regression-could-help-bust-lance-armstrong-8d8ac4d6ea12">How LDA can help bust Lance Armstrong</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>