Saturday, September 30, 2017

Serving Keras models using Tensorflow Serving


One of the reasons I have been optimistic about the addition of Keras as an API to Tensorflow is the possibility of using Tensorflow Serving (TF Serving), described by its creators as a flexible, high performance serving system for machine learning models, designed for production environments. There are also some instances of TF Serving being used in production outside Google, as described in Large Scale deployment of TF Serving at Zendesk. In the past I have built custom microservices that wrapped my machine learning models, which could then be consumed by client code in a language agnostic manner. But this is a repetitive task one has to do at some point for each new model being deployed, so the promise of a generic application into which I could just drop my trained model and have it be immediately available for use was too good to pass up, and I decided to check out TF Serving. In this post, I describe my experiences, hopefully it is helpful.

I installed TF Serving from source on my Linux Ubuntu 16.04 based notebook following the instructions on the TF Serving Installation page. This requires you to download the bazel build tool and install the grpc Python module. Compiling takes a while but is uneventful if you have all the prerequisites (listed in the instructions) set up correctly. Once done, the executables are available in the bazel-bin subdirectory under the TF Serving project root.

My initial thought was to create my model using Tensorflow and the embedded Keras API, that way the model would be serialized into the Tensorflow format rather than the HDF5 format that Keras uses. However, it turns out that TF Serving uses yet another format to serialize and export trained models, so you have to convert to it from either format. Hence there is no advantage to the hybrid Keras/TF approach over the pure Keras approach.

In fact, the hybrid Keras/TF approach has the problem of having to explicitly specify the learning_phase. Certain layers such as Dropout and BatchNormalization function differently during training and testing. Keras calls the fit() and predict() functions respectively during training and testing, so it is able to differentiate the necessary behaviors. Tensorflow, however, calls session.run() for both training and testing, so the learning_phase parameter needs to be supplied as an additional boolean placeholder tensor during this call for it to differentiate between the two steps.

I was able to build and train a hybrid CNN Keras/TF model to predict MNIST digits using the Keras API embedded in TF, and save it in a format that TF Serving recognized and is able to serve up through gRPC, but I was unable to consume the service successfully to do predictions. The error message indicates that the model expects an additional input parameter, which I suspect is the learning_phase. Another issue is that it forces me to input both image and label, an artefact of how I built the model to begin with. The labels need to be passed in because we are computing training accuracy. I didn't end up refactoring this code because I found a way to serve native Keras models directly using TF Serving, which I describe below. For completeness, the links below point to notebooks to build and train the hybrid CNN Keras/TF model, to serialize the resulting TF model to a form suitable for TF Serving, and the client code to consume the service offered by TF Serving.


In case you want to investigate this approach further, there are two open source projects that attempt to build on top of TF Serving. They are keras-serving and Amir Abdi's keras-to-tensorflow. Both start from native Keras models and convert them to TF graphs, so not exactly identical, but their code may give you ideas on how to get around the issues I described above.

Next I tried using a native Keras FCN model that was trained using an existing notebook. For what it is worth, this approach finds support in Francois Chollet's Keras as a simplified interface to TF (slightly outdated) blog post, as well as his Integrating Keras and Tensorflow: the Keras workflow, expanded presentation at the TF Dev Summit 2017. In addition, there are articles such as Exporting deep learning models from Keras to TF Serving which also advocate this approach.

I was able to adapt some code from TF Serving Issue # 310, specifically the suggestions from @tspthomas, in order to read the trained Keras model in HDF5 format, and save it to a format usable by TF Serving. The code to consume the service was adapted from a combination of the mnist_client.py example in the TF Serving distribution, plus some online sources. Links for the two notebooks are shown below.


TF Serving allows asynchronous mode operation where requests do not have to wait until the model does the prediction, as well as batched prediction payloads, where the client can send a batch of records for prediction at a time. However, I was only able to make it work synchronously and with one test record at a time. I feel that examples and better documentation would go a long way to increasing the usability (and production use outside Google) of this tool.

Also, as I learn more about TF, I am beginning to question the logic of the Keras move to tf.contrib.keras. Although, to give credit where it is due, my own effort to learn more TF is driven in large part because of this move. TF already has a Layers API which is very similar to the Keras abstraction. More in line with the TF way of doing things, these layers have explicit parameters which can be set to indicate the learning phase instead of a magic learning phase that is handled internally. Also, it appears that pure TF and pure Keras models are both handled well with TF Serving, so I don't see a need for a hybrid model anymore.

