<?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 Xing Zeng on Medium]]></title>
        <description><![CDATA[Stories by Xing Zeng on Medium]]></description>
        <link>https://medium.com/@xingzeng?source=rss-e36a783d923f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nzbp181Ro4YUJ6i69CAc2Q.png</url>
            <title>Stories by Xing Zeng on Medium</title>
            <link>https://medium.com/@xingzeng?source=rss-e36a783d923f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:08:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xingzeng/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[My Reading Notes for “Designing Machine Learning Systems” by Chip Huyen]]></title>
            <link>https://xingzeng.medium.com/my-reading-notes-for-designing-machine-learning-systems-by-chip-huyen-407f40da8477?source=rss-e36a783d923f------2</link>
            <guid isPermaLink="false">https://medium.com/p/407f40da8477</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[design-process]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Xing Zeng]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 23:09:00 GMT</pubDate>
            <atom:updated>2023-06-02T23:09:00.166Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently finished reading <em>Designing Machine Learning Systems</em> by Chip Huyen, so I would like to share some learnings I had from reading this book.</p><p>This book isn’t the type that would go very deep into one topic but is the type that would cover as many topics as it could. I guess that’s exactly the perfect representation of the current state of designing machine learning systems: there are so many components inside of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZaeoAI6gCp_qXGQZI4PjQ.png" /><figcaption>Sculley, David, et al. “Hidden technical debt in machine learning systems.” Advances in neural information processing systems 28 (2015).</figcaption></figure><p>The above figure, despite being published almost 8 years ago, the complexity around the many pieces next to the small ML Code still holds, and can be arguably claimed to have become more and more complicated.</p><p>Among all the topics it covered, here are some of the ones that I, as a Backend Software Engineer working on implementing a Text-based ML system, have found to be most interesting and/or are likely to miss, grouped by the Chapter, and some of the comments I have regarding to the content of it.</p><p>Note that this is not designed to be a general summary of the book. Someone with a very different background and/or position (e.g. Data Scientist) would focus on a completely different part of this book. So, I do recommend trying to get access to this book if possible, one may learn from a different aspect — and the book does cover a lot of different aspects — as I did.</p><h4>Chapter 3 — Data Engineering Fundamentals</h4><p>In a Machine Learning System, it’s common to have three types of data flows:</p><ul><li>Data Passing through Persistent Storage—Everything is stored in a Persistent Storage, each of the different containers/components just reads and writes from the database.</li><li>Data Passing through Service — Use RESTful or RPC framework to create API interfaces to allow different containers/components to interact</li><li>Data Passing through Real-Time Transport — Use a message queue system or pub-sub system to act as a broker that coordinates the passing of the data between different containers/components. The intermediate could either be based on Persistent Storage, partially based on Persistent Storage, or totally not related to Persistent Storage at all.</li></ul><p>In Batch Processing, which often deal with historical data as well as features that changed less frequently, the first two mechanisms are more common. In Stream Processing, where sometimes live data may appear and features can change more quickly, the last mechanism is more common and sometimes even required.</p><p>Recently, there has been more move toward Streaming Processing, as it’s sometimes being seen as a more generic paradigm. Even if you have historical data, you can probably utilize the Streaming paradigm by having a Batch Processing Component that specialized in putting Batch data into a Streaming pipeline. Though I do like to point out that some algorithms, like those to train a neural network and the one operating on the graph, will probably still have to stay as Batch Processing for a very long time. A significant number of neural network training algorithms these days are still not fully online, and graph operations naturally required a complete graph instead of one node or one edge to be operated on.</p><h4>Chapter 6 — Model Development and Offline Evaluation</h4><p>Data Parallelism is still the most common method to train ML models across multiple machines: There is one centralized server that has access to all the model parameters. Other machines can download the model from the centralized server, have access to different data, and can calculate part of gradients just on the data it has in parallel, and submit the gradient back to the centralized server for processing. The difference between whether the parameter service may set up barriers or not for progressing toward the next iteration separates Asynchronous SGD or Synchronous SGD.</p><p>Model Parallelism has also appeared, as an orthogonal direction to Data Parallelism, to speed up the training of larger ML models that may not fit in one machine. When a model’s number of parameters becomes too huge to be stored on only one machine, multiple machines may store only part of the model parameters. In a neural network case, the common approach to utilize such a mechanism is to store a group of layers in one machine, and another group of layers in another machine. This is especially useful for cases where there may be a fully connected component in-between layers, which makes splitting one layer complicated. Note that, this still does not automatically means the processing is actually parallel, since each layer is still dependent on each other. A popular technique for it is when a particular machine is processing the forward pass for one group of layers on the first batch of data, other machines will wait until the first group of layers has been processed. Once this particular data batch has been finished processing, the machine that has the next group of layers will kick in to process this batch, with the machine that has the first layer may start to process the next batch.</p><h4>Chapter 7 — Model Deployment and Prediction Service</h4><p>Depending on the data flows as well as the type of data that needs to predict, there can be:</p><ul><li>Batch Prediction</li><li>Online Prediction that only uses Batch Feature</li><li>Online Prediction that may use Streaming Feature (also called Streaming Prediction)</li></ul><p>Combined with Training — which usually happens in batch but can be made online depending on the algorithm — an important goal is to make sure the Streaming processing and Batch processing should generate the same feature instead of different features on the same data point. To avoid bugs that may result from different implementations of the same logic, one should implement a unified data pipeline that is shared across stream processing and batch processing.</p><p>The unification of the data pipeline may not be trivial — more to come in Chapter 10.</p><h4>Chapter 8 — Data Distribution Shift and Monitoring</h4><p>It is important to continuously monitor the performance of the ML system as Data Distribution shifts may occur. Some monitoring techniques include:</p><ul><li>Monitor accuracy-related metrics, if the user feedback may be immediate. This is common in recommendation systems and active learning scenarios.</li><li>Monitor the distribution of the prediction itself, and check if there is a distribution shift on the predicted labels from the test labels.</li><li>Monitor the distribution of each of the features. This can be more generic, but the min/max/median/histogram would be a good starting point.</li><li>Monitor the raw input. The book claim this may be out of the scope of data science or ML team, but I think it depends more on how the team structure is actually formulated. In my field of Text Processing, this is also where interesting metrics can come along: the length of the Text / the language of the Text / Token distributions within the Text can all be Metric to be monitored. These can also be used as features and thus may fall into the form of a “Monitoring feature”, but there are situations where these features may not contribute much to training a neural network model on text, especially in this ChatGPT era, but they can still be useful for the monitoring team to identify if the data has been shifted, to identify if a LoRA-type of fine-tune may need to be required.</li></ul><h4>Chapter 10 — Infrastructure and Tooling for MLOps</h4><p>(This is my favourite chapter of the book. Indeed, this is the part that’s more related to a Backend Software Engineer ^_^)</p><p>Standardized Dev Environments, either across the company or just across the whole team, will make it easy for a team to debug issues related to different versions related to a different package. When the need for a unified data pipeline may also arise (as in Chapter 7), a standardized dev environment will also make it easier to utilize such a pipeline, which may be developed to be more Production-oriented and thus harder to be deployed in an ad-hoc way. Container is a great way to make such standardization.</p><p>ML Workflows, which are naturally iterative, can be managed through Workflow Management Tools, which will make running workflow and monitoring the progress of workflow much easier. They also contribute to making sharing containers/components easier which is useful for a unified data pipeline. The book gave examples of Apache Airflow &amp; Argo &amp; Metaflow. I have also recently played with some other Workflow Management Tools like Prefect &amp; Temporal. They all have their own pros and cons. I personally prefer Temporal more since it is better at scaling and crash-handling, and it also has more capability in supporting multiple languages.</p><p>Storing a Model in persistent storage may sound easy, but combined with the requirement of monitoring and deployment, it may not be trivial. Using Model Store will make it much easier. MLflow is a very commonly used model store and perhaps the most popular one that’s not associated with a particular cloud provider. I have personally played with it and MLflow’s ability to also wrap around part of the preprocessing functionality makes it a really good choice as a Model Store.</p><p>The book also covered Featuer Store. This is a new concept that focuses either on managing features, or computing features, or maintaining the consistency of features across training and predicting, or all of them. This is also highly related to Chapter 7’s suggestion of building a unified data pipeline. Feast / Tecton are some of the examples that were given as Feature Store Tool one may look into.</p><p>An important section of this book segwayed from the above: for these tools, should one build in-house or consider the buying option? This is, of course, very case-by-case. But I guess, the naturality of this question may raise, does show the current stage of how the MLOps platform has been. This is certainly the best of time, as an immature industry means plenty of opportunities. It’s also the worst of times, I can’t tell how many times I heard of different ML tool startup companies tackling different problems from different angles, and with all these jargon flying around it’s really hard to decide on what to do ;(</p><h4>Chapter 11 — The Human Side of Machine Learning</h4><p>MLOps required ML expertise and Ops (short for “Operation”, usually referring to knowledge from the infra side or backend side) expertise. Companies have been either having two teams for them, or requesting one team to be good at both of them. Both have their own issue: having separated teams have tons of overhead you will have when there is more than one team, and requiring one team to have knowledge on both sides makes an impractical requirement on requiring Data Scientists to understand low-level infratusture. The author claims that the best approach probably lies somewhere in between: a good tool built by those with Ops expertise that abstracts the Ops concept away from Data Scientists, and with that tool Data Scientists may fully own their side of the work without having much need to contact the Ops side of the team. This, obviously, doesn’t eliminate all the communication complexity, but certainly, if the abstraction layer is done good enough, it will make cross-team collaboration much more efficient.</p><p>As a former UBC NLP Lab graduate who thought about becoming a Data Scientist, but somehow in the end turned up to be a Senior Backend Software Engineer, I can feel that I am sort of unique in this standpoint. But I do agree cases like mine are rare, and I feel like my stepping on both sides sometimes ends up me being neither perfect on Infra nor perfect on ML. Either way, the ML system is complicated, and it naturally required collaboration. And just like the author suggests, thinking more about packaging and abstraction is the best way to make collaboration across teams. As for me, who happens to be someone that lives in between, this is my perfect opportunity to think more about what exactly this abstraction should be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=407f40da8477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Case in Gensim Word2Vec Model Memory Usage: Can Not Release the Model through “del”]]></title>
            <link>https://xingzeng.medium.com/a-case-in-gensim-word2vec-model-memory-usage-can-not-release-the-model-through-del-e8af90b93bf9?source=rss-e36a783d923f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8af90b93bf9</guid>
            <category><![CDATA[gensim]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[python-multiprocessing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[word2vec]]></category>
            <dc:creator><![CDATA[Xing Zeng]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 22:50:50 GMT</pubDate>
            <atom:updated>2022-04-11T16:41:32.081Z</atom:updated>
            <content:encoded><![CDATA[<p>I run into a weird case regarding Gensim Word2Vec that forces my program out of memory.</p><p>We have a simple Flask application. For each API call to Flask, it spins up a subprocess through a customized subclass of Python’s own multiprocessing.Process. This subprocess is a long-running process which, as part of its running, it trains a number of different Gensim-based Word2Vec models with different attributes along its way.</p><p>More specifically, each time it finishes training one Word2Vec model, it collects some aggregated statistics related to it, and then we have everything needed for the current Word2Vec model, thus this model can be thrown away. And then it can proceed on training the next Word2Vec model.</p><p>As you can see from the above process, Word2Vec model is never really needed, so every time I finished training, I will have to remove the model from the memory to reduce the memory taken by the Subprocess. More specifically, the code looks like this:</p><pre>def __release_model(self):<br>    # self.wv_model is the name of the word2vec model persisted <br>    # it&#39;s a class attribute because it makes inferencing easier</pre><pre>    del self.wv_model<br>    self.wv_model = None</pre><p>However, that doesn’t seem to work. When my subprocess finished training one Word2Vec model, the memory goes up to 9G. When it finished training the second one, the memory goes up to 18G. Then after the third, it goes up to 27G. I need to train 4 models in one pass of the subprocess, and my computer only has 32G of memory. Of course, Ubuntu won’t be happy, thus a -9 is send to my subprocess.</p><p>One way to fix this is to make the 4 model training into 4 different subprocesses. This is actually the best way to fix it and how I envisioned my program can look like. If I starts making all the model training distributed using Ray, and if I track chained multiple processes coming from one API call using Prefect. However, I am not having enough time to do that migration — it sure will be extremely exciting but I have other matters to attend to also. Also — I feel like it’s extremely weird why Gensim Word2Vec can’t just release memory through del , so I spend some time looking into if I can fix it by updating my __release_model function.</p><p>The result is very much NOT exciting:</p><pre>def __release_model(self):<br>    # self.wv_model is the name of the word2vec model persisted <br>    # it&#39;s a class attribute because it makes inferencing easier</pre><pre>    del self.wv_model<br>    self.wv_model = None</pre><pre>    gc.collect()</pre><p>Basically, just calling Garbage Collector Explicitly, will fix the increasing memory issue I was having.</p><p>While this explicit calling Garbage Collector does not look like the standard recommended way of doing Python programming, after a bit of deep look into the issue this may still be a good way to fix this issue.</p><p>Firstly, we need to understand how Python Garbage Collection work. To do that, I highly suggest reading:</p><p><a href="https://rushter.com/blog/python-garbage-collector/">https://rushter.com/blog/python-garbage-collector/</a></p><p>Basically, Python has two primary modules regarding Garbage Collection. The primary module, reference-counting based, is what del is in ,and this operator can remove the last reference to the model for you. Thus in most cases, this will trigger the data mentioned after del to be removed.</p><p>However, reference-counting based method does not deal with circular dependency. And unfortunately, Gensim’s implementation somehow introduce a circular dependency somewhere, causing del to not work.</p><p>I was able to prove the existence of the circular dependency through:</p><pre>def __release_model(self):<br>    # self.wv_model is the name of the word2vec model persisted <br>    # it&#39;s a class attribute because it makes inferencing easier</pre><pre>    wv_model_id = id(self.wv_model)</pre><pre>    del self.wv_model<br>    self.wv_model = None</pre><pre>    # Code on PyObject can be found in aboved link<br>    # This print 2<br>    print(PyObject.from_address(wv_model_id).refcnt)</pre><p>Couldn’t tell which part of the Gensim actually introduce that dependency. The source code around __init__ looked fine and I wouldn’t have so many time to look into other parts of the source code. So the best I can do is nuke a gc.collect() here.</p><p>That being said, normally, gc.collect() are still be automatically called by the Python when time is appropriate. I do not know why it wasn’t called in time in my case. Each of my training of Word2Vec does take long enough (5 minutes) for gc to be invoked at least once. My guess is that this has to do with the fact that my training is running in subprocess triggers by the main process, and Python may automatically do lower gc in subprocess for some reason. This won’t be surprising to me since if your subprocess terminates, OS is automatically going to recover all the resources for you and you don’t really need to. Anyone who knows more about Python’s gc and subprocess is welcome to shed more light on this matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8af90b93bf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use hprof & gprof2dot to visualize the runtime of your Java application]]></title>
            <link>https://xingzeng.medium.com/use-hprof-gprof2dot-to-visualize-the-runtime-of-your-java-application-a475fc4e0e27?source=rss-e36a783d923f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a475fc4e0e27</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Xing Zeng]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 04:32:20 GMT</pubDate>
            <atom:updated>2020-11-27T04:48:44.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the past years of my working experiences, I have learned a lot of interesting techniques from my colleagues. Today I like to share one of them regarding how to visually do performance profiling in Java, utilizing Java’s standard hprof and an open-source application called gprof2dot.</p><p>Such visualization will give you a graphical representation of how the functions inside your code are called. Utilizing this graph, you can understand which part of your program takes the longest runtime and optimize it accordingly.</p><h3><strong>Installing</strong></h3><p>gprof2dot lies at <a href="https://github.com/jrfonseca/gprof2dot">https://github.com/jrfonseca/gprof2dot</a>. You may follow the install instruction there to install it and its corresponding dependencies.</p><p>Just one side note regarding installing from pip for Python newbies: if you installed it in sudo mode or installed it on a mac, this will result in <strong>/usr/local/bin/gprof2dot</strong> and the program should be accessible in your current folder. If not, it should either be in your virtualenv executable folders or under <strong>~/.local/bin/gprof2dot</strong>. Under both circumstances, you may need to set up the<strong> $PATH</strong> variable manually if you have not already done so.</p><h3>Running</h3><p>First, run your target Java program in this way to generate the hprof file:</p><pre>java -agentlib:hprof=cpu=samples,interval=20,depth=20 -jar target.jar</pre><p>This will generate a text file named <strong>java.hprof.txt</strong></p><p>Then run the following:</p><pre>gprof2dot -f hprof java.hprof.txt | dot -Tpng -o output.png</pre><p>This will generate the <strong>output.png</strong>, which is the final visualization file.</p><h3><strong>Example</strong></h3><p>Following is a sample code I have which we can use to test the method in this post.</p><p>[SPOILER ALERT] Contains the solution for Leetcode 1466, do not read it if you want to attempt it yourself some time in the future!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/609bda143b570e7c863a08c2567d700a/href">https://medium.com/media/609bda143b570e7c863a08c2567d700a/href</a></iframe><p>The above code generate a runtime graph that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8vqJ1OJylTblrkP-s7PhA.png" /></figure><p>(For full resolution, please visit: <a href="https://www.flickr.com/photos/191200776@N03/50651336101/in/dateposted-public/">https://www.flickr.com/photos/191200776@N03/50651336101/in/dateposted-public/</a>)</p><p>Here’s how I read this graph &amp; how I can use this graph to improve my performance to the solution of Leetcode 1466:</p><ol><li>Two trees to the right, each accounted for 1.37% of the runtime, is related to a separate thread regarding my usage of Java’s lambda function, since they don’t take too much time, I will just ignore them.</li><li>To the left, you got the <strong>main</strong>, which is the entry point to the main thread.</li><li>The <strong>minReorder</strong> called by <strong>main</strong> is the core part of my solution which takes most of the time, 94.52% of the time. This makes sense since that’s the question asked by Leetcode with the other function being just used to create a sample data. Let’s break it down:</li><li>21.92% of the total runtime is being used for basic operation within <strong>minReorder</strong> that does not involves calling other functions yet. This includes maintaining the for loop, collecting the response from one function and prepare to pass it to the other,</li><li>46.58% of the total runtime is being used by my <strong>dfs</strong> function, which also makes sense since that’s the primary approach to Leetcode 1466.</li><li>Going down the tree from my <strong>dfs</strong> functions, different streaming associated functions have taken different runtime to maintain the iteration I have inside my function, until you reach the core part of my iteration, which is the <strong>lambda$dfs</strong> function I have that I used to iterate over <strong>nextNodes</strong>. This takes 31.51% of the total runtime.</li><li>Then I realize a significant portion of <strong>lambda$dfs</strong>’s child — mathematically would be 6.85% / 31.51% = 21.74% — of the time, it is calling <strong>buildHashableConnection </strong>to the left, a function I wrote in my code. This function is also called by <strong>minReorder </strong>all the way from the above. In total, this function takes 16.44% of the time. <strong>This is one place where I can identify a location to optimize my performance by looking at the graph</strong> — why do I have to spend 16.44% of my time just constructing a String out of Integer that there is no real point to use?<strong> </strong>Why can’t I just hash Pair&lt;Integer, Integer&gt;? Oh yeah, I forget, I wanted to test my code on Leetcode Platform, which it does not support outside libraries :( so happy hacking that is.</li><li>Then I can see that <strong>lambda$dfs</strong> + its child is also spending a lot of time trying to add items to HashSet. In together with another call from <strong>minReorder</strong>, all <strong>HashSet.add</strong> operation takes 35.62% of the total runtime with 10.96% / 35.62% = roughly 1/3 being trying to hash the key and another 21/02% / 35.62% = 2/3 being trying to put the value actually into the set, and a very small portion of it being as part of the basic operations of the <strong>HashMap.put</strong> function. <strong>This is another place where I can identify a location to optimize my performance by looking at the graph</strong> — can some of the Java Set be turns to a List? Maybe some could, for instance, the one from <strong>adjacencyList</strong>, which the heck is even named after a List yet I used a Set. The Set add operation associated with the adjacencyList takes 13.70% of the total runtime. Here, the input format already guarantees no duplicates, so a set is not needed. The reason why I still did a Set is because I just don’t want to argue with that since it no longer affects Big(O), and usually with a good Big(O) my solution is already good enough to be accepted by Leetcode, so I was happy with a Set when I first tried to implement it.</li></ol><h3>Some of my personal advices regarding to how to use this tools</h3><h4>Make sure you have an efficient algorithm first</h4><p>As you can see from the example above, had there been an issue in my algorithm — let’s say that instead of actually doing Depth-first Search in the <strong>dfs</strong> function I did some strange brute force algorithm that has some weird O(n³) runtime complexity, then this graph won’t be helpful as the best it could do is proportionally adding more runtime to the <strong>dfs </strong>and its children — which there ain’t that much to add since this is already the entry point to the bulk of our workload. So you will result in a similar graph, and you can conduct a similar analysis, except your analysis would be wrong, as the primary place where you could improve your runtime performance is to improve your algorithm, not trying to call function that you don’t need to call.</p><h4>Test the performance of API by writing an executor</h4><p>There are situations where you may want to test the performance of, let’s say:</p><pre>curl -X GET your_server_host:your_server_port/endpoint</pre><p>Doing that through my approach is possible but has some concerns:</p><ol><li>You will get a lot of garbage related to how to start a service which may not be easily distinguishable from the API call you would like to fire,</li><li>Imagine that once this API finishes — and do note that some API could be Async by its nature— you have to quickly kill the jar to avoid some other garbage being dumped into your graph.</li></ol><p>My recommended way to solve this problem is to write an executor — basically, a standalone class that has the <strong>main</strong> function, that at best loads your dependency injection libraries and then ignore all the server setup stuff but just call the core logic of your API afterward. Then, you can call the jar that includes both the API you want to test and the executor you just wrote in this way:</p><pre>java -agentlib:hprof=cpu=samples,interval=20,depth=20 -cp target.jar package.path.to.your.Executor</pre><p>This will generate the hprof file that includes minimal extra information and then you can analyze that from gprof2dot easily.</p><h4>Apache Spark</h4><p>Do note that the above approach does not work with Apache Spark directly, since Spark jobs are mostly running on the Spark worker, which is a separate JVM from your main JVM. That being said, this is not the end of the universe:</p><ol><li>Spark worker nodes are, by their nature, still JVMs. So you can add the hprof arguments to your Spark worker nodes, get the hprof file, and then generate a visualization on top of it.</li><li>If you are utilizing some of the more unified distributed processing libraries to call Spark for you e.g. Apache Beam, these libraries may support running in standalone mode besides running in Spark mode, where running in the standalone mode usually means running in the same JVM as the one your main Application is in. Doing performance analysis in Standalone mode may already be good enough to reveal enough information regarding where can you improve your performance.</li></ol><h4>What if the final graph is only garbage of epollWait?</h4><p>Well, that’s my daily life:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*J75OswTrMc7n7TG-esXQMA.png" /></figure><p>When this happens, one thing to consider is to lower gprof2dot’s default min sample threshold, all the way down to 0:</p><pre>gprof2dot -n0 -e0 -f hprof java.hprof.txt | dot -Tpng -o output.png</pre><p>This is because gprof2dot by default ignores “nodes and edges with little or no impact in the total computation time”. By lowering the threshold, you will get them back.</p><p>Do be noted that to make this effective, it is highly recommended that you have a lower interval and higher depth when doing java hprof so that in CPU sampling a sample is more likely to hit a class of your interests.</p><p>If we consider all the classes that appear in the original <strong>java.hprof.txt</strong> file, it will be easy for us to identify what are some of the other calls going around at that time. These calls, while not consuming much of the total computation time, might be responsible for creating the thread that is responsible for most of the total computation time, and will give you a good understanding of what type of operations is your program is trying to achieve in a while it was doing the waiting.</p><p>In my example, I was able to use the 0 threshold graph — unfortunately I can not show it in full since it includes some other information but I can explain verbally —to do my analysis. In this graph, there is a tiny link leaving <strong>io.netty.channel.nio.NioEventLoop.run</strong> in the middle of the original graph going down towards something inside <strong>org.elasticsearch.</strong> This shows that the epollWait comes from Elasticsearch API calls.</p><p>After identifying what causes epollWait, the next step is to understand why this happens. This usually happens in a scenario where your code is making an external API call. And this whatever API call you are making to the outside — in my case, a call to Elasticsearch — is spending too much time waiting for the response to get back instead of actually processing the data it returns. Here you may have a lot of options you can try to pursue in order to reduce the percentage of runtime being spend on useless waiting, which are not the topic of this publication so I will just stop here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a475fc4e0e27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MinHash in Lucene / Elasticsearch]]></title>
            <link>https://xingzeng.medium.com/understanding-minhash-in-lucene-elasticsearch-e6799b78c0d7?source=rss-e36a783d923f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6799b78c0d7</guid>
            <category><![CDATA[lucene]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <dc:creator><![CDATA[Xing Zeng]]></dc:creator>
            <pubDate>Fri, 06 Mar 2020 02:50:04 GMT</pubDate>
            <atom:updated>2020-12-18T02:50:47.139Z</atom:updated>
            <content:encoded><![CDATA[<p>MinHash is a quite common technique in Information Retrieval. Just in case if you had never heard of it, here is the explanation of how it worked on Elasticsearch’s reference page:</p><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-minhash-tokenfilter.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-minhash-tokenfilter.html</a></p><blockquote><em>A general idea of the way MinHash produces a signature for a document is by applying a random permutation over the whole index vocabulary (random numbering for the vocabulary), and recording the minimum value for this permutation for the document (the minimum number for a vocabulary word that is present in the document). The permutations are run several times; combining the minimum values for all of them will constitute a signature for the document.</em></blockquote><blockquote><em>In practice, instead of random permutations, a number of hash functions are chosen. A hash function calculates a hash code for each of a document’s tokens and chooses the minimum hash code among them. The minimum hash codes from all hash functions are combined to form a signature for the document.</em></blockquote><p>That explanation, however, does not match with settings described by Elasticsearch in order to configure MinHash correctly:</p><blockquote><em>hash_count :</em></blockquote><blockquote><em>The number of hashes to hash the token stream with. Defaults to </em><em>1.</em></blockquote><blockquote><em>bucket_count :</em></blockquote><blockquote><em>The number of buckets to divide the minhashes into. Defaults to </em><em>512.</em></blockquote><blockquote><em>hash_set_size :</em></blockquote><blockquote><em>The number of minhashes to keep per bucket. Defaults to </em><em>1.</em></blockquote><p>Note that the hash count defaults to be 1, which does not match with the explanation of “a number of hash functions are chosen”. While at the same time, the number of buckets is still significantly big to result in a signature of higher dimensionality.</p><p>A deeper look into Lucene’s MinHashFilter.java code explains how does it actually work.</p><p>The MinHashSet are created from the following lines:</p><pre>this.hashCount = hashCount;<br>this.bucketCount = bucketCount;<br>this.hashSetSize = hashSetSize;<br>this.withRotation = withRotation;<br>this.bucketSize = (1L &lt;&lt; 32) / bucketCount;<br>if((1L &lt;&lt; 32) % bucketCount != 0)<br>{<br>  bucketSize++;<br>}<br>minHashSets = new ArrayList&lt;&gt;(this.hashCount);<br>for (int i = 0; i &lt; this.hashCount; i++) {<br>  ArrayList&lt;FixedSizeTreeSet&lt;LongPair&gt;&gt; buckets = new ArrayList&lt;&gt;(this.bucketCount);<br>  minHashSets.add(buckets);<br>  for (int j = 0; j &lt; this.bucketCount; j++) {<br>    FixedSizeTreeSet&lt;LongPair&gt; minSet = new FixedSizeTreeSet&lt;&gt;(this.hashSetSize);<br>    buckets.add(minSet);<br>  }<br>}</pre><p>Main points here:</p><ol><li>The bucketCount is the same as what ES has claimed, it refers to the size of the signature where each signature is a place where some sort of “recoding the minimal value” will happens</li><li>The hashSetSize is an extra functionality ES supported so that on one bucket, you can store more than 1 minimal value.</li></ol><p>This explains why if you increase them, you would be more likely to get higher precision, as they can be seen as increasing the dimension of the minHashSet variable, which in turns reduce the likelihood of dissimilar document to collide on a smaller dimensioned space.</p><p>The way how hashCount work and how it was able to deal with 512 buckets with one hash function is located at where the values of minHashSetis being actually created:</p><pre>while (input.incrementToken()) {<br>  found = true;<br>  String current = new String(termAttribute.buffer(), 0, termAttribute.length());<br><br>  for (int i = 0; i &lt; hashCount; i++) {<br>    byte[] bytes = current.getBytes(&quot;UTF-16LE&quot;);<br>    LongPair hash = new LongPair();<br>    <em>murmurhash3_x64_128</em>(bytes, 0, bytes.length, 0, hash);<br>    LongPair rehashed = <em>combineOrdered</em>(hash, <em>getIntHash</em>(i));<br>    minHashSets.get(i).get((int) ((rehashed.val2 &gt;&gt;&gt; 32) / bucketSize)).add(rehashed);<br>  }<br>  endOffset = offsetAttribute.endOffset();<br>}</pre><p>Now Recall that, if we ignore the remainder which are minor and does not appears for the default parameter:</p><pre>bucketSize = (1L &lt;&lt; 32) / bucketCount</pre><p>which implies</p><pre>(rehashed.val2 &gt;&gt;&gt; 32) / bucketSize<br>= (rehashed.val2 &gt;&gt;&gt; 32) / ((1L &lt;&lt; 32) / bucketCount)<br>= bucketCount * (the upper 32 digits of rehashed.val2 / 2 ** 32)</pre><p>This means that, for a particular hash function, it will at most only place you into one of the buckets, based on what the hash value is. This resulted in the two following:</p><ol><li>One token will affect at most one bucket if ignoring rotation.</li><li>Assuming Simple Uniform Hashing Principles and a long enough document, for every bucket, there exists a token in the document that will fill this particular bucket.</li></ol><p>It should be easy to see that such an approach will still work on finding similar documents, as dissimilar documents are still going to be more likely to have different values in the bucket resulted from different hashing values.</p><p>Another way of thinking about how this unorthodox way of doing MinHash would work is to think from how would you deduce this algorithm from the regular MinHash algorithm. Basically, you can assume for a particular token, it will never become the minimal element of all other buckets except one. This suggests that at least for a particular carefully created group of documents, whatever the signature one may get from Lucene’s MinHash, is still going to have limited differences from what one may get from a more regular MinHash function, depending on how many of the token would actually result in a smaller value in some other buckets.</p><p>This also explains why if you increase hashCount, you will have a higher recall, despite the fact that you are also increasing the dimension of the minHashSet. The point is that as the hash function never interferes with each other, so whatever similar document that is unfortunately not being mapped to enough similar values by the first hash function may get recovered by the second hash function.</p><p>As for why Lucene used this type of rather an uncommon strategy to deal with LSH, I am not really sure. One benefit I do found is that having only one hash function is much faster than maintaining multiple hash functions. Anyone who is willing to shed some light on it is very welcome.</p><p>Updates on December 17, 2020:</p><p>I’ve been reading a book, <a href="http://www.mmds.org/">Mining Massive Datasets</a>, recently, just to learn more about some of the standardized processes in Data Mining is as I have never got a chance to formally take such a course in School. Apparently, Lucene’s approach is very similar to a recommended speed up method mentioned in Section 3.3.7 of this book.</p><p>The book quoted:</p><blockquote><em>…we divide the rows of M into k/m groups. Then for each hash function, we compute one minhash value by examining only the first m rows of M, a different minhash value by examining only the second m rows, and so on. We thus get k/m minhash values from a single hash function and a single pass over all the rows of M. In fact, if k/m is large enough, we may get all the rows of the signature matrix that we need by a single hash function applied to each of the subsets of rows of M.</em></blockquote><p>Where here:</p><ul><li>M is, originally in the book, a matrix with each row representing all possible elements in a Set (i.e. possible shingle of tokens), and column representing a Set that has contained some of the elements (i.e. documents)</li><li>k is the number of all possible elements</li><li>m is the size of “group” where each “group” is only allowed with some members of k but not the other</li><li>Thus, there are k/m group that doesn’t touch each other, i.e. “one token will affect at most one bucket if ignoring rotation”</li></ul><p>Combining the above and using only one hash function you get the default minhash algorithm in Lucene.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6799b78c0d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>