Serving article comments using neural nets and reinforcement learning
<p>Yahoo properties such as Yahoo Finance, Yahoo News, and Yahoo Sports allow users to comment on the articles, similar to many other apps and websites. To support this we needed a system that can add, find, count and serve comments at scale in real time. Not all comments are equally as interesting or relevant though, and some articles can have hundreds of thousands of comments, so a good commenting system must also choose the right comments among these to show to users viewing the article. To accomplish this, the system must observe what users are doing and learn how to pick comments that are interesting.<br/></p><p>In this blog post, we’ll explain how we’re solving this problem for Yahoo properties by using <a href="https://vespa.ai">Vespa</a> - the open source big data serving engine. We’ll start with the basics and then show how comment selection using a neural net and reinforcement learning has been implemented.<br/></p><p><b>Real-time comment serving<br/></b></p><p>As mentioned, we need a system that can add, find, count, and serve comments at scale in real time. Vespa allows us to do this easily by storing each comment as a separate document, containing the ID of the article commented upon, the ID of the user commenting, various comment metadata, and the comment text itself. Vespa then allows us to issue queries to quickly retrieve the comments on a given article for display, or to show a comment count next to the article:</p><figure data-orig-width="1080" data-orig-height="191" class="tmblr-full"><img src="https://66.media.tumblr.com/a5b66936e7234eee3b303f3751d65051/tumblr_inline_pmf4v1kZRA1wxhpzr_540.png" alt="image" data-orig-width="1080" data-orig-height="191"/></figure><p><b><br/>Ranking comments</b></p><p>In addition, we can show all the articles of a given user and similar less-used operations.<b><br/></b></p><p>We store about a billion comments at any time, serve about 12.000 queries per second, and about twice as many writes (new comments + comment metadata updates). Average latency for queries is about 4 ms, and write latency roughly 1 ms. Nodes are organized in two tiers as a single <a href="https://docs.vespa.ai/documentation/cloudconfig/application-packages.html">Vespa application</a>: A single stateless cluster handling incoming queries and writes, and a content cluster storing the comments, maintaining indexes and executing the distributed part of queries in parallel. In total, we use 32 stateless and 96 stateful nodes spread over 5 regional data centers. Data is automatically sharded by Vespa in each datacenter, in 6-12 shards depending on the traffic patterns of that region.</p><p>Some articles have a very large number of comments - up to hundreds of thousands are not uncommon, and no user is going to read all of them. Therefore we need to pick the best comments to show each time someone views an article. To do this, we let Vespa find all the comments for the article, compute a score for each, and pick the comments with the best scores to show to the user. This process is called ranking. By configuring the function to compute for each comment as a <a href="https://docs.vespa.ai/documentation/reference/ranking-expressions.html">ranking expression</a> in Vespa, the engine will compute it locally on each data partition in parallel during query execution. This allows us to execute these queries with low latency and ensures that we can handle more comments by adding more content nodes, without causing an increase in latency.</p><p>The input to the ranking function is features which are typically stored in the comment or sent with the query. Comments have various features indicating how users interacted with the comment, as well as features computed from the comment content itself. In addition, we keep track of the reputation of each comment author as a feature.</p><p>User actions are sent as <a href="https://docs.vespa.ai/documentation/document-api.html#put">update operations</a> to Vespa as they are performed. The information about authors is also continuously changing, but since each author can write many comments it would be wasteful to have to update each article everytime we have new information about the author. Instead, we store the author information in a separate document type - one document per author and use a <a href="https://docs.vespa.ai/documentation/search-definitions.html#document-references">document reference</a> in Vespa to import that author feature into each comment. This allows us to update author information once and have it automatically take effect for all comments by that author.</p><p><b></b></p><p>With these features, we can configure a mathematical function as a ranking expression which computes the rank score or each comment to produce a ranked list of the top comments, like the following:</p><figure data-orig-width="1240" data-orig-height="740" class="tmblr-full"><img src="https://66.media.tumblr.com/20f851ddc83cae50b5b24b2797c30cff/tumblr_inline_pmf4y2aJta1wxhpzr_540.png" alt="image" data-orig-width="1240" data-orig-height="740"/></figure><p><b>Using a neural net and reinforcement learning<br/></b></p><p>We used to rank comments using a handwritten ranking expression with hardcoded weighting of the features. This is a good way to get started but obviously not optimal. To improve it we need to decide on a measurable target and use machine learning to optimize towards it.</p><p>The ultimate goal is for users to find the comments interesting. This can not be measured directly, but luckily we can define a good proxy for interest based on signals such as dwell time (the amount of time the users spend on the comments of an article) and user actions (whether users reply to comments, provide upvotes and downvotes, etc). We know that we want user interest to go up on average, but we don’t know what the correct value of this measure of interest might be for any given list of comments. Therefore it’s hard to create a training set of interest signals for articles (supervised learning), so we chose to use reinforcement learning instead: Let the system make small changes to the live machine-learned model iteratively, observe the effect on the signal we use as a proxy for user interest, and use this to converge on a model that increases it.</p><p><b></b></p><p>The model chosen is a neural net with multiple hidden layers, roughly illustrated as follows:</p><figure data-orig-width="998" data-orig-height="550" class="tmblr-full"><img src="https://66.media.tumblr.com/151063a753002f0caf9a6437c07b824b/tumblr_inline_pm9r40Dpc71wxhpzr_540.png" alt="image" data-orig-width="998" data-orig-height="550"/></figure><p>The advantage of using a neural net compared to a simple function such as linear regression is that we can capture non-linear relationships in the feature data without having to guess which relationship exists and hand-write functions to capture them (feature engineering).<b><br/></b></p><p>To explore the space of possible rankings, we implement a sampling algorithm in a <a href="https://docs.vespa.ai/documentation/searcher-development.html">Searcher</a> to perturb the ranking of comments returned from each query. We log the ranking information and our user interest signals such as dwell time to our Hadoop grid where they are joined. This generates a training set each hour which we use to retrain the model using <a href="https://github.com/yahoo/TensorFlowOnSpark">TensorFlow-on-Spark</a>, which generates a new model for the next iteration of the reinforcement learning.</p><p>To implement this on Vespa, we configure the neural net as the ranking function for comments. This was done as a manually written <a href="https://docs.vespa.ai/documentation/tensor-user-guide.html">ranking function over tensors</a> in a <a href="https://docs.vespa.ai/documentation/ranking.html">rank profile</a>:</p><p> rank-profile neuralNet {</p><p> function get_model_weights(field) {</p><p> expression: if(query(field) == 0, constant(field), query(field))</p><p> }</p><p> function layer_0() { # returns tensor(hidden[9])</p><p> expression: elu(xw_plus_b(nn_input,</p><p> get_model_weights(W_0),</p><p> get_model_weights(b_0),</p><p> x))</p><p> }</p><p> function layer_1() { # returns tensor(out[9])</p><p> expression: elu(xw_plus_b(layer_0,</p><p> get_model_weights(W_1),</p><p> get_model_weights(b_1),</p><p> hidden))</p><p> }</p><p> function layer_out() { # xw_plus_b returns tensor(out[1]), so sum converts to double</p><p> expression: sum(xw_plus_b(layer_1,</p><p> get_model_weights(W_out),</p><p> get_model_weights(b_out),</p><p> out))</p><p> }</p><p> first-phase {</p><p> expression: freshnessRank</p><p> }</p><p> second-phase {</p><p> expression: layer_out</p><p> rerank-count: 2000</p><p> }</p><p> }</p><p>More recently Vespa added support for <a href="https://docs.vespa.ai/documentation/tensorflow.html">deploying TensorFlow SavedModels directly</a>, which would also be a good option since the training happens in TensorFlow.<b><br/></b></p><p>Neural nets have a pair of weight and bias tensors for each layer, which is what we want our training process to optimize. The simplest way to include the weights and biases in the model is to add them as constant tensors to the application package. However, to do reinforcement learning we need to be able to update them frequently. We could achieve this by redeploying the application package frequently, as Vespa allows this to be done without restarts or disruption to ongoing queries. However, it is still a somewhat heavy-weight process, so we chose another approach: Store the neural net parameters as tensors in a separate document type, and create a Searcher component which looks up this document on each incoming query, and adds the parameter tensors to it before it’s passed to the content nodes for evaluation.</p><p>Here is the full code needed to accomplish this:</p><p>import com.yahoo.document.Document;<b><br/></b></p><p>import com.yahoo.document.DocumentId;</p><p>import com.yahoo.document.Field;</p><p>import com.yahoo.document.datatypes.FieldValue;</p><p>import com.yahoo.document.datatypes.TensorFieldValue;</p><p>import com.yahoo.documentapi.DocumentAccess;</p><p>import com.yahoo.documentapi.SyncParameters;</p><p>import com.yahoo.documentapi.SyncSession;</p><p>import com.yahoo.search.Query;</p><p>import com.yahoo.search.Result;</p><p>import com.yahoo.search.Searcher;</p><p>import com.yahoo.search.searchchain.Execution;</p><p>import com.yahoo.tensor.Tensor;</p><p>import java.util.Map;</p><p>public class LoadRankingmodelSearcher extends Searcher {</p><p> private static final String VESPA_DOCUMENTID_FORMAT = “id:canvass_search:rankingmodel::%s”;</p><p> // <a href="https://docs.vespa.ai/documentation/ranking.html#using-query-variables:">https://docs.vespa.ai/documentation/ranking.html#using-query-variables:</a></p><p> private static final String QUERY_FEATURE_FORMAT = “query(%s)”; </p><p> /** To fetch model documents from Vespa index */</p><p> private final SyncSession fetchDocumentSession;</p><p> public LoadRankingmodelSearcher() {</p><p> this.fetchDocumentSession = DocumentAccess.createDefault().createSyncSession(new SyncParameters.Builder().build());</p><p> }</p><p> @Override</p><p> public Result search(Query query, Execution execution) {</p><p> // fetch model document from Vespa</p><p> String documentId = String.format(VESPA_DOCUMENTID_FORMAT, query.getRanking().getProfile());</p><p> Document modelDoc = fetchDocumentSession.get(new DocumentId(documentId));</p><p> // Add it to the query</p><p> if (modelDoc != null) {</p><p> modelDoc.iterator().forEachRemaining((Map.Entry<Field, FieldValue> e) -></p><p> addTensorFromDocumentToQuery(e.getKey().getName(), e.getValue(), query)</p><p> );</p><p> }</p><p> return execution.search(query);</p><p> }</p><p> private static void addTensorFromDocumentToQuery(String field, FieldValue value, Query query) {</p><p> if (value instanceof TensorFieldValue) {</p><p> Tensor tensor = ((TensorFieldValue) value).getTensor().get();</p><p> query.getRanking().getFeatures().put(String.format(QUERY_FEATURE_FORMAT, field), tensor);</p><p> }</p><p> }</p><p>}</p><p>The model weight document definition is added to the same content cluster as the comment documents and simply contains attribute fields for each weight and bias tensor of the neural net:</p><p> document rankingmodel {</p><p> field modelTimestamp type long { … }</p><p> field W_0 type tensor(x[9],hidden[9]){ … }</p><p> field b_0 type tensor(hidden[9]){ … }</p><p> field W_1 type tensor(hidden[9],out[9]){ … }</p><p> field b_1 type tensor(out[9]){ … }</p><p> field W_out type tensor(out[9]){ … }</p><p> field b_out type tensor(out[1]){ … }</p><p> }</p><p>Since updating documents is a lightweight operation we can now make frequent changes to the neural net to implement the reinforcement learning.</p><p><b>Results<br/></b></p><p>Switching to the neural net model with reinforcement learning led to a 20% increase in average dwell time. The average response time when ranking with the neural net increased to about 7 ms since the neural net model is more expensive. The response time stays low because in Vespa the neural net is evaluated on all the content nodes (partitions) in parallel. We avoid the bottleneck of sending the data for each comment to be evaluated over the network and can <a href="http://blog.vespa.ai/post/173669458506/scaling-tensorflow-model-evaluation-with-vespa">increase parallelization indefinitely</a> by adding more content nodes.</p><p>However, evaluating the neural net for all comments for outlier articles which have hundreds of thousands of comments would still be very costly. If you read the rank profile configuration shown above, you’ll have noticed the solution to this: We use two-phase ranking where the comments are first selected by a cheap rank function (which we term freshnessRank) and the highest scoring 2000 documents (per content node) are re-ranked using the neural net. This caps the max CPU spent on evaluating the neural net per query.</p><p><b>Conclusion and future work</b><br/></p><p>We have shown how to implement a real comment serving and ranking system on Vespa. With reinforcement learning gaining popularity, the serving system needs to become a more integrated part of the machine learning stack, and by using <a href="https://vespa.ai/">Vespa</a> and <a href="https://github.com/yahoo/TensorFlowOnSpark">TensorFlow-on-Spark</a>, this can be accomplished relatively easily with a standard open source technology.</p><p>We plan to expand on this work by applying it to other domains such as content recommendation, incorporating more features in a larger network, and exploring personalized comment ranking.</p><p><b>Acknowledgments</b><br/></p><p>Thanks to Aaron Nagao, Sreekanth Ramakrishnan, Zhi Qu, Xue Wu, Kapil Thadani, Akshay Soni, Parikshit Shah, Troy Chevalier, Sreekanth Ramakrishnan, Jon Bratseth, Lester Solbakken and Håvard Pettersen for their contributions to this work.</p>