Overall, TF Serving appears to be powerful, at least for Keras and TF models. At some point, I hope the TF Serving team decides to make it more accessible to casual users by providing better instructions and examples, or possibly higher level APIs. But until then, I think I will continue with my custom microservices approach.


Thursday, September 14, 2017

EMNLP 2017: Trip Report


Last week, I was at the EMNLP 2017 at Copenhagen. EMNLP is short for Empirical Methods for Natural Language Processing, and is one of the conferences of The Association for Computational Linguistics (ACL) that brings together NLP professionals from academia and industry to talk about their research and present their findings to each other. The conference itself was for 3 days - Saturday September 9 to Monday September 11 - but it was preceded by two days of tutorials and workshops, which I also attended. This is my trip report.

Overview


My main takeaway from the conference is that the NLP community is still heavily invested in deep learning. My frame of reference is NAACL 2015, the last ACL conference I attended, where the majority of the papers were about word embeddings and their applications. Papers this year continue to use word embeddings. But in addition, there are many other kinds of embeddings, such as character and subword embeddings to represent word morphology, phrase embeddings that marry the capabilities of NLP parsers to represent sentence structure. Both offer improvements over the Bag of Words approach or even combining word vectors through Bidirectional LSTMs to produce sentence (or higher abstraction) vectors.

In addition to the Bidirectional LSTM approach, many novel architectures were presented, including CRF-LSTMs, Graph LSTMs, and CNN-LSTMs. These modifications exploit the structure of natural language by providing extra information about phrase structure, emphasizing nearby words, or taking advantage of hierarchy imposed by the application (such as comment threads). Google's efforts with Machine Translation gave us the seq2seq model, but since then it's encoder-decoder architecture with optional attention has been adapted for many other NLP tasks that involve sequence inputs and outputs. In addition, Google briefly talked about their Transformer architecture, which is likely to become more important in coming years. Other interesting ideas are the use of adversarial techniques and joint learning to improve the accuracy of difficult tasks.

One other important trend I saw was the broader adoption of Reinforcement Learning (RL) techniques. I mostly think of RL in the context of game playing AIs, which implies that there is a physics engine somewhere to provide automated reinforcement during training. In the context of NLP, this physics engine seems to be search engine, optionally coupled with domain dependent retrieval rules. Applications taking advantage of RL seem to be mostly related to Learning to Rank (L2R), as far as I could see.

Finally, there were a few papers using more traditional techniques, such as the use of probabilistic graphical models or other Bayesian techniques, or based on clustering and topic modeling. In keeping with the focus on deep learning, almost all of them use word (and optionally character) embeddings to augment their feature set.

Structurally, the conference was organized into three parallel tracks, organized around themes such as Syntax, Semantics, Information Extraction, Machine Translation, Machine Learning, Language Generation, Discourse and Summarization, Multilingual NLP, Language Grounding, Multimodal NLP, Linguistic Theory, Computational Social Science, Sentiment Analysis, Dialog, and NLP Applications. In addition, there were 7 tutorials and 14 workshops held on the first 2 days, perhaps based on the premise that an attendee would either be a newbie or an expert, so you would find something to occupy your day. You could do a maximum of 3 tutorials (0.5 day per tutorial) or 2 workshops (1 day per workshop) if you attended the first 2 days.

There were also tons of poster sessions throughout the three days of the conference, and some of the ideas in these posters were really cool. One thing I found a bit annoying was that the posters would be up for a limited time and they would get changed after each session. This meant that either you miss a few talks if you wanted to do justice to the posters, or try to take in as many posters as you can during the coffee and lunch breaks. I chose to do the latter, except one time when a speaker failed to show up.

What follows is a brief description of the talks I attended, probably falls into the TL;DR category unless you want my personal take on the talks. Links to all papers presented at EMNLP can be found here (you might need ACL membership in the future, but they seem to be readily available now). In addition, the entire event was live streamed and the recordings are here. I am guessing that the recordings of the individual talks will eventually make it to a Youtube channel once the editing process is completed. I will update the post with the links once that happens. If you find the Youtube videos first, please let me know in the comments and I will update.

