<?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 Ameya on Medium]]></title>
        <description><![CDATA[Stories by Ameya on Medium]]></description>
        <link>https://medium.com/@ameya_s?source=rss-793f3e5d88dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LSD3L9Go1syPkZ5P.</url>
            <title>Stories by Ameya on Medium</title>
            <link>https://medium.com/@ameya_s?source=rss-793f3e5d88dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:00:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ameya_s/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[C-Store: A Columnar Database]]></title>
            <link>https://medium.com/@ameya_s/c-store-a-columnar-database-1fe7e84d7247?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe7e84d7247</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[distributed-database]]></category>
            <category><![CDATA[columnar-databases]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Fri, 05 Apr 2019 17:14:44 GMT</pubDate>
            <atom:updated>2019-04-05T17:14:44.691Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p><a href="http://db.csail.mit.edu/projects/cstore/vldb.pdf">C-store</a> was one of the earlier database designs that lead to a progression of databases that were centered on column oriented approaches for storage. Before that, the common design pattern was to store the database records as contiguous rows. C-store focuses on read-optimized workloads such as a data warehouse and also supports infrequent write workload. There are a bulk of applications such as Data warehouses or CRMs that need to load data once and do multiple interactive queries on that data. Such workload would benefit from being read-optimized. With column-oriented databases, one can bring only required attributes/columns into the memory and do the necessary analysis on it. If that data was stored in a row-oriented manner, a lot of unnecessary attributes would need to be accessed or brought into memory. Another additional advantage of column oriented storage is that attributes of the same column are of the same data type and hence can be encoded for efficient storage and retrieval (For row oriented storage — this becomes tricky). C-store stores a group of columns sorted on some key, in a physically contiguous space — such group is called a projection. In addition, C-Store assumes a distributed architecture where different projections might land on different nodes in the system. C-Store supports k-safe failure mode i.e.the database is accessible and data is recoverable/queryable even if k nodes in the system fail. Since the same column might belong to multiple projections and those projections might land on different nodes, there is a natural redundancy in the system which helps in case of node failures.</p><p>In order to support read-optimized workload and to avoid concurrency/locking issues with write based workload, C-Store utilizes two logical sets: Writable-Store(WS) and Readable-Store(RS). All the writes happen to WS and a tuple mover component moves the changed records using a merge-out process periodically to the RS. To support lock-free access to RS, a snapshot of RS(upto the very recent past) is created which can then be used for querying without any locks — this mechanism is called as snapshot isolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*TGQOwGIZ1dRWeRdMBSbgOg.png" /><figcaption>High-level components of C-Store</figcaption></figure><h4>Data Model</h4><p>C-Store supports traditional database models of tables comprising of columns as attributes and concepts of primary keys and foreign keys. Most row stores physically store the data in the tabular format with indices used to speed up the access. C-Store only stores column families(projections) in a physically contiguous manner. The C-Store projections consist of a column from a given table — this column is the anchor of the projection. The same projection can contain other columns from the same table or other tables as well as long as the anchor can be mapped to the foreign table. For example, if there are two tables called EMP(name, age, salary, dept) and DEPT(dname, floor), then a projection EMP1 could be:</p><p>EMP1: (name, dept, DEPT.dname | name)</p><p>For the projection EMP1, each column is stored separately. The order of the values in this projection is dependent on the sort key, here indicated by the column name after the character ‘|’. Every such projection is divided into one more segments and each segment is given an SID. This segmentation is based on the sort key and hence each segment basically represents the range of keys for that segment. One important thing to note here is that, all rows/values in the database should be reconstructable from the various projections — this is called a “covering set” of projections.</p><p>In order to represent the entire table or all records that a query should return, <strong>Join indices and Storage Keys</strong> are used. Storage keys are used to represent a logical row or a tuple in the given segment. Storage keys are stored in WS, but are not stored in RS. Join indices use Storage Keys to create the original tables across multiple segments. If two projections T1 and T2 can cover an entire table, then the join index entry consists of (Segment ID, Storage Key) of T2 for the corresponding keys in T1. Here is an example of a join index that maps EMP1(name, age| age) projection to EMP3(name, salary| salary).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*Ey04_TdbiYp55RUDFbXKxw.png" /><figcaption>Join index based on the “name”</figcaption></figure><p>Maintaining join index is expensive. Any update to a projection leads to an update of the incoming or outgoing join index.</p><h4>RS: Read optimized store</h4><p>The read optimized store uses efficient encoding schemes based on the distribution of the data in the columns e.g. For a column consisting of a few unique values, it can use a run-length encoding kind of scheme that can be described as (occurrence in the column, value, frequency). Similarly for a column consisting of many distinct values, one can store the first value in the column followed by deltas from the first value — this will help reduce the overall size needed to store deltas and hence the column. Join indices are also stored in the RS — as we discussed earlier, it is really two columns consisting of (segment id, Storage key) tuple.</p><h4>WS: Write optimized Store</h4><p>This is where all the recent modified data resides. It makes sense to have similar structure for WS as RS to avoid writing query optimizers differently. Only difference that exists in WS is that the columns are not stored in an encoded format — to facilitate ongoing updates. There is 1:1 mapping between WS and RS — sid and storage-key(SK) identify the same tuple in both. sid is explicitly stored in the WS. A new sid is created when a new value is inserted in WS. A column is represented as (value, SK) pair. B-trees on SK are used to represent these columns. In addition the entire projection is represented as (s, SK) with s being the sort key. Combination of sort index and the raw storage key based index one provides efficient access to attributes while scanning/querying.</p><h4>Storage management</h4><p>Segments is the unit of operation in C-Store. Due to the distributed nature of the database, it uses a storage allocator to assign particular segments to particular nodes. Some ideas presented in the paper include colocating the following: same columns in the projection, same segments of RS and WS, the sender segment like EMP3 and the join index in the figure above.</p><h4>Updates and Transactions</h4><p>Inserts happen in WS and it means updating all the columns in the given projection and also the sorted-key column. This change can first land at any of the nodes in the system and so this node is responsible for creating a new storage key for this entry. A unique storage key is obtained by node_id + local_counter combination. This local_counter is unique and greater than the largest key in RS to ensure a unique value across all nodes. Locking is minimized by using snapshot isolation — the central idea being read queries use some snapshot in the past which is immutable.</p><h4>Snapshot isolation</h4><p>To provide snapshot isolation, it is important to note the epochs(time-ranges) at which the records were inserted or deleted. WS maintains an Insertion vector(IV) and a Deleted record vector(DRV) for every logical record in a given segment. All the records inserted or deleted before Low watermark(explained later) are visible to any query. Looking at IV and DRV, the execution engine can figure out if the record should be visible or not to this query. If you think of time from top to bottom, the high watermark(HWM) denotes the time at which snapshot isolation ran. Low watermark(LWM) indicates the latest time at which a read-only query can be run on the snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*EuUcmLtXdJXs3oYcOUYqrQ.png" /><figcaption>Establishing and maintaining HWM and epochs</figcaption></figure><p>C-Store doesn’t track time with high fidelity. It divides time into epochs(few seconds or more) and then provides snapshot isolation based on the epoch number. As shown in the figure above, there is a timestamp authority(TA) which assigns epoch to all nodes and maintains the HWM. It sends the “start of epoch” message to all nodes to indicate that new epoch should start. Each node sends the “Epoch complete” message back when some transactions from the earlier epoch e are done. When TA gets all the complete messages back, it announces the new HWM of “e” to all the nodes — this is the isolated snapshot. Current epoch in the system is e + 1 which is being updated, but not visible to queries. The tuple mover ensures that no records in the RS were created after LWM — this helps RS to not maintain the IV.</p><h4>Distributed Commits</h4><p>To support commits across different nodes, each transaction gets a master. The master is responsible for splitting the work of the transaction and assigning it to many nodes. Master waits for all nodes to finish their work. Then it sends the “commit” message to all nodes and can release locks and delete the UNDO log when all nodes have gotten that message.</p><h4>Recovery</h4><p>Recovery consists of 3 main cases:</p><ol><li>When the failed node has data intact. In that case it can be recovered by executing updates that were queued somewhere else.</li><li>If both WS and RS failed and suffered data loss on the given node, then it needs to be reconstructed using projections and join indices at other site</li><li>The most common case is when RS is intact, but WS is damaged. This scenario can be dealt with efficiently given that it is the most common scenario. Paper contains more details on this.</li></ol><h4>Moving tuples</h4><p>Tuple mover is a merge process that runs in the background to move qualified blocks of tuples from WS to RS. LWM is essentially the earliest effective time at which a read-only transaction can be run. The tuple mover needs to ensure that all the transactions before LWM are available in RS. The tuples in WS with deleted timestamp less than LWM are discarded as they should not be visible to any query. Newly inserted tuples are added to RS. This merge is performed by using a new temp segment. This means that each tuple gets a new storage key and SID. This implies that join indices also need to be maintained.</p><h4>Conclusion</h4><p>C-store introduces a columnar database with a novel concept of isolating WS for efficient writes and RS for efficient read-heavy workload. It also supports distributed committing mechanism using a transaction master, thus supporting a fully distributed database. Encoding schemes not covered in this post(are in the paper) also provide an efficient mechanism for effective storage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe7e84d7247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clipper: High throughput, Low latency, real time inference engine]]></title>
            <link>https://medium.com/@ameya_s/clipper-high-throughput-low-latency-real-time-inference-engine-40f44280f563?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/40f44280f563</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Tue, 08 Jan 2019 23:23:12 GMT</pubDate>
            <atom:updated>2019-01-08T23:23:12.552Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Classical ML applications generally consist of two phases. First phase is using a lot of data to train models and the second phase involves drawing inference from previously unseen data. A lot of previous work in ML infrastructure space has been about scaling the first phase i.e. model training — This is where a lot of compute is spent and previously discussed papers such as <a href="https://medium.com/coinmonks/parameter-server-for-distributed-machine-learning-fd79d99f84c3">parameter server</a> focus on using distributed systems for scaling purposes. There hasn’t been similar focus on inference or prediction scaling where a a big request flood might overwhelm the ML inference or prediction system. <a href="https://www.usenix.org/system/files/conference/nsdi17/nsdi17-crankshaw.pdf">Clipper</a> focuses on this second phase of the ML workload. In addition, clipper provides an ability to deal with ever growing list of ML frameworks such as TensorFlow, Caffe, Spark, Scikit-learn by abstracting those frameworks out into a common layer. Since the intended use-case is for real-time applications, Clipper reduces and places a bound on latency while maximizing throughput. Clipper also provides novel ways to select a particular model(or use ensemble) to improve the accuracy and reliability of predictions.</p><h4>Challenges with real-time inference system</h4><ol><li>There are a large number of existing frameworks to deal with and more being developed. This poses substantial challenge for application developers. In addition, machine learning applications use modify-deploy-modify iterations all the time. Hence one may need to change to use a much bigger dataset and hence use a distributed model training framework which may not have been necessary when the model development started. Sometimes developers may have to deal with many frameworks, since some frameworks are only optimized for model training. Clipper addresses these issues by adding a model abstraction layer and providing a common interface between model abstraction and various frameworks.</li><li>For real-time applications, bounded latency, in orders of few milliseconds, is important. Most ML frameworks are optimized for offline batch training, but not for batch inference. Batched queries for inference can benefit for BLAS or GPU/SIMD, but current ML training frameworks are only optimized for point queries. Some complex ML applications combine many models to improve accuracy, but it comes at the cost of increased tail latencies and straggler models that may not converge quickly. Clipper improves latency by adaptively batching queries and maintaining bounds on latency. Clipper also implements straggler mitigations to reduce latency at the cost of reduced accuracy.</li><li>Many applications test out multiple models and try to choose the best one by either doing offline testing on stale data or online A/B testing. Offline analysis can be inaccurate due to reliance on stale data, while online A/ testing leads to selection on a static model that may not perform well in the future either due to feature corruption or concept drift. In addition, some models may be more suited for certain regions or certain users(consider speech). So Clipper provides an online model selection algorithm. It also improves accuracy by using prediction from ensemble of models.</li></ol><h4>System architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*A1CZr2-Pmc87jBMVzGqXBg.png" /><figcaption>Clipper architecture abstracting multiple ML frameworks and model selection dealing with end user applications</figcaption></figure><p>To trace a request through clipper, let’s start with the top layer. Front-end application issues an inference query to the clipper framework. <strong>Model selection layer</strong> then selects model(s) based on available feedback for this application/query and dispatches the query to the model abstraction layer. <strong>Model abstraction layer</strong> then looks for cached results and returns if it has those in the cache. If not, then inference query is added to the queue for the given model container. This queue adaptively batches queries based on the model and framework before sending it to the model. Once results come back, cache is populated with the results. Model selection layer then combines results to give out final prediction and also provides a confidence estimate if more than one model was used. This final result is used by the front-end application and that provides feedback to the model selection layer for improving future selection of models.</p><p><strong>Model abstraction layer:</strong></p><p>Model abstraction layer consists of two important functions — Caching and batching.</p><p><strong>Caching</strong> is done using two APIs. First one is “Request”. When inference is needed, a query is assigned to cache using this non-blocking “Request” call. If results are in the cache then they are returned. Otherwise, the API indicates that the result is not available in the cache and the cache issues the query to the model. Another call “Fetch” can be used to check for availability of results — almost like in a polling manner. Clipper uses LRU for cache eviction. Caching is really useful for returning answers to popular content and offload some work from models.</p><p><strong>Batching</strong> is done to improve throughput of machine learning frameworks by amortizing cost of multiple RPCs and by data parallel optimizations and better utilizing system resources — such as copying data to GPU memory. Batching layer knows about the ML framework that it is dealing with and batches queries accordingly. Throughput in this case comes at the expense of latency since the batching layer now needs to wait for all results to come back. This is addressed by asking for specific SLOs for latencies. Applications define this SLO and batching layer maximizes throughput using this SLO as a constraint. While batching is adaptive, maximum batch size is used to meet the latency SLOs.</p><p><strong>Adaptive batching</strong> works to find the right size for the given batch. One way clipper does this is by using “Additive increase multiplicative decrease” (AIMD) policy. That is clipper keeps on increasing batch size in constant increments while SLOs are being met. As soon as latency SLO misses, the batch size decreases multiplicatively. This strategy is simple and works very effectively and is the default that clipper provides. Another approach that the authors explored was to use a quantile regression in the 99 the percentile of tail latencies and set the max batch size accordingly. This performs similarly to AIMD and is not as simple to implement due to computational complexity associated with quantile regressions.</p><p><strong>Delayed batching</strong> is useful when workload is bursty or moderate. In such cases, the optimal batch size chose for the given framework may not be reached. In such cases, batches can be delayed by a few milliseconds so as to accumulate more queries. Such approach benefits some frameworks such as scikit-learn which uses BLAS for optimizations. Data from the paper shows 3x improvement for scikit-learn by delaying batches upto 2 ms.</p><p><strong>Model Selection Layer:</strong></p><p>Model selection layer allows for dynamically selecting models that yield good results. Quality of results can be established using some feedback from the client applications. In addition, combination of multiple models can disregard failing models. Clipper continuously learns the feedback from the performance of the models and hence obviates the need for manual intervention for model selection.</p><p>Clipper provides a State data structure(S) that can be used for contextualizing model selection policy, a model selection API that depends on state S, a way to combine results of the query that can yield best results(can also provide confidence score on the results) and the “observe” API that can update state S to reflect the feedback. As for the model selection, clipper provides two algorithms off the bat. One is computationally cheaper — exp3 which depends on selecting a single model and another one is ensemble approach which combines results from multiple models, but at the cost of more computation. Using these approaches, application developers can select appropriate policy depending on their needs.</p><p><strong>Single model selection</strong></p><p>In this approach, only one model is chosen at a time for the given query. Selecting a model depends on how the model has performed before. Similar to <a href="https://medium.com/@ameya_s/introductory-notes-of-reinforcement-learning-3ec29a2e1822">k-bandit problem</a> in reinforcement learning, there is an explore and exploit tradeoff. Exp3 chooses a model and based on the error feedback, updates the probability of selecting the same model again. Exp3 is much more efficient compared to manual experimentation or A/B testing. Some details on exp3 are as follows:</p><p>If si is the confidence with which a model is chosen and L(y, yˆ) is the loss function between obtained output versus the expected one, the new confidence is updated as: si = si * exp(−ηL(y, yˆ)/pi), here η can be considered as learning rate or how quickly the si converges to an optimal solution. The probability of selecting a particular model is given by: si / (summation of si’s for all models)</p><p><strong>Ensemble model selection</strong></p><p>Ensembles(multiple models) have been pretty effective in providing accurate results. Many Kaggle competitions are won by ensembles. The overall idea is that instead of using a single model, many models trained on different subsets of data can be more effective in generalizing and predicting. Clipper uses linear models with weighted average of base model predictions. Clipper relies on exp4 algorithm which out of scope of discussion of this paper. This ensemble approach obviously comes at the cost of computation because of the need to evaluate multiple base models.</p><p>Having looked at both exp3 and exp4, model selection comes in very handy if model degrades for some reason. Due constant feedback loop in the clipper, it will choose some other mechanism or model and reduce the error rate. Below are the results of an experiment in which authors simulated errors and clipper responded by keeping the overall error rate low. In this case, errors were introduced in the model 5 between 5K to 10K queries. While error rate suffers drastically for model 5, both exp3 and exp4 divert queries to other models and maintain relatively low overall error rate. Once model 5 recovers, error rate improves further in both exp3 and exp4 methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*KINt5A0Y2ijC472DciHDvQ.png" /><figcaption>Model 5 error rate spikes between 5k and 10k. Both exp3 and exp4 still keep the overall error rate low</figcaption></figure><p><strong>Handling stragglers:</strong></p><p>With ensemble methods, straggles(models that take a long time) get introduced which can affect tail latencies. To address this, Clipper makes a design choice to give out an inaccurate prediction instead of giving out an accurate prediction late. This is done by maintaining SLO on latency and if the query doesn’t return, then low confidence is conveyed back to issuer. This best effort straggler mitigation strategy obviously reduces the size of the ensemble.</p><p><strong>Contextualization</strong></p><p>Context can improve results of learning quite a bit. A model trained for certain dialect would perform better for certain users or a region. The model selection state S that was introduced earlier helps with that. It can be instantiated for every user, session or some context. This context related state is stored externally in a Redis database.</p><h4>Conclusions</h4><p>Clipper provides a ML-framework agnostic approach for inference. This in itself can be a great blessing in the evolving landscape of ML frameworks. In addition, built-in advantages of model selection are pretty useful for fault tolerance in models and also for improving accuracy. Latency SLOs ensure very high throughput needed at the time of inference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40f44280f563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introductory notes of Reinforcement learning]]></title>
            <link>https://medium.com/coinmonks/introductory-notes-of-reinforcement-learning-3ec29a2e1822?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec29a2e1822</guid>
            <category><![CDATA[books]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 23:23:51 GMT</pubDate>
            <atom:updated>2018-12-13T19:10:01.657Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introductory notes on Reinforcement learning</h3><h4>Overview</h4><p>This post covers introductory aspects of reinforcement learning. There has been a lot of buzz around reinforcement learning lately with many new applications getting mainstream visibility. One such example is a where a reinforcement learning based system <a href="https://www.bbc.com/news/technology-40042581">AlphaGO has defeated</a> many prominent GO world champions. Another cool example of reinforcement learning came from DeepMind, where they were able to train a model to <a href="https://deepmind.com/research/publications/playing-atari-deep-reinforcement-learning/">play some games</a> on Atari. In addition, many systems problems might be solvable using reinforcement learning techniques. This post covers some of the introductory aspects of reinforcement learning mostly chapter 1 and some aspects of chapter 2 from <a href="http://incompleteideas.net/book/bookdraft2017nov5.pdf">this book</a>.</p><h4>What is Reinforcement learning?</h4><p>In a nutshell, reinforcement learning consists of an agent interacting with an environment and reacting to the sensory input from the environment by taking some actions. These actions get rewarded so as to direct the agent to make more optimal decisions going forward. The agent is not told what actions to take; but must discover those by trial and error. In addition, reward doesn’t only mean the immediate reward, but the reward in the long run. These two aspects: <em>trial-and-error search</em> and <em>delayed award</em> form the most fundamental aspects of reinforcement learning.</p><p><em>Trial-and-error search </em>mentioned above can also be thought of as explore and exploit dilemma. An agent interacting with the environment, needs to take actions that have been useful before — this is exploitation of known facts. But agent cannot know which actions lead to better results without exploring different actions which may not be optimal in the short term.</p><p><em>Delayed Reward </em>is where a lot of research in reinforcement learning is focused on. There is an immediate reward and a long term goal. Greedy approaches may not always lead to most optimized results. How to define the long term value function for any action becomes a critical aspect of reinforcement learning. Many learning methods in that sense focus on estimating the value functions.</p><h4>How is reinforcement learning different from supervised and unsupervised learning?</h4><p>In supervised learning, a training set labeled by a knowledgeable expert instructs the system about expected results — whether a given picture contains cat or not. The model is then supposed to generalize from that labeled data to figure out if a previously unseen picture does indeed contain a cat or not. In reinforcement learning, an agent is supposed to learn from its own action, there are no labeled samples. Agent that is interacting with environment may not have any correct answer or it might be impractical to label a correct answer for all the different scenarios.</p><p>One then might be tempted to think of this as an unsupervised learning problem. In unsupervised learning, the system tries to uncover the patterns hidden within the data. This could be useful in reinforcement learning, but is not sufficient. Agent needs to maximize the reward signal irrespective of finding patterns in data.</p><h4>Major components of a reinforcement learning system</h4><p>There are 4 major components of any reinforcement learning system with the fourth one(environment model) being optional.</p><p><strong>Policy</strong>: Policy is a mapping that represents what actions to take in the current state of the environment. In simple cases, given the current state of the environment, this can be a lookup table that can be used to take the next action by the agent.</p><p><strong>Reward signal</strong>: Reward signal generally represents a numerical number that indicates to the agent whether the given action is positive or not. A low reward will indicate to the agent that this action yielded pain in the short-term. So, in future, the agent may select a different action to get better reward.</p><p><strong>Value function</strong>: Value is a reflection on how much reward the agent is likely to accrue going forward from the given state. Does the current action in the current state yield to accumulation of more rewards over time? It is possible that the current action that has given the most reward is followed by lots of low reward states or an immediate low reward state is followed by many high reward states. In that sense, reward is immediate while value is delayed. Value is also not too useful without rewards — the only purpose of using the right value function is to accumulate more rewards in the long run. Estimating value is one of the most fundamental aspects of reinforcement learning.</p><p><strong>Model of the environment</strong>: Model mimics the environment. Generally this is useful for predicting how the environment will behave given the current state and action — what would be the reward, given the current state and the action. Models can be useful in deciding course of actions without actually experiencing all the scenarios.</p><h4>A tabular method for Reinforcement learning</h4><p>For simpler problems, it is possible to arrive at optimal solutions by keeping a lookup table of values that can be used for selecting actions. Let’s look into an example: A K-armed bandit problem. The problem is relatively simple. There are k options to select from and there is a reward associated with selecting any of those options. Over many steps, the idea is to maximize the value by selecting some actions during every step.</p><p>Let’s assume that we can maintain value estimates of each actions. Thus during every time step, we can select an action with the highest value. Selecting such action can be called a greedy action. But we would also like to explore and learn more other actions so as to improve their estimates going forward. These are the non-greedy actions. Having more uncertainty about non-greedy actions may imply that there are those actions which can lead to more value and hence greedy actions may not be the only choice. If we had known values for every action with certainty, then these exploration would not be needed. There are many complicated ways to balance this trade-off between exploration(non-greedy) and exploitation(greedy), but we will only stick to doing both somewhat here. Also subsequent results will show that non-greedy solutions will lead to more optimal results in long term value.</p><p>To solve this problem more concretely, we can use average-so-far as an estimate of the value of selecting the current action. This can be done by easily maintaining a running average for every action type and then updating the average each time an action is selected. In greedy mode, we would always select action type with max value, but since we want to explore as well, we select non-greedy action from all other actions with some small probability ε. Such methods are called as ε-greedy methods. An advantage of this methods is that, with many time steps, it ensures that all actions will be selected enough times to ensure almost certain value estimation. Experiments from the book(figure below) clearly show how ε-greedy with ε values of 0.1 and 0.01 outperform fully greedy options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*lPSKb48CTMrCIm8sIV6qcw.png" /><figcaption>As number of steps increase, more exploratory approach of ε = 0.1 leads to more average reward.</figcaption></figure><p>This method is called a tabular method because it can be implemented using a simple table that stores the running average so far for every action. A simple formula for running value average Q at n+1th time step can be expressed as:</p><p>Q(n+1) = Q(n) + 1/n * (R(n) — Q(n))</p><p>Here R(n) is the reward obtained at the nth step. Another way to think about this formula is: <strong><em>NewEstimate = OldEstimate + StepSize * (Target- OldEstimate)</em></strong>.</p><p>In this case all the past rewards are weighted equally. This works well if the probability distributions and problem spaces are stable. If those were to change, then it could be more useful to give more weight to recent selections. This can be done altering the same formula to use a constant 0 &lt; ⍺ ≤1.</p><p>Q(n+1) = Q(n) + ⍺ * ( R(n) — Q(n))</p><p><strong>Biases</strong></p><p>In above value-action scenarios, all averages were dependent on Q(1) i.e initial value, which is called as a bias into the algorithm. Generally for stationary non-alpha cases, the bias disappears once we select all actions. But for alpha based cases bias is permanent and only decreases with time.</p><p>One possible use of bias is to use an optimistic value for Q1. For example, in the K-arms bandit problem, if we choose a value that is off from the mean by quite a bit, then it will lead to more early exploration — this happens because Target — Q(1) will be wildly off and all actions will look inappropriate, forcing the algorithm to explore more. Generally speaking this is not a good strategy for sustainable exploration given that it is based on temporary initial condition.</p><h4>Selecting next actions using uncertainty metric(UCB)</h4><p>In ε-greedy, we discussed that when we selected the next action for exploration it was picked with uniform probability from all the remaining non-greedy actions. It would be good to select the next action with some better heuristic. One such heuristic is called Upper-Confidence-Bound selection. In this measure, we select an action that maximizes:</p><p>Q(t) + c * ( sqrt(ln t/N(a))</p><p>What this formula tries to do is to add an uncertainty measure for the given action a. N(a) indicates the number of times a has been selected so far. If ‘a’ has never been selected then sqrt term is maximized and leads to selection of ‘a’. Otherwise as ‘a’ gets selected more and more times, the sqrt term becomes smaller — increasing the certainty. Similarly when any other action other than ‘a’ is selected, it increases the value of sqrt term, but slowly. This causes actions that have been often but with lower value, to not get selected after a while. It also causes to accrue more certainty around actions that haven’t been selected before.</p><h4>Gradient Bandit Algorithm</h4><p>All the previous approaches mentioned below estimate values for every action. Another way could be to assign a priority/probability, at time t, H(t)(a) to every action and then select actions accordingly. Higher H(t)(a), more chances of it being selected. Once we have H(t)(a) — relative priorities, we can then use softmax to land relative probabilities(Pa) for all K actions.</p><p>Ideas of stochastic gradient descent to improve values of Ht(a) with every time step seem possible in this case. If R’ is the baseline reward so far, then we can use the following equation for improving Ht(a) with every step with ⍺ as the step size used in gradient descent.</p><p>H(t+1)(a) = H(t)(a) + ⍺ (R — R’)(1-Pa)</p><p>H(t+1)(a’) = H(t)(a’) — ⍺ (R — R’)(Pa’)</p><p>If reward R &gt; R’, then positive feedback improves H(t+1)(a). At the same time, the second equation decreases the H(t+1)(a’) for all other actions a’. One can see the opposite effect when obtained reward R &lt; baseline reward R’.</p><h4>Summary</h4><p>We discussed basic aspects of reinforcement learning and some ways to manage the trade off between exploration and exploitation. All three methods ε-greedy, UCB, Gradient bandit achieve those trade offs by altering some parameter values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*8DP-GKGMcnCBtC2f3B33Kw.png" /><figcaption>Reward values for different methods by varying related parameters</figcaption></figure><p>As it can be seen for k-bandits problem form U-graphs, all methods have an optimal value of the parameter where they perform the best. UCB seems to outperform other methods at least for this problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec29a2e1822" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/introductory-notes-of-reinforcement-learning-3ec29a2e1822">Introductory notes of Reinforcement learning</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application of synchronized clocks in Distributed Systems]]></title>
            <link>https://medium.com/@ameya_s/application-of-synchronized-clocks-in-distributed-systems-9d630ba1cb56?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d630ba1cb56</guid>
            <category><![CDATA[ntp]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[clock]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Tue, 04 Dec 2018 04:54:51 GMT</pubDate>
            <atom:updated>2018-12-04T04:54:51.130Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Most distributed systems make use of time in some form of another. For time to be useful, clocks on different nodes in the network need to be synchronized in some way. Protocols such as <a href="https://tools.ietf.org/html/rfc958">NTP</a> ensure such synchronization within a certain margin of error. It is important to note that NTP like protocols only guarantee synchronization with a certain level of probability. There are scenarios when clocks might get out of synch. In addition, NTP servers are connected to real universal time clocks that are sampled to ensure that the time is close to real-time, again within a certain margin of error.</p><p>Since clocks can drift sometimes, synchronized clocks are useful in distributed systems for improved performance and only occasionally for ensuring correctness. In such cases, synchronized clocks act as a proxy for some message exchange between two nodes in a distributed system. One can make local decisions(relying on past information) without having to communicate with another node every time. <a href="https://link.springer.com/article/10.1007/BF02242709">Barbara Liskov’s paper</a> covers some such practical applications of synchronized clocks. Let’s go over these applications.</p><h4>At-most-once messages</h4><p>Protocols such as SCMP, rely on at most once delivery of messages i.e. duplicates are not tolerated. For this to work, the receiver of the message would need to know if the sender has sent this message before. Receiver cannot potentially have infinite storage and hence cannot store every message from the sender. In such cases, synchronized time can be used to establish “recentness” and to discard all messages that are not recent as duplicates. While this approach risks rejecting some duplicate messages, it does so with very low probability as long as “recentness” has decent enough lifetime.</p><p>If both sender and the receiver have synchronized clocks, then sender can send the current time with the message to the receiver. Receiver stores a table of timestamps, per connection. The receiver can prune this table and remove entries that are older than the lifetime i.e. cur_time — lifetime. When messages are removed from the table the highest time is also stored called upper. When a new message lands on the receiver that has an entry in the table, timestamp is compared against the recorded timestamp in the table. If it is less than the stored timestamp then it is rejected as duplicate. If a connection does not have an entry in the table, then the timestamp of the message is compared against “upper”. If incoming timestamp is less than upper, then this message is likely very old and hence rejected as a duplicate with a very low probability of rejecting a previously unseen message. If incoming timestamp &gt; upper, then it means that we have not seen a message this recent on this connection and hence a new entry is created in the connection table.</p><p>Another interesting variation of this is how to handle process crashes. One could potentially commit the connection timestamp table mentioned above, every so often to the disk. But that can be a little expensive. Another approximate but effective way to deal with this is to introduce another timestamp “latest”. On the receiver, “latest” is assigned to current_time + recovery_window(some seconds) and this latest is written to disk every few seconds. Any message later than “latest” is discarded or delayed. This is not too meaningful during normal operations. But it is useful during crash recovery. When the receiver crashes and comes back up after some time, it initializes “upper” to last “latest” that was committed to disk. Now any message with timestamp &lt; upper is discarded as a potential duplicate, because only messages before “latest” could have been accepted before the crash. Good values of “recovery_window” ensure that not too many messages are rejected as potential duplicates and also minimizes the writes to disk.</p><h4>Detecting validity of encrypted tokens</h4><p>Systems such as <a href="https://en.wikipedia.org/wiki/Kerberos_(protocol)">Kerberos</a>, use session tokens for mutual authentication between client and servers with the help of a trusted third-party that issues session tokens. Private keys are used to exchange encrypted information and messages are trusted as long as they can be verified. In such scenarios, it is critical to guard against tokens that are just left over at a shared workstation and where user hasn’t logged out. To avoid, perennial use of such tokens, each token also contains an expiry. If current_time at the server &gt; expiry, then such tickets are rejected. If synchronized time wasn’t available, then the server would have to ask the token granting third party for validity of the tokens. Here server’s time acts as a proxy for the third-party time.</p><p>Another useful feature is to detect replays. In kerberos, an authenticator is created by encrypting client’s current time and it’s private key which is also shared with the server. Server can verify the authenticator be decrypting it. Server can also store all recent authenticators — this is similar to at-most-once messages. It can detect replays of the authenticator using similar schemes described in the last section.</p><h4>Cache consistency</h4><p>Cache consistency in a distributed system is about ensuring that modifications to objects on some node is visible on some other node so that all nodes have a consistent view of the modified object. This wouldn’t be an issue if every read and write went to a primary node or a server. But generally for better performance many cached replicas of the object are present on different nodes. Without synchronized clocks, messages would need to be exchanged for every operation to ensure that the object be read or written to, is the most recent one. Let’s see how time/clock based leases simplify this.</p><p>In a write through cache, where any write is reflected on the server write away. In such cases a time based lease can be given to all nodes caching this object. When a modification is attempted, the server will notify all clients holding the lease and ask them to give up the lease. When clients give up the lease, write goes through. When there are no writes, all the nodes that have valid lease(based on local time) can continue to use the object without asking the server.</p><p>In a write-behind cache, changes are only written back to the primary or the server asynchronously or after some time. So system can be more prone to inconsistent views and there is no well defined event if write due to the asynchrony. For this type of cache, leases can be modified to have read and write leases. The leases still have valid expiry times. Read leases on different nodes can be used without conflict, while write leases conflict with other leases. In this case, whenever a node asks for a write lease, other nodes are asked to relinquish their leases. This is how consistent views are ensured. In all other cases, whenever client uses a file, it checks for the validity using expiry of the lease.</p><p>One interesting discussion point on using clocks in leases(or cases mentioned before), is that clocks can drift. A machine can fall behind and have a slow clock or slow synchronization for some period e.g. a client with a slow clock may end up reading an stale/invalid cached version. This will continue while the clock catches up and lease expires eventually.</p><p>While this is not too terrible, it would be good to be able to ensure cache consistency in all cases. It can be done by adding a higher level primitive such as a transaction. Each object can have a version number and server stores version numbers along with the objects. Clients can store objects and will have leases still. But when changes are made, new versions along with objects are sent in a transaction to the server. Server checks for the correct transaction numbers from the client and aborts the transaction if client doesn’t have the right version number of objects. Server will also notify clients holding leases when some object is changed on the server. This helps with minimizing the aborted transactions. Here also clocks can drift, but the worst it can do is to cause an aborted transaction.</p><h4>Replication</h4><p>Consider a file system that uses primary-copy-replication technique. In this primary owns the files and creates replica on sub-majority backups. Sub-majority is one less than majority i.e. If there are 9 nodes in the system, then 4 backups are chosen because together with the primary they form a majority. This ensures that when many nodes go down and at least any half of nodes stay up, at least one of those nodes will have the needed file. When this situation occurs, the owner of the file may change. In normal course of operations, a log is maintained for recording change operations. Owner sends the log to backups and they append it to their logs and when acknowledgment is received from sub-majority, the operation is committed. Read operations are not interesting for the purposes of the log, because they don’t change any objects. This is problematic in case of a network partition. If the old owner is separated from the new owner via a partition, then old owner could conceivably keep on reading stale file, while the new owner is modifying and changing this file. This can be addressed via leases.</p><p>When owner assigns the file to sub-majority it also get leases from the sub-majority. While owner has leases from sub-majority, it can do the read operation unilaterally. During partition, owner is not able to communicate with these backups. So when some other backup becomes the new owner for the file, it waits for the lease given to previous owners to expire. Once the previous owner’s lease has expired, the new owner can change/own this file without having to worry about stale use at the previous owner.</p><h4>Discussion on synchronized rates</h4><p>Some algorithms may not need synchronized clocks and can use synchronized rates instead. As long as all nodes tick at the same rate, there may not be a need to have synchronized clocks at all the nodes. Consider the case of leases. In those cases instead of using expiry time, one could use time to expire. Time to expire can be added to local time to establish final expiry. When a lease is expiring at the client, it is in response to some message that it sent. So expiry can be established with regards to the initial message sent by the client to obtain the lease. For server to establish the lease, server’s reference time can be the local time at which it sent the response to the client. When there are such dependent events, synchronized rates suffice and clocks are not necessarily needed.</p><p>In some cases, rates are just not sufficient and synchronized clocks are necessary. Consider the case of at-most-once messages. In that case, just sending time to expire is not sufficient. On the receiver node, the time-to-expire has no meaning, because receiver node didn’t initiate any message with the sender. In such cases, expiration time i.e. synchronized clocks are necessary.</p><h4>Conclusion</h4><p>While this paper is quite old, concepts mentioned in this paper are still quite relevant. Synchronized clock and rate based algorithms provide an efficient mechanism for making local decisions without having to communicate with remote nodes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d630ba1cb56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time and clocks and ordering of events in a distributed system]]></title>
            <link>https://medium.com/coinmonks/time-and-clocks-and-ordering-of-events-in-a-distributed-system-cdd3f6075e73?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd3f6075e73</guid>
            <category><![CDATA[logical-clock]]></category>
            <category><![CDATA[lamport]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Tue, 13 Nov 2018 08:11:31 GMT</pubDate>
            <atom:updated>2022-07-02T13:39:20.180Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>In this post, we will cover the <a href="https://lamport.azurewebsites.net/pubs/time-clocks.pdf">notion of time</a> in distributed systems. We rely a lot on time in our daily existence for ordering. One thing “happened before” another is a relation that is codified by time, using physical clocks as a mechanism to deliver time. So ordering of events is done using physical clocks in the real world. In a distributed system, this notion of time needs to be understood more carefully. Without relying on physical clocks that can be inaccurate, the central question becomes how do we define ordering of events in system of collection of nodes. Each node can establish their own local order of events. But how can one establish a coherent order of events across multiple nodes. This order is important for solving problems like distributed locking — a shared resource which can only be used by one node at a time and the node requesting the lock on the resource needs to be granted the lock as long as another node hasn’t asked for it before. In such cases local order is not sufficient and some global order needs to be established across multiple nodes.</p><h4>Partial ordering of events in a distributed system</h4><p>One way to define an order of events in a distributed system would be to have a physical clock. So “happened before” event can be described using t1 &lt; t2. But clocks are not accurate, can drift and are not necessarily synchronized in lock-step. So this paper takes another approach to define “happened before” relation. (The meaning of “partial order” will become clear later. )</p><p>A distributed system can be defined as a collection of processes. A process essentially consists of a queue of events(which can be anything — like an instruction, or a subprogram, or anything meaningful) and has apriori order. In this system, when processes communicate with each other, sending of a message is defined as an event. Let’s establish a more precise definition of “happens before” (⇢) in such a system.</p><ol><li>In the same process, if event a comes before event b, then a ⇢ b</li><li>When process i sends some message at a to process j and process j acknowledges this message at b, then a ⇢ b</li><li>Happens before is transitive. a ⇢ b and b ⇢ c, then a ⇢ c.</li><li>Two events a and b are described as concurrent when a hasn’t happened before b and b hasn’t happened before a. This condition generally reflects the fact that process i may not have knowledge about all events that could have happened in process j. So we cannot establish authoritative order in the system — this also makes it clear that we have only a <strong><em>partial order</em></strong> in the system. There could be a lot of events in the system for which no meaningful order can be established without relying on physical time.</li></ol><p>Taking some examples might be useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*7jfRoG8tHMbnTErbQCN0tA.png" /><figcaption>Partial ordering of events in the system. Vertical bars are processes. Wavy arrows are messages. A dot is an event. Time elapses bottom up.</figcaption></figure><p>As you can see in the figure on the left above, p1 ⇢ p2 as those are the events in the same process. q1 ⇢ p2 due to sending of the message from process Q to process P. If we consider that time is elapsing bottom up and q3 seems to happen before p3 if we were to consider physical time. But in this system, we will call these events as concurrent. Both processes don’t know about these events — there is not causal relationship at this time. But what we can say is that q3 ⇢ p4, because q3⇢q5 and q5 ⇢ p4. Similarly we can say that p1 ⇢ r3. Now having gone through some examples, it becomes clear that, another way to envisage a ⇢ b is that event a can causally affect event b. On a similar note, q3 and p3 mentioned above are not causally related.</p><h4>Logical clocks</h4><p>Lamport’s paper introduces a new function, essentially a counter, in every process that can assign a number to an event. Let’s call this function as Ci(a) as a counter in process i for event a. There are no physical clocks in the system. The function C(a) establishes the invariant that, event a must have happened before b, then C(a) &lt; C(b). Using this function, a partial ordering of events in the system can be established using the following two conditions:</p><p>C1: Ci(a) &lt; Ci(b) if a happens before b in the same process i. This can be implemented using a simple counter in the given process.</p><p>C2: When process i sends message at event a and process j acknowledges the message at event b, then Ci(a) &lt; Cj(b)</p><p>These clock functions can be thought of as ticks that occur regularly in a process. Between any two events, there needs to be at least one such tick. Each tick essentially increments the number assigned to the previous tick. This is illustrated in the right-hand side figure above. Similar numbered ticks are connected across process boundaries. In the same process one touches or crosses the tick boundary to land on the next event. Across processes when messages are sent, that message needs to cross or touch a tick boundary to define the “happens before” event.</p><p>This can be implemented in the following way:</p><p>IR1: This one obeys C1. This can be done by incrementing the Ci(a) between any two successive events in the system.</p><p>IR2: This is one implements C2. It can be done by sending Ci(a) as a timestamp to process j. When Process j acknowledges the receipt of this message at event b, it needs to set Cj(b). Cj(b) will be set to a value ≥ the current Cj and also greater than Ci(a)/timestamp.</p><h4>Total ordering of events in the system</h4><p>So far the system of logical clocks has established a partial order of events in the system. There are still events which are concurrent and it would be useful to break ties, specially for the locking problem described in the introduction — someone needs to get the lock. This can be done by introducing an arbitrary process priority. In case of a tie, the process with lower priority gets the event that happened before. More formally, a total order a ⇥ b (notice the new type of arrow)can be defined as:</p><ol><li>Ci(a) &lt; Cj(b).</li><li>If Ci(a) = Cj(b), then use Pi &lt; Pj.</li></ol><p>These two conditions imply that ⇥ completes the partial relationship ⇢. If two events are partially ordered then they are totally ordered already. While partial ordering is unique in the given system of events, total ordering may not be.</p><h4>Distributed locks using total ordering</h4><p>Consider the following problem which can be quite common in distributed systems. The central idea of the problem is to access a shared resource, but only one process can access it at any time. More formal conditions can be specified as:</p><ol><li>A process which has been granted a resource, must release it before any other process can acquire it.</li><li>Resource access requests should obey the order in which requests are made</li><li>If every process releases the resource it asked for, then eventually access is granted for that resource.</li></ol><p>One possible solution could be to introduce a centralized scheduler. While one issue is that it is a completely centralized, another is that ordering condition 2 may not work. Consider the scenario: Process i asking for a resource to the scheduler. Then it informs process j about the request. Process j now asks for the same resource, but its message reaches the scheduler before process i’s. This means that event order was not obeyed. To address this issue, we can use total ordering based off of IR1 and IR2. With this, every event is totally ordered in the system. As long as all the processes know about requests made by other processes, the correct ordering can be enforced. A decentralized solution can be designed such that each process keeps a queue of lock and unlock operations.</p><ol><li>Process i asking for a resource lock, uses the current timestamp and puts lock(T,Pi) in the queue. It also sends this message to all other processes.</li><li>All other processes put this message in their queue and send the response back with a new timestamp Tn.</li><li>To unlock a resource, process i, sends unlock(T, Pi) message to all processes and removes the lock(T, Pi) message from its own queue.</li><li>Process Pj, upon getting unlock message, removes lock(T, Pi) message from its queue.</li><li>Process Pi is free to use the resource i.e. gets its lock request granted when: it has the lock(T, Pi) messages in its queue with T enforcing the<strong><em> total order</em></strong> such that T is before any other message in the queue. In addition, process Pi needs to wait until it has received messages from all the processes in the system timestamped later than T.</li></ol><h4>Conclusion</h4><p>The notion of time/order-of-events is quite complicated in distributed system. Idea of logical clocks to ensure causal ordering, without having to rely on physical clocks, is quite useful in distributed systems. Lamport’s logical clocks ensure that if a ⇢ b then, C(a) &lt; C(b). It is also good to understand that if C(a) &lt; C(b) then it doesn’t necessarily mean that a ⇢ b. If we just looked at C(j) and C(k) and C(j) happened to be less than C(k), then those could be concurrent events and processes may not have communicated with each other yet. This later property, of just looking at some timestamps and realizing the causality, is achieved by <a href="https://en.wikipedia.org/wiki/Vector_clock">vector clocks</a>.</p><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="https://medium.com/coinmonks/top-3-telegram-channels-for-crypto-traders-in-2021-8385f4411ff4">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li><a href="https://medium.com/coinmonks/buy-bitcoin-in-india-feb50ddfef94">Buy Bitcoin India</a> | <a href="https://medium.com/coinmonks/pionex-review-exchange-with-crypto-trading-bot-1e459d0191ea">Pionex Review</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading bots</a></li><li><a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Crypto exchanges in India</a> |<a href="https://medium.com/coinmonks/bitcoin-savings-account-e65b13f92451"> Bitcoin Savings Account</a></li><li><a href="https://coincodecap.com/cloudbet-casino-review">Cloudbet Casino Review</a> | <a href="https://coincodecap.com/ignition-casino-review">Ignition Casino Review</a></li><li><a href="https://medium.com/coinmonks/binance-fees-8588ec17965">Binance Fees</a> |<a href="https://medium.com/coinmonks/botcrypto-review-2021-build-your-own-trading-bot-coincodecap-6b8332d736c7"> Botcrypto Review</a> |<a href="https://medium.com/coinmonks/hotbit-review-cd5bec41dafb"> Hotbit Review</a></li><li><a href="https://coincodecap.com/myconstant-review">MyConstant Review</a> |<a href="https://coincodecap.com/best-swing-trading-bots"> 8 Best Swing Trading Bots</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd3f6075e73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/time-and-clocks-and-ordering-of-events-in-a-distributed-system-cdd3f6075e73">Time and clocks and ordering of events in a distributed system</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parameter Server for Distributed Machine learning]]></title>
            <link>https://medium.com/coinmonks/parameter-server-for-distributed-machine-learning-fd79d99f84c3?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd79d99f84c3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[parameter-server]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Sat, 27 Oct 2018 20:35:44 GMT</pubDate>
            <atom:updated>2020-08-31T14:22:16.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Many machine learning problems rely on large amounts of data for training and then for inference. Big internet scale companies train with terabytes or petabytes of data and create models out of it. Such models consist of weights that will optimize for error in inference for most cases. The number of weights/parameters run into orders billions to trillions. In such big models, both learning and inference on a single machine is not possible. It is useful to have a framework that can be used for distributed learning as well as inference. Since parameters need to be shared and then updated across multiple nodes using which these nodes perform and perfect their computations, these large numbers can be become bottleneck when it comes to sharing. Sharing is expensive in terms of bandwidth, synchronization for sequential ML algorithms, fault tolerance on commodity machines that can have high failure rates upto 10%. <a href="https://www.cs.cmu.edu/~muli/file/parameter_server_osdi14.pdf">Parameter sever</a> proposes a new framework for addressing these challenges and building distributed machine learning algorithms.</p><h4>Main design ideas</h4><p>To address the challenges mentioned in the last section, Parameter Server proposes the following design requirements:</p><ol><li>Efficient communication: An asynchronous task model and API that can reduce the overall network bandwidth for ML algorithms</li><li>Flexible consistency models: Relaxed consistency helps with reducing the cost of synchronization. It also allows developers to choose between algorithmic convergence and system performance.</li><li>Elasticity for adding resources: Allows for adding more capacity without restarting the whole computation.</li><li>Efficient Fault tolerance: Given high rate of failures and large amounts of data, allow for quick recovery of tasks in a second or so - if the machine failures are not catastrophic.</li><li>Ease of use: Structure the API to support ML constructs such as sparse vectors, matrices or tensors.</li></ol><h4>Example of a distributed machine learning algorithm</h4><p>A classical supervised ML problem consists of optimizing a cost function given a training set of labeled data. Cost function is changed and tweaked over many samples so as to reduce or minimize the error of prediction. For tweaking the model or reducing the error, partial derivatives/gradients are computed. These gradients help move the weights in the right direction to minimize the error.</p><p>For a ‘d’ dimensional feature vector, the model tries to predict the outcome for a previously unseen x using the following formula: for every i=1 to d, ∑xi * wi. To make sure that model generalizes relatively well(i.e. it doesn’t perform well only on the training data), a regularization component is added to the prediction function. So the function mentioned above morphs into ∑xi * wi + ƛ*Norm(w). Here the ƛ is used to penalize the weights that were discovered on training data. This added term deemphasizes learned weights a little bit and hence avoids overfitting and helps with generalization on previously unseen data. For the purposes of this paper, it is less interesting to know about the exact functions used for cost minimization or regularization. This paper focuses more on systems aspect of this framework.</p><p>Let’s see how a distributed stochastic gradient descent would work for solving the prediction algorithm mentioned above. The following diagram depicts the high level process of parallelizing work for an iterative algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*6VRMmXkY3On-PJh8vNRHww.png" /><figcaption>Distributed training algorithm</figcaption></figure><p>The system consists of some server nodes and worker nodes. Each worker node loads some subset of data with different workers loading different samples. Each worker computes gradients on the local data for optimizing the loss function. Each worker then sends those partial gradients to the server node. Server node aggregates those gradients received from many worker nodes. Once server node is done, worked nodes can pull the new set of weights available from the server node and perform the gradient computation again. Most of the time is spent in calculating g1, g2,…, gm gradients on workers. These are calculated using <em>transpose(X) * w</em>. If w is in orders of billions to trillions, this computation would be infeasible on any single node. But a good side effect of each node working on only a subset of data is that, they only need the weights corresponding to that data e.g. If one is trying to predict how likely is the user to click on an advertisement, then words such as “regularizers” would be less interesting and most workers won’t update weights for it at all. As you can see in the figure above, on a given node, only the weights(w) for which features of x are present/relevant for the dot product are necessary to be sent to the worker nodes (see the columns of x on each worker node and corresponding w in the sparse weight vector).</p><p>At a high level, the algorithm looks like the following on each <em>worker</em>:</p><ol><li>On each worker, compute the gradient(partial derivative) on a subset of data</li><li>Push this partial gradient out to the server</li><li>Pull the new sets of weights from the server when server is ready</li></ol><p>On each <em>server</em>:</p><ol><li>Aggregate the gradients for all ‘m’ workers e.g. g = ∑ gi</li><li>new_weights = old_weights — learning_rate * (g + ƛ*Norm(old_weights))</li></ol><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*2tfESTWpp_CFl4UIHcXDAQ.png" /><figcaption>High level architecture</figcaption></figure><p>ParameterServer consists of server groups to facilitate running of multiple algorithms in the system. Each server node in the server group is responsible for a partition of the keyspace/data. Servers can communicate with each other for migrating/replicating the data for scalability and availability. A server manager is responsible for maintaining the consistent view of the server groups. It performs liveness checks and assigns ownership of keyspaces to each server node.</p><p>A worker group is typically assigned for an application. Multiple worker nodes constitute worker groups which communicate with the sever groups for pulling of parameters and pushing of gradients as mentioned in the last section. Worker groups don’t need to communicate with each other. A scheduler looks at the worker group and assigns task to them. Generally the same worker node leverages data stored locally by running iterative algorithms on the same dataset. Parameter namespaces can be used for parallelizing work further among multiple worker groups. In addition, same parameter namespace can be shared among multiple groups: a typical example being one group supporting the real-time inference, while other worker groups can support the development of the model and updating of shared parameters.</p><p>Let’s look at some of the primitives needed to build this architecture</p><h4>Key-Value API</h4><p>When this paper was written, existing systems used key-value pairs for communicating the shared parameters. An example of this would be feature-id and its weights. Traditionally this has been implemented using memcached or some other key-value store. The important insight is that values are mostly some linear algebra primitives such as vectors or matrices and it is useful to be able to optimize operations on these constructs. Typical operations are dot product, matrix multiplication, L-2 norms etc. So keeping the key-value semantics and endowing values as vectors, matrices is useful for optimizing most common ML operations.</p><h4>Range based push and pull</h4><p>As mentioned in algorithm earlier, weights pulled from the server nodes and gradients are pushed to the server node. Supporting a range based push and pull would optimize for the network bandwidth usage. Hence the system supports w.push(R, destination), w.pull(R, destination) for pulling the data. In both cases, values corresponding to keys in range R are pushed and pulled from the destination node. Setting R to a single key, gives the simple key-value read-write semantics. Since gradients g share the same keys as that of w, w.push(R, g, destination) can be used for pushing local gradients to the destination.</p><h4>Asynchronous tasks and dependency</h4><p>Tasks can be thought of as RPCs. Any push or pull request can be a task, so can be a remote function that is executing. Tasks are generally asynchronous in nature and programs/applications can continue executing after issuing the task. Once the response in (key, value) pairs is received, tasks can be marked as completed. A task can be marked as completed only when all subtasks that the given task depends on returns. Task dependencies help with implementing the overall control flow for the application.</p><h4>Flexible consistency models</h4><p>As it can be seen from the model above, tasks run in parallel and most often on remote nodes. Because of this, where there is data dependency between various tasks, it may end up pulling old version of data. In machine learning, sometimes it is not too detrimental to pick up old weights or weights that are not too old, instead of the most recent weights. Parameterserver lets implementors select the consistency model that they are after. Three types of consistency models are supported as described in the diagram below. In sequential consistency all tasks are executed one after another. In eventual consistency, all tasks start in parallel and eventually converge. In bounded delay, tasks are started as long as any task started greater that “t” times back has already completed — the figure c below shows bounded delay of 1 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*vA6o0pFlZpSueuoeph7dXA.png" /><figcaption>Consistency models</figcaption></figure><h4>Implementation details</h4><p><strong>Vector clocks: </strong>For fault tolerance and recovery, some timestamping is needed in the system. Parameter server uses vector clocks for establishing some order of events in the system. Vector clocks can be expensive based on number of nodes(m) and number of parameters(p) i.e. O(m * p). This can be very large given the large number of parameters in the system. Since most operations can be done using ranges, each range can be assigned a vector clock instead of every ket getting one. If there r unique ranges in the system, then complexity can be reduced much further by this mechanism i.e O(m * r). The system initially starts with only m clocks thus the entire key space belonging to the node has one vector clock. This can slow down recovery process. Hence as and when more ranges get created in the system, newer vector clocks are assigned to these range partitions.</p><p><strong>Messages: </strong>Messages in the system are represented as (VectorClock(R), All keys and values in R). Since the communication can be heavy in data intensive ML applications, one can have reduce the bandwidth via caching. The same keys are communicated many times in iterative algorithms and hence nodes can cache keys. The values also might contain a lot of unchanged values during iterations and thus can be compressed effectively. ParameterServer uses <a href="https://en.wikipedia.org/wiki/Snappy_(compression)">snappy compression</a> for effectively compressing lot of zeros.</p><p><strong>Consistent Hashing: </strong>Consistent hashing is used for easy addition and removal of new nodes to the system. Every server node on the hashing ring is responsible for some keyspace. The partitioning and ownership of keyspace is managed by the server manager.</p><p><strong>Replication: </strong>Replication is done by neighboring nodes. Each node replicates keyspaces of it’s k neighbor nodes. The master responsible for the keyspace is coordinating with the neighbors keeping the replica via synchronous communication. Whenever master pulls key ranges, it will be replicated to its neighbors. When a worker pushes data to a server, the task is not ack’d as completed until the data is replicated to the slave. Obviously this can be very chatty if done for every push and pull. Hence system also allows for replication after aggregating a certain amount of data. This aggregation is shown in the figure below. Only one replication message is exchanged between s1 and s2. It comes after both x and y have been pushed to S1, followed by the function computation task on S1 and then comes the last message of replication after which the acknowledgments(4, 5a, 5b) flow back to worker1 and worker2 to complete the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*nQz_OAHhUgX3E2qm2ZMKIg.png" /><figcaption>Replication after aggregation</figcaption></figure><p><strong>Server Node Management: </strong>It is useful to be able to scale by adding new server nodes to the system. When this happens, Server Manager assigns a keyspace to the new node. This keysapce can come from some node that was terminated before or by splitting keyspace of a heavily loaded server node. This new node then pulls the keyspace that it is responsible for and also replicas from k neighbors as a slave. Generally a two-phase fetch might be needed to pull data that is being overwritten while being fetched by this new node. Server manager then broadcasts this ownership assignment message to other nodes on the ring and these other server nodes can then shrink their keyspace usage based on this new ownership assignment. For a departing node, server manager will assign the keyspace to some new incoming node. Node health is maintained via heartbeats by the server manager.</p><p><strong>Worker nodes: </strong>Adding a new worker node is relatively simpler. Task scheduler assigns a data range to worker node. This new node will pull data from NFS or some other workers. Then the scheduler broadcasts this message to other workers so that other workers can reclaim some space by giving up some of the training data. When a worker node departs it is left to the owner of the algorithm on whether to recover the data or not — depending on the size of the data.</p><h4>Conclusion</h4><p>This paper lays out some important concepts of distributed machine learning. From systems perspective, this paper puts together to good use techniques like consistent hashing. Range based communication and supporting native ML constructs for message passing seems like a good insight for building an efficient ML framework.</p><blockquote><a href="https://coincodecap.com/?utm_source=coinmonks">Get Best Software Deals Directly In Your Inbox</a></blockquote><figure><a href="https://coincodecap.com/?utm_source=coinmonks"><img alt="" src="https://cdn-images-1.medium.com/max/584/0*OJ-qb5G6i863msBB.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd79d99f84c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/parameter-server-for-distributed-machine-learning-fd79d99f84c3">Parameter Server for Distributed Machine learning</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ray — A cluster computing ML framework for emerging applications]]></title>
            <link>https://medium.com/coinmonks/ray-a-cluster-computing-ml-framework-for-emerging-applications-9dfa14934749?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dfa14934749</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scheduling-software]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Sun, 14 Oct 2018 19:44:11 GMT</pubDate>
            <atom:updated>2020-08-31T14:47:42.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ray — A cluster computing ML framework for emerging applications</h3><h4>Introduction</h4><p>The last post covered <a href="https://medium.com/@ameya_s/design-principles-for-a-real-time-machine-learning-framework-40e46f827a7d">design principles</a> outlined in a paper from Riselabs at Berkeley for a new framework that is needed for emerging class of AI applications. This post will build up on those design principles and do a deep dive into <a href="https://arxiv.org/pdf/1712.05889.pdf">Ray framework </a>that was built following those principles. I would highly recommend going over design principles before jumping into this one. This post will rely on a lot of material that was covered in the last post.</p><p>Just to recap the last post: at a high level, framework for new class of API applications will need to be able to support low latency of scheduling, high throughput for millions of tasks, dynamic generation of tasks, heterogenous tasks, arbitrary complex dataflow dependencies. Ray supports these requirements and in turn enables a new class of AI applications that use reinforcement learning(RL) that need support for distributed training, model serving and running of many simulations. Ray focuses on running of lightweight stateless tasks and also time consuming stateful operations that are needed for training.</p><p><strong>A typical RL algorithm</strong></p><p>A typical example of an RL agent interacting with the environment goes through the following iterative algorithm:</p><ol><li>Start with some model</li><li>Make the policy(from the model) interact with environment and obtain the recommended action(Model serving)</li><li>Get the reward by interacting with the simulated environment(Simulations)</li><li>Repeat steps 2–3 until simulations have finished</li><li>Using the results from the last step, retrain the policy. (Training)</li><li>Repeat steps 1–5 till the results have converged and reward has been maximized</li></ol><p>As you can see from this algorithm, this framework needs to be able to support model serving, simulation of tasks and training on large data. <em>Model serving</em> is focused on rendering policy quickly — making many decisions/inferences quickly and reducing latency by effective load balancing. <em>Simulations </em>use policy to evaluate its effectiveness in the given environment as current algorithms are not efficient enough to deal with physical world in real-time. <em>Model training</em> is based on massively distributed stochastic gradient descent. This is very much in contrast with supervised learning where model training and model serving/inference are decoupled. Training occurs offline and inference occurs online(in real-time).</p><h4>Ray API primitives</h4><p>This was covered in the design principles post. But here is a concise summary to refresh that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*lNX1q2EdRD5yYqk8mp0FkA.png" /><figcaption>First three pertain to stateless Tasks and the last row corresponds to stateful Actors and their API</figcaption></figure><h4>Tasks and Actors</h4><p>Tasks(first three rows) mentioned in the last section are remote functions that rely on external input and that are stateless. Think of them as functions which can be executed remotely on any node where the input is. Tasks are easy to recover — it can be done just by re-executing them. Tasks are inefficient for small updates.</p><p>Actors are stateful entities that carry state with them. These are useful for iterative modes such as training or parameter servers which rely on internal state and their continuous update. Actors have methods that can execute remotely like a task, but need a “stateful worker” to execute. Actors also make it easy to wrap third-party packages that cannot be easily deserialized as input to a task. Actors are also useful for smaller updates as opposed to bulk updates that pure tasks are designed for.</p><h4>Task Graphs</h4><p>Ray creates a dynamic graph based on the program that the user has written. This graph forms a dependency structure and the next tasks in the graph are executed by the system when inputs become available. The graph consists of nodes that represent data objects, remote function invocations(tasks). The graph also has edges. Dataflow edges capture dependency between tasks and data objects. Control edges capture the nested tasks or functions that create further remote functions. So far we didn’t discuss Actors in this model. Actors are again similar to tasks. The only difference is to capture the statefulness. This is done by adding a stateful edge. When Actor invokes two methods M1 and M2, a stateful edge is added between the two task nodes represented by M1 and M2. This means that the chain of stateful edges is formed for all the methods invoked by the same actor and also helping with lineage construction that is useful for recovering from fault.</p><h4>Architecture</h4><p>The system architecture of Ray consists of application and system layers. Let’s look at how the two layers functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*0Pqh23sCAxuFqngSiHIktA.png" /><figcaption>App layer that contains drivers and workers. System layer encompassing the hybrid scheduler.</figcaption></figure><p><strong>Application layer</strong></p><p>As you can see the application layer consists of driver, worker and actors. <em>Drivers</em> execute the application programs. <em>Workers</em> execute tasks or functions present in the system. Whenever a remote function is declared, it is pushed out to a worker. Driver and the local-scheduler asks the worker to execute tasks. <em>Actor</em> is similar to worker in that it executes tasks, but it works on state of the previous method and only invokes methods that belong to the actor.</p><p><strong>System layer</strong></p><p>System layer consists of three main components that consist of global control state(GCS), Global scheduler and in memory distributed store + local scheduler.</p><p><strong><em>Global control store(GCS)</em></strong> is used for storing the information such as all the remote function tables, event logs, object tables. At the core, it is a key-value store augmented with pub-sub functionality. This table also stores the information about where objects are located, so that that can be used for efficient colocation of tasks and data. Since GCS maintains all the state, it helps with scaling of the scheduler. In addition, GCS can be used for recovering from failures. Coarse-grained recovery has been addressed via architectures such as <a href="https://medium.com/coinmonks/apache-spark-and-rdds-fault-tolerant-distributed-in-memory-data-processing-7e5a763d3236">RDDs,</a> but fine grained recovery needs a different mechanism, especially for dynamic tasks that get added during simulation. This is addressed by having GCS maintain the lineage information for recovery. This allows for all other components in the system to be stateless and to not worry much about recovery from failures.</p><p><strong><em>Global scheduler: </em></strong>The global scheduler is really a hybrid, bottom-up scheduler in which tasks are submitted to the local scheduler. Local scheduler first tries to schedule the given task on the same node. If it cannot, because of constraints(lack of GPU) or because of high load on the local node, it will submit the task to the global scheduler. Global scheduler is aware of overall systems usage on all the nodes and data needs of different tasks via GCS. These tasks can then be submitted to the local scheduler on the node that the global scheduler has picked. The global scheduler may find multiple nodes that satisfy the capacity needs for this task. Since tasks in Ray are very latency sensitive, the scheduler chooses a node that minimizes the wait-time for the task. Wait-time is defined as the sum of “time spent in queues on the selected node” and “time spent in transferring inputs to that node”. GCS uses heartbeats to get information about data transfer bandwidth and also queue sizes at each node. In addition, if the scheduler becomes the bottleneck, then it is possible to scale out the scheduler using GCS as the data source.</p><p>See the figure below which makes this task scheduling workflow clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Kob5TbQ_ZHWuDAYZRVB_-w.png" /><figcaption>Hybrid scheduler that starts with local scheduler and then goes to global scheduler to find another node if needed.</figcaption></figure><p><strong><em>In-memory distributed object store </em></strong>is present on every node on the system and used for storing inputs and outputs of tasks. For any input that is not present on the node, object store will replicate those to the local node. This also helps with hot-object bottlenecks. The object store is limited to immutable data, so consistency is not a big issue. In addition, only objects that are supported are the ones that can fit on a single node.</p><h4>Execution of a remote task in Ray</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*XSDt8QUbPyeKUf-2RWPXTQ.png" /><figcaption>Typical execution of a remote task</figcaption></figure><p>Lets walk through the sequence of steps needed to execute a function in Ray and the steps needed to fetch the results. Consider there are two nodes N1 and N2 in the system. A remote function is declared and it is registered with the GCS and then propagated to workers on N1 and N2 (step 0 in the figure above). The application is running on N1 and wants to perform an “add” operation on two objects a and b. This operation returns a future “id” and then application on N1 calls a get() on future “id’ — which is a blocking call. Now first let’s step through what happens in the system for<em> executing add</em> operation. This is shown in figure (a).</p><ol><li>The add task is submitted to the local scheduler on N1.</li><li>Local scheduler realizes it only has object “a” available locally. So it submits the task to global scheduler.</li><li>Global scheduler looks at the the GCS for where objects “a” and “b” are present and then decides to schedule this on N2.</li><li>Local scheduler on N2 gets the information about “a”from local object store. “b” is locally available.</li><li>Since object store, doesn’t have “a”, it needs to get it from the node where it is present.</li><li>Object store on N2 gets to know from GCS that “a” is on N1.</li><li>“a” gets replicated on N2 via object store replication from N1</li><li>Local scheduler schedules the add tasks using local workers</li><li>Local worker uses the object store to fetch “a” and “b” to perform the addition.</li></ol><p>The second part of the application is to get the result of addition using the future “id” referenced by the application on N2. This is shown in figure (b)</p><ol><li>Local scheduler on N1 is executing the get on future “id”. It checks the object store locally — which doesn’t have an entry for “id” yet.</li><li>The local object store asks GCS for “id”. Since GCS doesn’t have it, a callback is registered with GCS.</li><li>In the meanwhile, add completes on node N2. The data is stored in the objects store on N2.</li><li>N2 object store informs GCS about availability of results of “id”. This is registered in the object table.</li><li>GCS invokes the callback on N1, mentioning the availability of “id” on N2.</li><li>The object store on N1 replicates “id” from N2.</li><li>Now the task on N1 waiting for future-get (ray.get) is unblocked.</li></ol><h4>Evaluation for RL applications</h4><p>This paper also compares the performance of Ray framework against two RL algorithms and their reference implementations. These two algorithms are <a href="https://blog.openai.com/evolution-strategies/">evolutions strategies</a> and <a href="https://blog.openai.com/openai-baselines-ppo/">proximal policy optimizations</a>. For both cases, ray based algorithm performs much better compared to one-off solutions built for these problems. Keep in mind that building such one-off solutions is pretty complex. For ES, the reference solution doesn’t scale beyond 1024 nodes, while ray scales upto 8192 node. Similarly for PPO, ray outperforms OpenMPI implementation at a much lower cost(thus improving cluster utilization) and needed far less number of GPUs. This was possible because tasks and actors can ask for specific heterogeneous resources and use data locality better while pinning those resources.</p><h4>Conclusion</h4><p>Both, the design principles and the actual framework paper, make for an interesting read on new-age ML frameworks need to evolve to support RL techniques. Frameworks that can support Hybrid scheduling and combination of task/actor based approaches seem like a good fit for this problem space.</p><blockquote><a href="https://coincodecap.com/?utm_source=coinmonks">Get Best Software Deals Directly In Your Inbox</a></blockquote><figure><a href="https://coincodecap.com/?utm_source=coinmonks"><img alt="" src="https://cdn-images-1.medium.com/max/584/0*OJ-qb5G6i863msBB.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dfa14934749" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/ray-a-cluster-computing-ml-framework-for-emerging-applications-9dfa14934749">Ray — A cluster computing ML framework for emerging applications</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design principles for a real time machine learning framework]]></title>
            <link>https://medium.com/@ameya_s/design-principles-for-a-real-time-machine-learning-framework-40e46f827a7d?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e46f827a7d</guid>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[ray-framework]]></category>
            <category><![CDATA[scheduling-software]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 02:00:01 GMT</pubDate>
            <atom:updated>2018-10-10T02:21:20.958Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Traditional approach to ML has been to operate on a bunch of data offline, create models using supervised learning methods and then use those trained models for inference in an online environment. While this has had great success in the past, a new class of applications is emerging. These applications want to infer in real-time environment, react to sensory inputs, perform continuous small micro simulations and then take actions. This is a typical flow in reinforcement learning based approaches. Generally learning from the real environment can be very resource heavy or can be limited by bandwidth. Hence one approach has been to update simulated environments and perform many such simulations using methods such as <a href="https://en.wikipedia.org/wiki/Monte_Carlo_tree_search">Monte carlo tree search</a>. This implies that system would need to be able to perform simulations faster than the real-time. Some of the existing frameworks such as Spark or TensorFlow don’t appear to be sufficient for this kind of workload. Mostly these frameworks support static dataflow graph building as they are not generally good at extending these dataflow graphs in real-time. Also data-centric frameworks such as MapReduce are focused on bulk parallel operations, as opposed massive parallelization for short tasks which is needed for this new class of applications. <a href="https://arxiv.org/pdf/1703.03924.pdf">This paper </a>from <a href="https://rise.cs.berkeley.edu/">RISELab</a> in UC Berkeley explores the design principles for a framework that might be needed to support such real time needs. A prototype implemented for a reinforcement learning based agent that plays Atari, using the principles outlined below, performs 63x faster than spark.</p><h4>Requirements for the new framework</h4><p>The requirements for a new framework that can schedule such new age applications and their tasks, can be broadly classified in three categories: Performance, Execution Model, Practicality.</p><p><strong>Performance</strong></p><ol><li>Low latency: Since these ML applications need to react in real time, quick end-to-end response, in orders of milliseconds is needed. (R1)</li><li>High throughput: Since monte carlo simulations used in RL can create up to millions of small tasks, the scheduler framework needs to ensure high throughput. (R2)</li></ol><p><strong>Execution Model requirements</strong></p><p>3. Dynamic task creation: New tasks will get created dynamically(e.g. using monte carlo tree search) based on execution flow of other tasks and also duration of tasks. (R3)</p><p>4. Heterogeneous tasks: Tasks will vary along the dimensions of resources needed and duration of execution. (R4)</p><p>5. Arbitrary dataflow dependencies: New small tasks will depend on execution of other tasks and create a graph of tasks that depend on each other and that too dynamically. (R5)</p><p><strong>Practical usage requirements</strong></p><p>6. Fault tolerance: This is specially tricky in high throughput and low latency environments. But it is needed in any distributed environment(R6)</p><p>7. Debugging and Profiling: ML applications and the ones that rely one reinforcement learning are compute intensive. So profiling for performance issues quickly is important. Similarly debugging capabilities in a distributed and stochastic environments are useful for quicker troubleshooting. (R7)</p><p>Given these requirements, overarching idea of the framework centers on having a hybrid approach. A centralized scheduler with state can help with fault tolerance and data-graph lineage replay and helps with cluster level resource assignments. At the same time, having stateless and bottom-up local schedulers can make efficient local machine level decisions and take quick decisions on most tasks using data locality.</p><h4>A real world example</h4><p>Let’s look at a real world example that will make requirements R1 to R5 more concrete. See a representative system that can be used by a robot moving around using video and LIDAR input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*-FT9v2xXRwJuQmXTi3PjYA.png" /><figcaption>Robot using different ML components for making decisions in real-time. Box sizes and colors represent duration and diversity of tasks.</figcaption></figure><p>Such a robot needs to listen on multiple sensory inputs from the physical world and use that data to make decisions. It might be using RNN based model for inference and policy decisions. It could be using MC tree search to simulate more physical conditions. In the tree search, it may decide to follow certain sub trees or ignore others depending on time it is taking compute the completion of the subtree. Obviously most of this needs to happen in real-time for the robot to be effective.</p><p>As we can see, R1 is necessary for real-time needs of the system. R2 is necessary for supporting MC tree searches. R3 is needed as one takes different tree branches and spawns tasks corresponding to those. R4 is apparent due to the need to support RNN inference tasks- different functions at different layers, sensory input processing, various physics simulations. As it can be seen from the diagram, R5 is needed because of complex data flow dependency present in the system.</p><h4>Architecture</h4><p>Based on the requirements R1-R7 above and the real world example, let’s first look at what primitives need to be built that form the basis of a real-time machine learning architecture.</p><p><strong>System Primitives</strong></p><ol><li>Task creation needs to be non-blocking and a “future” can be returned after task creation. Tasks will be executed asynchronously and futures can be obtained as needed.</li><li>Any function call can be deemed as remote execution to support various tasks types and their execution on different hardware types. The function call can take simple data values or futures as arguments. When a future is used as an argument, then that means there is a dataflow dependency(DAG) between the task that provides the future and the task that needs the future as input.</li><li>Any task can create new tasks which may need to be executed remotely. This also helps to remove the dependency on throughput of that specific worker/task where the original task is running.</li><li>“get” method on a future will return the value of the task when it is ready and this is a blocking call.</li><li>“wait” method can use multiple futures as inputs and a timeout value. It returns the futures that have completed on a timeout or if a certain threshold of tasks have been completed already. Such wait primitives can help with the latency requirements because they provide an ability to ignore certain tasks which can take a long time and might provide only marginal improvements which can be common in ML algorithms.</li></ol><p><strong>Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*YKplO6xw3ho4bRaawrB1TQ.png" /><figcaption>Proposed hybrid architecture with local and global schedulers</figcaption></figure><p>At a high level, each node in the cluster has a local scheduler that is managing multiple worker processes which share some information via some shared memory. There is also a global scheduler that is responsible for managing centralized control information. This makes for a hybrid scheduling approach.</p><p><strong>Centralized scheduler</strong></p><p>The global scheduler uses a database for managing centralized control state of the system. As long as the database is fault-tolerant, the system can recover from component failures. In addition, a pub-sub system manages the updates on significant event changes that different components in the system can react to. Database can be sharded for better scalability.</p><p><strong>Hybrid scheduling</strong></p><p>Given R1 and R2, it makes sense to be able to make local scheduling decisions to avail data locality. The worker on the given node can submit tasks to local scheduler. Local scheduler can decide to schedule the task on the given node or submit it to global scheduler if there is spillover. Global schedulers are looking at the overall global state, data placements and resource availability and making the scheduling decisions. As tasks can create some other tasks, those can be scheduled locally for optimal execution.</p><h4>Conclusion</h4><p>The system design approach outlined in this paper seemed like a good way to design a new-age ML framework. Principles lead the way to the hybrid scheduling approach. In subsequent posts, I intend to cover <a href="https://arxiv.org/pdf/1712.05889.pdf">Ray</a> framework, which i believe is based on these principles .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e46f827a7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mesos: A cluster scheduler for diverse frameworks]]></title>
            <link>https://medium.com/coinmonks/mesos-a-cluster-scheduler-for-diverse-frameworks-131ffbd082ca?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/131ffbd082ca</guid>
            <category><![CDATA[mesos]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[apache-mesos]]></category>
            <category><![CDATA[cluster-scheduling]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 20:57:15 GMT</pubDate>
            <atom:updated>2020-08-31T17:19:25.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*_zI5dFwfO90pMeZle9a7WA.png" /></figure><h4>Introduction</h4><p>In companies or research groups that are working on large compute loads or datasets, there are many applications that run using different types of application frameworks such as map-reduce, spark, Dyrad, Pregel. No single framework is a panacea. In presence of such diverse workloads, it is important that different frameworks are able to share the resources of the cluster efficiently. One traditional approach has been to reserve capacity by static partitioning of the cluster or by allocating a certain number of VMs for each framework. Such allocation is not optimal and leads to either overworked or underutilized cluster resources.</p><p>To provide efficient utilization of cluster resources, <a href="https://amplab.cs.berkeley.edu/wp-content/uploads/2011/06/Mesos-A-Platform-for-Fine-Grained-Resource-Sharing-in-the-Data-Center.pdf">Mesos</a>, offers a fine grained resource scheduler, that monitors the current cluster resource usage and then offers resources to these frameworks, as they become available. Mesos is highly scalable as it can deal with tens of thousands of nodes and tasks in a cluster and their resources. Also it is fault tolerant as critical applications depend on it. Mesos is designed in a way to be able to support multiple different frameworks such as map-reduce, MPI, spark.</p><h4>Design Approaches</h4><p>One approach for such a cluster scheduler could be to have a centralized scheduler that gets resource requirements for all the frameworks and then comes up with an optimal policy across all frameworks. While this seems promising, it also is a very hard problem to solve which would affect scalability of such a scheduler. Another issue is that new frameworks are evolving all the time and it is not clear if an optimal scheduler can be built that take into account their future needs.</p><p>Instead, Mesos uses a decentralized scheduling approach using a technique of “resource offer”. Mesos scheduler decides how many resources of different types can it hand out to a given framework based on some high level organization policy. The framework can decide to take or reject the resources offered. If the framework takes the offer, then it can schedule it’s own tasks using these resources. While this may not lead to the most optimal scheduling approach, it scales well and performs pretty optimally taking into account data locality and alike. This also allows framework builders to build specialized frameworks and schedulers that perform well for those workloads.</p><p>The classic workload that Mesos was originally built on consisted of many small tasks and some long tasks. The median for jobs takes approximately 30s. Traditionally such clusters at facebook, yahoo were used for loading log data and running interactive queries on it or running some map-reduce tasks.</p><h4>High level architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*9cGUhdvAbrZzqLrvf_N5Wg.png" /><figcaption>Mesos master making resource offers and Framework scheduler using that to deploy tasks on nodes on the cluster where framework executors and mesos slave runs</figcaption></figure><p>Mesos consists of slave processes that run on each node in the cluster. There is mesos master process what is connected to these slaves that are monitoring local resource usage. Each framework has its own scheduler and an executor. Executor runs on the same nodes that slave runs on. Framework scheduler decides which tasks needs to run on which nodes and then hands it off to the master. Master can then use the slaves and executors for running jobs on the nodes as assigned by the framework scheduler. The first resource offer is dependent on organization policy such as should resources be assigned fairly or using some other priority based mechanism. These different policies can be plugged into Mesos master by using an allocation module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*P3rch5kF74hTv9Wc_Qo0tQ.png" /><figcaption>Resource offer sequence from slave-&gt;AllocationModule-&gt;Framework-&gt;Master-&gt;slave</figcaption></figure><p>In the diagram above, Mesos-slave1 notices that node 1 has 4Cpus and 4 GB memeory available. It informs that to the master. Master(based on the organizational policy) offers all of these resources to framework1. Framework currently has only 2 tasks that it wants scheduled: task1 needs 2cpus and 1GB memory, while task2 needs 1cpu and 2GB memory. The framework informs the master about this. Master can then assigns these resources to the slave1 which reserves this resources and informs the framework executor which can then launch the two tasks that framework1 is interested in. There is still 1 CPU and 1 GB left, which master can offer to framework2 or any other resources that might become available from slave2.</p><p>The question that still remains is how can frameworks leverage the data locality. This is an issue because the master is unaware of what each framework needs for optimal locality. This is achieved by having the framework scheduler reject the offer of resources, if it thinks that it is not optimal or hampers the locality drastically. Frameworks also use <a href="https://cs.stanford.edu/~matei/papers/2010/eurosys_delay_scheduling.pdf">delay scheduling</a> to wait for some time for nodes to become available which can achieve near-optimal locality.</p><p>Resource offers need to be scalable. This is achieved by implementing filters at the master. Frameworks can specify filters such as “only give me nodes from a certain list of nodes, ignore nodes that don’t have x”. In addition, for the master to scale, master incentivizes the frameworks to respond quickly to it’s offers: Either by rescinding offers that are taking a long time for confirmation by the framework or by counting the unacknowledged resource offers towards the usage of the framework.</p><h4>Allocation module and Revocations</h4><p>As mentioned earlier, the allocation module is a pluggable entity in the master process. So organizations can direct it in a manner that helps them. Two default choices are fair scheduling and strict priorities.</p><p>With the help of delay scheduling, most short tasks don’t have to wait for long. They generally get resources after waiting for a short time. It is possible that long running tasks or buggy code blocks the short running tasks. In such cases, the master can kill the long running process by giving them some grace period. Grace period helps the long running(non buggy) processes by setting up recovery mode when the process comes back up again.</p><p>Generally, short tasks are not too perturbed by revocations. In addition, each framework can ask for some guaranteed allocation. As long as, the framework is under this allocation, it won’t have any tasks terminated. If the framework is above the allocation limit, then any task can get killed. This simplistic scheme can be improved by assigning priorities to tasks of a framework and lower priority tasks can be killed until the usage falls below the allocation limits.</p><h4>Mesos master fault tolerance</h4><p>Mesos slaves are already distributed and need local recovery mechanisms when they die. Frameworks also get notified of the failures on slaves and executors.</p><p>Main central point of failure is the master. Master uses zookeeper for fault tolerance. A hot-standby (and other standby masters) is registered with zookeeper to take over as soon as zookeeper notices the master failure. In addition, master is designed to operate with soft-state i.e. it can reconstruct its state using periodic messages from the slaves and the framework schedulers.</p><p>Similarly framework schedulers can also die. So framework schedulers can register their failover schedulers so that operations can continue seamlessly. But frameworks need to figure out a way to share state among themselves.</p><h4>Defining and measuring Mesos’ effectiveness</h4><p>The authors discuss what kind of workloads might Mesos have to schedule and how to measure the effectiveness of scheduling in those cases. The different types of workload that authors considered were: The workloads that can scale-up or scale-down elastically. Workloads can be separated by their durations i.e. short, medium, long. Another type of workload can be one that has to wait for certain number of resources to become available.</p><p>In presence of such workloads, Mesos measures the following metrics:</p><ol><li>Framework ramp-up time: The time it takes for a framework to achieve it’s allocation</li><li>Job completion times: How long does it take for jobs to complete</li><li>Cluster utilization: How occupied vs idle is the given cluster.</li></ol><p>The paper summarizes their work from another paper in a table explaining the effect of scheduling on these numbers. While this works reasonably well for homogeneous tasks, there is question of long tasks versus short tasks. You don’t want long tasks starving short ones. This can be done by placing a cap on percentage utilization for long tasks in the given cluster e.g. no more than 50% resources will be allocated for large tasks. Master can have different timeouts for task revocation and ensure that it incentivizes short tasks.</p><h4>Incentives for frameworks</h4><p>As mentioned earlier, Mesos gives frameworks some control over their scheduling needs. It means that it is important to build Mesos such that frameworks are incentivized for high utilization. For atask that framework wants to launch, here are some incentive structures that are built into Mesos.</p><ol><li>Short tasks: These are incentivized because short tasks will find resources quickly and also will have less recovery cost if those were to be killed.</li><li>Lack of guaranteed allocation: This ensures that frameworks can start using resources as soon as any of them become available as opposed to ALL of them.</li><li>Elastic resource usage: This is ensured because frameworks can scale down when cluster is under pressure without getting the whole job killed and scale up by grabbing resources when they are available.</li><li>Usable resources: Only usable resources should be accepted by frameworks(e.g. GPUs), otherwise it is holding onto resources that count towards its cluster usage, but actually not using. This will affect the future resource allocation for itself.</li></ol><h4>When is the distributed scheduling is sub-optmial?</h4><p>As we have seen Mesos is not a centralized scheduler. When tasks are heterogenous, Mesos may not able to do bin-packing as effectively as a centralized scheduler that is aware of all the different tasks. This will lead to fragmented use of the scheduler. There is also some chance of starvation of large tasks because as soon as small resources free up, small tasks take up that slot. This can be prevented by having minimum offer sizes that Mesos will make to frameworks and ensures that certain sized resource set is available before it is offered. In terms of complexity of schedulers for frameworks, frameworks need to know about their needs anyway and then express it to a centralized scheduler or use the resource offers made by a decentralized scheduler — in fact, a lot of schedulers cannot predict task times and need to make online adjustments to the scheduler.</p><h4>Conclusion</h4><p>Mesos is useful for fine grained scheduling in clusters so that different types of frameworks can get access to the resources of the cluster in an efficient manner. Frameworks can scale up and down depending on cluster utilization and use resource offers from the master for scheduling their tasks optimally. I thought distributed scheduling approach of Mesos was pretty novel.</p><blockquote><a href="https://coincodecap.com/?utm_source=coinmonks">Get Best Software Deals Directly In Your Inbox</a></blockquote><figure><a href="https://coincodecap.com/?utm_source=coinmonks"><img alt="" src="https://cdn-images-1.medium.com/max/584/0*OJ-qb5G6i863msBB.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=131ffbd082ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/mesos-a-cluster-scheduler-for-diverse-frameworks-131ffbd082ca">Mesos: A cluster scheduler for diverse frameworks</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wormhole : A pub-sub system at Facebook]]></title>
            <link>https://medium.com/coinmonks/wormhole-a-pub-sub-system-at-facebook-6274ea5fd11b?source=rss-793f3e5d88dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6274ea5fd11b</guid>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[research-paper]]></category>
            <dc:creator><![CDATA[Ameya]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 01:01:48 GMT</pubDate>
            <atom:updated>2020-08-31T17:39:43.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*HOGUDPxBDGOdXuui_Frilw.jpeg" /><figcaption>A wormhole shortcut in space-time. Credit: <a href="http://www.shutterstock.com/">Shutterstock</a></figcaption></figure><h4>Introduction</h4><p>Publish-Subscribe systems solve the problem of communicating changes in system efficiently. Whenever a certain data is changed, a publisher informs subscribers about this change. In a classical application that uses a database for storing state, producers of data may write to a database. In order to gather these updates, subscribers then face the dilemma of polling infrequently at the cost of operating on stale data for some time or polling often at the cost of performance overhead on the database itself. Pub-sub systems solve this problem by generally introducing an intermediate broker. Publishers publish to the broker about changes and subscribes register with the broker for getting change notifications.</p><p>In Facebook, many applications depend on such change notifications. Newsfeed may want to receive the latest updates, friends may want to access the notification content. In addition, even internal systems such as index modification or cache invalidation can benefit by knowing about changes in the underlying data or to invalidate data that is not valid anymore. This obviously generates a ton of data internally. This data is internally sharded and stored across many clusters using systems such as RocksDB, HDFS, MySQL etc. For Facebook, to use such a broker based system would mean that the broker would need to support Facebook’s internal systems and scale to very high volume and also there would be replication at a large scale. To address these limitations Facebook proposed a new system called <a href="https://www.usenix.org/system/files/conference/nsdi15/nsdi15-paper-sharma.pdf">wormhole</a>.</p><p>In wormhole, subscribers register with the data systems directly. All data systems maintain transaction logs. Wormhole uses these logs to identify updates and then propagate those updates to the subscribers. This is quite unique and completely obviates the need for an intermediate broker, but it means publishers may need to be specialized for different data systems. In this post, we will cover the high level architecture of wormhole.</p><h4>Challenges at Facebook for a pub-sub system</h4><p>As you can imagine, a lot of data gets generated at Facebook. For reliability, this data is sharded and geo-replicated across data centers. In addition, there are many data systems at facebook — <a href="https://medium.com/coinmonks/tao-facebooks-distributed-database-for-social-graph-c2b45f5346ea">Tao</a> which optimizes read heavy graph data and <a href="https://www.usenix.org/system/files/conference/nsdi13/nsdi13-final170_update.pdf">memcache</a> for read-heavy workload. Such systems use aggressive caching for offloading database access. On a write, these cached copies need to be invalidated or if there is an index on the database then that needs to be rebuilt. In addition, a pub-sub system may need to support the following:</p><ol><li>In order delivery of updates from the same shard</li><li>At least once delivery — No updates are ever lost, but some duplicates might be delivered</li><li>Different consumers may have different storage and speed of consumption needs.</li><li>Like with any big distributed systems, it needs to be fault tolerant and software and hardware exceptions are the norm.</li></ol><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*BHqcbWxNl8SfIjSnEoN7KA.png" /><figcaption>Wormhole architecture with many-to-many mapping between publishers and subscriber shards.</figcaption></figure><p>Wormhole consists of a datastore that is scaled to address needs of facebook. Each such datastore, MySQL or TAO runs a publisher. This is the Wormhole publisher. This publisher knows how to consume the content written to the transaction logs by the producers of data. Publisher then converts this native data-store format to a key-value format that is standardized and then delivers it to subscribers. A publisher finds the subscribers by reading the zookeeper(distributed coordination service like <a href="https://medium.com/coinmonks/chubby-a-centralized-lock-service-for-distributed-applications-390571273052">chubby</a>) configuration file for that data store. A subscriber or application gets a client side wormhole library which registers with zookeeper. One interesting aspect of subscribers is that, for a given application, multiple subscribers exist and they are assigned to deal with some shard of the overall data by the publisher. Publishers assign ownership of specific shards to specific subscribers and then send updates of shards to the corresponding subscribers. For the given shard, all updates always land on the same subscriber as long as it is available. Publishers ensure that all updates from the given shard are delivered in-order to the subscribers.</p><p>It is good to introduce some terminology at this point which will be useful in subsequent sections.</p><p><em>Datastore</em> stores a collection of <em>shards </em>for the dataset.</p><p><em>Flow: </em>A stream of updates for every shard that is sent by the publisher to the subscriber. It contains the shard number in the every update.</p><p><em>Datamarker</em>: It indicates the last successfully acknowledged flow by the subscriber. This is a pointer into the transaction log of the given datastore. Publisher stores the datamarkers to ensure at least once delivery of data to subscribers.</p><p><em>Reader</em>: Component that funnels the reads from the transaction log to the publisher. Explained more in next section.</p><p><em>Caravan and leader</em>: A reader and associated flow is called a caravan. Since multiple readers can be reading from the transaction log at the same time, the reader that has read the farthest is called the lead caravan.</p><h4>Delivering updates to the subscribers</h4><p>A publisher reads the zookeeper file for discovering which applications are interested in updates. For each shard and application pair, it creates a stream of updates i.e. flow. Once in a steady state, a reader is reading from the most current location and sending out updates. The reader helps with managing the transaction log access in an efficient manner. When recovery is in progress, reading from multiple data markers i.e. positions in the log might be necessary. To avoid thrashing the disk, reader can manage the data access more efficiently. Hopefully this explains the concept of caravan and the lead caravan.</p><p>In addition, publisher tries to not overwhelm the subscriber. So publisher can publish the given flow to a lightly loaded subscriber using a weighted random selection. In addition, the subscribers can update the zookeeper file to divert away load to some other subscribers. Once publisher establishes the flow between caravan and subscriber, all the updates are sent over TCP for reliable in-order delivery. Wormhole also multiplexes many updates over the same connection to reduce connection overhead.</p><h4>Multiple Caravan and Slow consumers</h4><p>Generally the lead caravan is satisfying most updates and reading from the most current time. But either during recovery or when there are slow consumers, multiple caravans are needed to send the old updates. Allocation of caravans to flows is dependent on I/O load vs latency requirements. If there were a lot of caravans then they can access disk pretty arbitrarily and cause heavy I/O load. But they unblock later updates in the same flow much more quickly. On the other hand, if there are less number of caravans, then I/O load can be optimized better by batching the disk access. But this may cause increase in latency due to longer queues — specially for the later or most recent updates. Wormhole allows for caravans to split and merge depending on these two parameters. Typically, non-lead caravans are asked to read at faster speed so that they can catch up with lead caravan. Also there are configuration limits to avoid excessive disk usage by limiting speed of reads, number of caravans etc.</p><h4>Filtering</h4><p>A nice feature is for application/subscriber to specify what it would like the publisher to filter. This can be done via configuration using simple AND/OR based filtering rules. Publisher will not send these updates to the subscriber applications. Popular types of filters are: <em>Is key in a specific range? Does key have a specific value? Negation of such membership queries.</em></p><h4>Reliable Delivery with single publisher</h4><p>Reliable delivery is important for wormhole because critical processes such as index generation depend on it. Missing an update on an index, would obviously cause an inconsistent state of index. Hence wormhole publisher uses datamarkers with updates it is sending to subscribers. When clients acknowledge the markers, publishers write the datamarkers(offset into the transaction log) to a persistent log. If a publisher process dies and comes back up, it can start reading from the last acknowledged datamarker and send updates from there on. This can obviously cause duplicates, but subscribers own the responsibility of dealing with duplicates. If subscriber fails, then publisher can use the same mechanism to send updates from the last acknowledged marker. Usage of TCP ensures in-order delivery.</p><h4>Reliable Delivery with publisher failover</h4><p>Most of the data in facebook is geo-replicated for reliability. Subscribers can register with multiple copies of the dataset. When publisher faces a hard failure like machine not coming up, another publisher needs to help with the recovery. In this mode, wormhole guarantees at least once delivery of all updates from some dataset. This poses several challenges.</p><p>When a publisher experiences a permanent failure, generally all the datamarkers that are stored on the same machine also become unavailable. Also publishers don’t communicate with each other to avoid overhead. To overcome these limitations, wormhole uses zookeeper to store datamarkers.</p><p>Consider the following diagram of a geo replicated database. There are two publishers P1 and P2. P1 initially owns the flows for A1. As P1 updates A1 subscribers, it is storing datamarkers in zookeeper. In addition, each publisher gets a corresponding ephemeral node which other publishers watch. Ephemeral node in distributed coordination is something that disappears once its owner of the node goes away. In this case once P1 dies, P1 ephemeral node may disappear and P2 will get a notification of it via Zookeepr API. Now P2 can take over the ownership of the flows and start publishing to A1 via stored datamarkers. One more implementation detail here is that datamarkers are pointers into the transaction logs which cannot be used directly by P2. Hence wormhole adds logical offsets to help with that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*IHjqMvjC-nXPuvnW0WXTNQ.png" /><figcaption>Publisher failover monitored by backup publishers that are watching ephemeral zookeeper nodes</figcaption></figure><p>Some of the operational improvements include using a distributed deployment model using a monitor on the same machine as the publisher instead of a centralized deployment model. In addition, all the configuration is made dynamic such that it doesn’t always need a restart of the process for the new configuration to take effect.</p><h4>Comparable pub-sub systems</h4><p>Most comparable pub-sub systems like Kafka, RabbitMQ use an intermediate brokers. These brokers can store and forward messages depending on the speed of the consumers. This is not needed in Facebook as their datastores already keep a reliable log. In addition the data scale makes development of an intermediate broker equally challenging and may add additional latency.</p><p>Google’s Thialfi only works with version numbers and is used for invalidation of data. While wormhole can be used for data refills since it sends data updates. Kafka can lose data if broker fails and runs an order of magnitude slower than wormhole. Apache Hedwig doesn’t scale with too many publishers and subscribers. Various message queue implementations do not scale as well for facebook with limitations on geo replication or they are not just generic enough.</p><h4>Conclusions</h4><p>Although more complex, Wormhole provides a pretty unique and efficient mechanism to implement pub-sub systems in data intensive and high throughput environments using transaction logs which i found to be pretty different than how traditional pub-sub systems are implemented.</p><blockquote><a href="https://coincodecap.com/?utm_source=coinmonks">Get Best Software Deals Directly In Your Inbox</a></blockquote><figure><a href="https://coincodecap.com/?utm_source=coinmonks"><img alt="" src="https://cdn-images-1.medium.com/max/584/0*OJ-qb5G6i863msBB.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6274ea5fd11b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/wormhole-a-pub-sub-system-at-facebook-6274ea5fd11b">Wormhole : A pub-sub system at Facebook</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>