Tutorials and Workshops


Tutorial: Acquisition, Representation and Usage of Concept Hierarchies - by Marius Pesca (abstract)
A brief but very representative overview of techniques used to extract and represent entities in IS-A relationships, and various techniques for using these concepts in search applications. I could identify a few techniques I knew about, but there were quite a few I did not, so it was very useful for me.

Tutorial: Graph based text representations: Boosting text mining, NLP and information retrieval with graphs - by Fragkiskos D Malliaros and Michalis Vazirgiannis (abstract)
Very comprehensive coverage of graph techniques for NLP, using graph of words for information retrieval, text summarization using k-core decomposition, using graph based document representations for clustering, subgraph extraction and frequent subgraph mining techniques. Again, the benefit to me was the breadth of coverage.

Tutorial: Memory Augmented Neural Networks (MANN) for Natural Language Processing - by Caglar Gulcehre and Sarath Chandar (abstract)
Despite the success of LSTMs for solving NLP problems, there are still some complex tasks that need the ability to store and retrieve information on demand from an external store because they need to look at information that is too far in the past (or future) for an LSTM's hidden vector to provide. The resulting architecture is the Neural Turing Machine (NTM), and this tutorial discusses NTMs in quite a bit of depth.

Workshop: evaluating vector space representations in NLP
I attended part of this on the second day, highlights of the workshop for me were the talks by Yejin Choi from University of Washington, Jacob Uszkoreit from Google and Kyunghyn Cho (of GRU fame) of New York University. Yejin spoke about the need for extracting tactile information from the physical world and using it in reasoning. Jacob talked at length about the Transformer Architecture in connection with Machine Translation (and Language Understanding), and Cho spoke about using character models.

Conference Day #1


Keynote: Physical Simulation, Learning and Language - by Nando de Freitas
Nando de Freitas spoke about the need to build systems that can learn to learn from the environment like a general AI, and described a framework that allows researchers to simulate a physical world at faster than real time, that has led to many improvements in robotics. He argued for the need for something similar in the area of language research.

Monolingual Phrase Alignment on Parse Forests - by Yuki Arase and Jun'ichi Tsuji
Presenter described a tree-based method to detect and align phrases using paraphrase statements. In the process they have developed a gold dataset of parse trees and phrase alignments that they offer to fellow researchers.

Heterogeneous Supervision for Relation Extraction: A representation learning approach - by Liyuan Liu, Xiang Ren, Qi Zhu, Shi Zhi, Huan Gui, Heng Ji and Jiawei Han.
Presenter described a method to learn to learn relation extraction using domain heuristics and knowledge bases. The resulting learning is quite noisy, which are resolved using reliability ranking of sources and context embeddings much like word disambiguation using word vectors.

Mimicking word embeddings using subword RNNs - by Yuval Pinter, Robert Guthrie, Jacob Eisenstein
Presenter described results from their system MIMICK against other subword embedding systems such as Char2Tag. MIMICK can generate subword embeddings for Out of Vocabulary (OOV) words, using subword embeddings, much like word vectors are used to generate sentence vectors using the BiLSTM approach. Code for MIMICK can be found at the link.

Entity Linking for Queries by Searching Wikipedia Sentences - Chuanqui Tan, Furu Wei, Pengie Ren, Weifeng Lo and Ming Zhu
Extracting entities from queries can make disambiguation easier. System uses a search index to retrieve sentences containing the query terms and does entity extraction on the resulting sentences to find entities in the query. For word disambiguation, the presenters used the system supWSD (supWSD code), which is a supervised WSD system, and provides a toolkit and trained models.

End to end neural coreference resolution - by Kenton Lee, Luheng He, and Luke Zettlemoyer
Presenter describes an end-to-end system (e2e-coref) similar to Question Answering (QA) systems, where a document is broken up into spans using standard parsing techniques. All spans are treated as mention spans and a network used to detect similar mentions and cluster them. Code for the e2e-coref system can be found at this link.

Neural Machine Translation with word prediction - by Rongxiang Weng, Shujian Huang, Zaixiang Zheng, Xin-Yu Dai, and Jiajun Chen
The presenter suggests a change to the standard seq2seq model used for machine translation, to also include all previous predictions at each stage in the decoder sequence, and use the top K words as the vocabulary. They have found that it improves translation performance.

Affinity preserving random walk for multi-document summarization - by Kexiang Wang, Tianyu Liu, Zhifung Sui, and Baobao Chang
Output of MDS is a short text that summarizes all the documents in the MD collection. Presenter describes a graph based method that collects the entities from all documents in the collection, and then executes a random walk similar to Pagerank. Once the process converges, the important entities of the graph can be converted to the MDS.

Google's multilingual Neural Machine Translation System: Enabling Zero Shot Translation - by Melvin Johnson, Mike Schuster, Quoc V Le, Maxim Krikun, Yanghui Wu, Zhifeng Chen, Nikhil Thorat, Fernanda Viegas, Martin Wattenberg, Greg Corrado, Macduff Hughes, and Jeffrey Dean
Google's NMT model is well known. Presenter describes results of various experiments, including creating a combined multi-language model, creating languages for CJK and European languages and how they perform among different groups of languages. Turns out that multi-language NMT results in higher performance, also NMT trained on one language family is more effective (for certain language families) on their own family than on others.

DeepPath: A reinforcement learning method for knowledge graph reasoning - by Wenhan Xiong, Thien Hoang, and William Yang Wang
Presenter describes their DeepPath system, which uses Reinforcement Learning (RL) and Knowledge Graph embeddings to learn to find the most promising relation in a KG to extend the path. Code for DeepPath is available here.

Task Oriented Query Reformulation with Reinforcement Learning - by Rodrigo Nogueira and Kyunghyun Cho
Presenter describes a RL based Neural Network (NN) that reformulates complex user queries to maximize the number of relevant documents returned. The reward function used is the document recall. Code for the Query Reformulator is available here.

Sentence Simplification with Deep Reinforcement Learning - by Xingxing Zhang and Mirella Lapato
Presenter describes a RL based DL system for sentence simplification system called DRESS (Deep REinforcement Sentence Simplification). Reward function used is the SARI metric which rewards similarity, simplicity and correct grammar. Code for DRESS is available here.

Learning how to active learn: A Deep Reinforcement Learning Approach - by Meng Fang, Yuan Li and Trevor Cohn.
Presenter describes their system which uses RL to learn a policy to do Named Entity Recognition (NER) in one language, and apply the same policy to do NER in another language. The policy learned is based on labeling functions developed against a small dataset in the original language. Code for the RL system is here.

Conference Day #2


Keynote: Towards more universal language technology: unsupervised learning from speech - by Sharon Goldwater
Sharon makes a case for unsupervised and semi-supervised learning and describes her work on unsupervised learning in the area of speech. Results are not very good but the task is very hard. Some of her ideas may be directly transferable to language, but she makes the case that the NLP community should also invest effort in unsupervised techniques going forward.

A structured learning approach to temporal relation extraction - by Qiang Ning, Zhili Feng and Dan Roth.
Presenter describes the difficulty with manually annotating temporal relations in text, and proposes a graph based approach with verbs connected by candidate temporal relation edges, computing pairwise KL divergence between the nodes and comparing to KL divergence between two entities with uniform distribution.

Importance sampling for unbiased on-demand evaluation of knowledge base population - by Arun Chaganty, Ashwin Paranjpe, Percy Liang and Christopher D Manning
Presenter discusses how NER system evaluation is inherently biased in that it penalizes new findings from new NER systems. He proposes a way to sample from the predictions of the new NER system and verify that these findings are valid using crowdsourcing. Resulting approach is cheaper than naive crowdsourcing and removes bias in evaluation. Project code is here, and here is the Online Demo.

PACRR: A position aware neural IR model for relevance matching - by Kai Hui, Andrew Yates, Klaus Berberich, and Gerard de Melo.
Presenter describes a NN based model that mimicks the relevance formula in a search engine. Since the input embeddings are word vector based, the intuition is that the resulting model will be better at capturing semantic similarity. Good results are already available for unigram matching, this work explores the effect of position of context words on relevance matching. Code for PACRR is here.

Globally Normalized Reader - by Jonathan Raiman and John Miller.
Presenter describes their GNR system that does QA using iterative search instead of typical bidirectional attention mechanism. Results are back propagated through beam search, and is found to produce better results against the SQUAD dataset. The team has also used a novel data augmentation method for their training, and they offer the dataset as well to interested researchers. Code for the Globally Normalized Reader can be found here.

Encoding sentences for graph convolutional networks for semantic role labeling - by Diego Marcheggiani and Ivan Titov.
Presenter describes a Graph Convolutional Network (GCN) for modeling syntax dependency graphs, and their use as sentence encoders for Semantic Role Labeling (SRL) applications. They note that GCNs are complementary to LSTMs, and stacking them together results in improved results in identifying predicate-argument structures in a sentence, compared to the previous state of the art LSTM-based SRL model. Code for the NN based SRL system is here.

Neural Semantic Parsing with Type Constraints for Semi-structured tables - by Jayant Krishnamurthy, Pradeep Dasigi and Matt Gardner.
Presenter describes their model which learns how to answer compositional questions on semi-structured Wikipedia tables. Input is the natural language question and output is a well-typed logical form for navigating and looking up the answer. Dataset used is the Wikitable Questions.

Joint Concept Learning and Semantic Parsing from Natural Language Explanations - by Shashank Srivastava, Igor Labutov, and Tom Mitchell.
Presenter describes their system that certain features of text explanations to identify concepts. For example, the presence of "bank account number" in an explanation about phishing. Label functions are generated from these texts and used to identify a concept.

Opinion Recommendation using a Neural Model - by Zhongquing Wan and Yue Zhang.
Presenter describes their system that jointly generates a custom review score and a review for a given user, given his other reviews and scores. Task is novel, hence a new name Opinion Recommendation. Inputs are 3 NNs which model the reviews about the product, the user, and the user neighborhood (other users). These are concatenated using multi-hop attention (which seems to be iterative dot products) and form the input to another NN that outputs the score and the generated review using a standard encoder-decoder architecture.

Accurate Supervised and Semi-supervised machine reading for long documents - by Daniel Hewlett, Llion Jones and Alexandre Lacoste.
Presenter describes a standard QA network, the novel bit is that documents are split into equal sized parts (best results found with chunk size of 30 words) and encoded using RNNs in parallel. The network then attends over these separate encodings and reduces them to a single encoding, which is then decoded into an answer using a sequence decoder.

Adversarial Examples for Evaluating Reading Comprehension Systems - Robin Jia and Percy Liang.
Presenter describes how adding extra information to documents in a QA scenario can lead to a QA system giving the wrong answer. This is similar to the adversarial examples used in vision. They then propose an evaluation scheme for QA systems using this idea to measure if the QA system is demonstrating true language understanding versus just learning how to do pattern matching.

Joint modeling of Topics, Citations and Topical Authority in Academic Corpora - by Jooyeon Kim, Dongwoo Kim and Alice Oh.
Presenter introduces Latent Topical Authority Indexing (LTAI) which they show is a better way to expose topic signals from papers and authors than current techniques. LTAI can be used to find an expert on a topic, compare topical authority among multiple authors. The model used is a Programmable Graphical Model (PGM) which uses Expectation Maximization (EM) to compute the LTAI metric.

Identifying semantic intentions from revisions in wikipedia - Diyi Yang, Aran Halfaker, Rober Kraut, and Eduard Hovy.
Presenter talks about a 13 category taxonomy of semantic intention behind Wikipedia edits, and describes a classifier that can predict the intention given the user's edit history. This also opens up avenues for research into behavior of Wikipedia editors.

Conference Day #3


Keynote: Processing the language of policing for Improving Police-Community Relations. - by Dan Jurafsky
Dan Jurafsky speaks about his recent research into how the language policemen use exhibit a racial bias. Data for the research comes from 1 month of video footage from body cameras worn by Oakland PD officers. He also gave a brief update on his ongoing research into food and sociology. The theme of the talk was the need for NLP to do cross-disciplinary research so it can have a greater impact.

Part of Speech tagging for Twitter with Adversarial Neural Networks - by Tao Gui, Qi Zhang, Haoran Huang, Minlong Peng and Xuanjiang Huang
Presenter describes how combining POS tags from a high resource corpus such as WSJ, as well as character embeddings from both WSJ and Twitter, enables learning of POS tags on Twitter using an adversarial discriminator setup.

Learning Generic Sentence Representation using Convolutional Neural Networks - Zhe Gan, Yunchen Pu, Ricardo Henau, Chunyuan Li, Xiadong He, and Lawrence Carin
Presenter proposes a new encoder-decoder approach to learn distributed sentence/paragraph representations using a CNN-LSTM or hierarchical CNN-LSTM network instead of using LSTMs for both encoder and decoder as is done currently. He presents empirical evidence showing that performance is as good or better than using LSTM for both encoder and decoder.

Conversation Modeling on Reddit using a Graph Structured LSTM - by Victoria Zayats and Mari Ostendorf
Presenter describes her project to capture keywords/topics for popular vs unpopular Reddit comments (objective is to find what makes some comments popular vs not popular for a given subreddit). Since Reddit comments are hierarchical, a Graph LSTM is used, which builds the hidden component of the input from both the parent comment as well as the previous comment. Learned a nice method of quantization by selecting the median of each quantile of the score distribution as the threshold.

Learning what to read: Focused Machine Reading - by Enrique Noriega-Atala, Marco A Valenzuela-Escdrcega, Clayton Morrison, and Mihai Surdeanu
Presenter describes project to capture statements of the form "A related-to B given context C" on the Pubmed OpenAccess (OA) dataset. A pair of entities are chosen and queries fired against the corpus to find all possible entity pairs. RL is used to score the best path between the two specified entities, results in approximately 40% of path lookups compared to exhaustive search.

DOC: Deep Open Classification of text documents - by Lei Shu, Hu Xu, and Bing Liu
This talk is unique in that it makes the open world assumption, instead of a document being classified into 1 of N classes, the document can also be not one of the N classes, as well as belong to more than one of N classes. Approach is to create one-vs-rest classifiers for each class, and then softmax across their scores to find the classes. Thresholding to detect the class(es) to assign to each document involves fitting a gaussian to a histogram of scores for positive labels for each class, and then considering the mean + a multiple of the standard deviation as the threshold.

Exploiting Cross Sentence Context for Neural Machine Translation - by Longyue Wang, Zhaopeng Tu, Andy Way and Qun Liu
Presenter describes a novel idea of computing the context (3 previous sentences to current sentence being translated) and using it as additional input to the encoder, decoder, or even for attention during decoding. Experiments show that the additional context results in better scores on their test data. Code for the project is available here.

Cross Lingual Transfer learning for POS Tagging without cross lingual resources - by Joo-Kiyung Kim, Young-Bum Kim, Ruhi Sarikaya, and Eric Fosler-Lussier
Yet another example of adversarial learning in the NLP space, where the POS tags for the resource rich language are used to train a discriminator which is then used to train a generator to generate POS tags for the resource poor language. Code for the tagger is available here.

A Simple Regularization based Algorithm for learning Cross-Domain Word Embeddings - by Wei Yang, Wei Lu and Vincent Zhang.
Presenter describes building a graph using entities from a given domain as the nodes, and the edges weighted using the cosine distance between their vector representations. Then an iterative algorithm such as Pagerank is run until convergence. Cross domain word embeddings are learned by running analogies between selected words in one domain and single words in the other.

Best Paper: Bringing Structure into Summaries: Crowdsourcing a Benchmark Corpus of Concept Maps - by Tobias Falke and Iryna Gurevych.
Presenter describes a system that extracts entities from one or more documents, sets them up in a graph based on cosine distance between their word vectors, and finds the most important entities. These entities are then sent to human experts in a crowdsourcing arrangement who construct the summaries manually.

The other 3 papers in the best paper category were around the language learned when two automated agents engage in dialog, predicting depression and suicide risk in online forums, and how to correct for dataset bias for machine learning models.

Conclusion


Presentations were predominantly from academia, which is kind of expected, since most of the papers tend to push the envelope of the state of the art, something academia tends to do. Among US universities, Stanford and Carnegie Mellon are well known for their NLP, so as expected, there were quite a few presentations from there. University of Washington also had quite a few good submissions. I also saw a lot of presentations from Chinese universities, looks like NLP and Deep Learning are quite popular in China. From industry, I saw two presentations from Google and one from Baidu.

That's pretty much all I have for this week. I made a few awesome friends, thanks to an introduction from a colleague, with some other attendees who were local to Copenhagen. Thanks to their help, I got to eat authentic Italian pizza and spicy Indian food in Copenhagen at an area right next to the conference, but which I am pretty sure I wouldn't have found on my own :-).