Building an ML System for Continual Learning

In setting out to build Salient we unwittingly assigned ourselves a rather challenging task: designing a system that allows non-technical users to use machine learning to automate simple business processes (related to documents) without requiring them to understand anything about machine learning or even programming. Our hypothesis:

Many (most?) tasks and challenges faced by business users are specific to their organization or their set of documents so they can’t be addressed by simple pre-built and pre-packaged machine learning models.

Rather we wanted to build a system that continuously learns from the users, their documents, and their tasks.  Even tasks that are amenable to using pre-trained models will generally benefit from being tweaked by end users: nothing is more infuriating than an automated system that can’t be fixed or corrected!

Of course “users” here could be regular business users or it could be IT engineers training and integrating Salient into their infrastructure. In either case, the goal is for Salient to provide flexible, organization-specific machine learning without requiring any intervention from us (its developers) or even data scientists.

The Challenge(s)

If you start thinking about how to do this you’ll realize the challenges involved are significant:

  1. Normal users or even IT admins are not data scientists or ML experts so Salient has to be able to manage the plethora of choices and steps required in building a model without user intervention.
  2. In particular users don’t want to spend a large amount of time labeling documents or generating training data so the process of training the system has to be fast, smooth and feel like a natural part of their workflow. Most importantly users have to quickly see good results otherwise they will not feel motivated to continue using the system.
  3. We don’t know beforehand (or ever) what the users’ documents will look like so Salient has to be able to support a wide range of document formats, languages and also domain-specific terminology and vocabulary.
  4. Each client’s task is unique and is not known to us beforehand. The primary use case for Salient is extracting information from or labeling documents but these tasks span a wide range of cases:
    • extract specific words or phrases from a sentence based on the meaning of the text
    • extract fields from a form based on the visual information (layout of the document)
    • label selections of text based on the type of section it is (e.g. clauses in a contract)

In each case we want the system to support a large amount of variability in the input and learn very quickly to generalize to similar documents.

Because of regulatory or security concerns many clients want to run Salient on premise so all the machine learning and other components of the system have to run in a relatively hardware-constrained environment (private corporate clouds are usually expensive) and so be very efficient. In particular, we can’t depend on the presence of GPUs or easily accessible computing power. Our target is to have a single CPU core be able to provide real-time interactive training and inference for a user.

Solving the challenges above has been a very enlightening journey, fraught with painful lessons. In this article I’m not going to dive very deeply into any given problem but rather will focus on the overall architecture we developed to address these problems. Hopefully, I’ll have time later to dig into individual problems and explain some of the interesting things we learned in solving them.

Architecture

This is the architecture for the ML part of Salient (there are several other components involved with document and knowledge management that are not covered here):

Salient Machine Learning Architecture

Below I’ll explain the components of the architecture and how they help address the problems above. Hopefully, there’s something in here for you to take away in building your own ML system.

Interface

The elaborate architecture above is invisible to the user or even admin of the system. Instead the user interacts naturally with documents in a nice “smart reader” interface that lets them view, search and extract information from documents:

Interactive annotation of a document in Salient UI using on-line learning.

They select text from the document and assign it to fields in a “form” that constitutes the “structured” version of the document (note that both the fields and form are defined by the user — Salient can be taught to extract any kind of data the user wants to extract).

As they do this Salient trains itself automatically in the background, testing and selecting the best models to match the user’s task. When users open a new document Salient can auto-populate the form so the user can evaluate how well the extraction is working and improve it. This interactive process is called “online learning” because the system learns in real-time from user interactions.  The ability to quickly see and correct what Salient is learning greatly speeds up the workflow.

Document Ingestion & Processing

This process warrants a whole article on its own but its largely outside the scope of the current discussion. Suffice it to say that document processing can be expensive. Salient reads documents in a range of format, including scanned images that it OCRs, and then converts them to a standardized format that can be rendered in the interactive browser-based view shown above. Salient doesn’t just extract the text from the document but it also tracks layout information as this is an important feature for the ML extraction models. The text of the document is then enriched with the output of a full NLP pipeline (entities, parts-of-speech, etc..). This enriched version of the document is stored in a series of data stores (mongo db, minio, & elasticsearch) so that it can be indexed and used later on.

Model Infrastructure

The machine learning pipeline in Salient runs without user intervention (though users can tweak it if desired). Everything from building unsupervised models and generating features to training and selecting models runs in an automated, distributed pipeline driven by changes of state to the training data (generated by the user) and the document set. This presents some interesting challenges discussed below.

Feature Generation & Caching

Salient makes very heavy use of unsupervised learning. Since our goal is to let users train the system very quickly and efficiently, the more work we can do to help them up-front, the better. To that end, Salient builds a range of unsupervised models (variants of word2vec and our own specialized embedding models) to capture statistical properties of the text, the layout, the entities in the documents, etc.. These features, along with other data about the documents, change quite frequently: the unsupervised models are retrained automatically as more data is added or the data distribution changes and features for new documents are generated as documents are inserted or modified, etc.

All this is computationally expensive so we want to cache the results in a way that can be quickly leveraged when we start to do supervised learning. To that end, we have developed a smart “Corpus Features” data service, built on mongo and minio, that tracks the state of the document corpus, the features for each document and automatically manages rebuilding unsupervised models as needed. We use mongo because it is very flexible (supporting the dynamical needs of such a system) and fast to write and read from and we use minio as blob storage for the models themselves.

Distributing Models

Salient is designed around a distributed stateless worker-based architecture so systems like “Corpus Features” (which can be embedded in any worker) have to be able to intelligently update any worker if e.g. a model changes. To this end all models (supervised and unsupervised) in Salient are tagged with unique ids and a centralized caching system (redis) is used to track the newest version of a model. If one worker updates a model the other workers detect this change and update their local copy of the model to the newest version. This is particularly important for supervised models because a user interacting with the system will generally be hitting several workers (possibly on different servers) so they must have a synchronized state.

Training

Training in Salient can be triggered by a range of events. Models retrain while users are interacting with the system so that users get immediate feedback on what the models have learned. This happens in dedicated background workers so as to not interfere with the user’s workflow but of course any model changes have to be propagated back to the real-time ML inference workers. This is managed by tracking the latest version of each model in a distributed cache and having all workers reload any stale models automatically.

Model retraining can also be triggered by non-user events. For instance, importing a large amounts of new documents can trigger unsupervised models to retrain (to capture the new data distribution) and this will also trigger the supervised models that use them to retrain. This chain of dependencies is managed by generating unique identifiers (UUIDs) on each model training and storing this in any dependent model so we can easily track dependency chains.

Model Selection

For every kind of task (labeling a document, extracting specific text or table entries, etc) Salient has a range of models that are sensitive to different types of features (semantic, structural, visual, local, etc..) and that also have different predictive power.  When users have less training data simpler models are favored so they can be retrained faster and be less prone to overfitting.

The selection of features, architecture and training parameters for a model is made by testing many possibilities against user generated data (as part of the background training process) and then selecting the best model based on a “validation set”.  This is a (random) subset of the training data that is hidden from the models during training and then used after training to evaluate the performance of each model variant.  Not only does this let Salient select the best combination of model, features and parameters but it also provides some indication of how well the model will perform on unseen data.  Ultimately Salient selects the best few models for each task and averages their results in an “ensemble”.

All this information about how models have been trained and selected is stored in a training database so that admins can evaluate and understand which models are being used.

Some Technicalities

The discussion and the architecture diagram above cover the conceptual components  of the system but not the detailed service or technical architecture.  That might be subject a separate post but, in brief, Salient (and the diagram above) is implemented as a distributed job queue with both real-time and batch workers running various stateless mircro-services.  This architecture runs in docker-compose or kubernetes but has no other dependencies so it can be deployed in any environment (on the cloud, on-premise).  It is, by design, horizontally scalable and fault tolerant.

If you’re interested in learning more about Salient or have some thoughts or questions about the architecture above please don’t hesitate to get in touch!

 

 

Enemy of the State

Nowadays, I spend a lot of time thinking about system design and architecture. I spoke last year at PyParis about the lessons we learned building Salient and how to get some control of a large and complex system.

Of course,  a system like Salient is always evolving,  usually as a function of requirements and customer feedback (someone once used the analogy of “changing the engine of an airplane in mid-flight”).  In this post however I’m going to focus on a different kind of insight or requirement, one that doesn’t come directly from the customer but rather, indirectly, by challenging our own understanding of software and how it should be designed and managed.

As a former theoretical physicist I’m very familiar with the idea that abstract thinking, and particularly the right abstractions, can have a huge impact in solving practical problems.  In my own career I witnessed how, by recasting and reformulating the same problem with new and better abstractions we were able to achieve hundred-fold performance and accuracy improvements more than once.

So I was very pleasantly surprised when I discovered a paper espousing a similar powerful set of abstractions in the much more general setting of software design.  I learned about “Out of the Tar Pit” in this very beautiful talk by Rich Hickey (which warrants an entire blog post on its own) and have since been slowly digesting it and working through its implications for our software.

State and Control

The central point of the paper is that much of the complexity of large software systems is potentially avoidable (at least it is not theoretically essential) and has its origins in appropriate handling of state and control.

While the problem of state is something many of us have thought a lot about, I was less familiar with the notion of control and particularly that it might not be essential.

Basically software is generally defined in terms of a series of operations that happen in a certain order to generate a result.   The examples they give are very illustrative:

a = b + 3
c = d + 2
e = f/4

While the above lines might appear in a body of code its very clear that we are enforcing an order on them unnaturally.  I’m so used to this that it did not occur to me that this is really an artifact of the implementation rather than an essential feature of the problem.

Programming paradigms like declarative programming challenge this.  When we write an SQL statement or specify a pod spec in Kubernetes we are not specifying a set of operations but rather the desired business logic.  This cleanly separates out the logical constraints (e.g. relationships in a data model) or system specification from the flow of control required to achieve this (which is is generally not at all unique).  Think of the distinction between simply declaring that a field is a Foreign Key versus the code required to enforce this.  When thought of in these terms its rather shocking that we systematically confound these two aspects of system design in standard software development.

Accidental and Essential

The second dimension used in their deconstruction of the software development process is the distinction between essential and accidental complexity.  Essential complexity is, in their language, complexity that is innate to the specification of the problem.  This is to be distinguished from accidental complexity which emerges by thinking about the problem in terms of a specific implementation or paradigm.

In some sense this leads us to a very user-centric view where only user-specified aspects of the problem become truly essential.  For instance nothing about the choice of programming language, database, operating system, hardware, caching mechanism, etc. can be characterized as essential.  All these are subject to change and critical review.

By imagining a fictitious ideal world with no resource constraints they arrive at the following perhaps surprising observations:

  1. The only essential state in any system is the state provided as inputs by the users (and only if the requirements imply that this state must be available later on).
  2. There is no essential control in the system.  All control is a source of accidental complexity.  This is essentially tantamount to the statement that the entire system can be specified in declarative terms (users don’t care how you enforce the business rules).

Reflecting on the above, we are forced into an embarrassing realization.  Very little of the state we usually associate with a system (the database, the caches, status of various parts of the system, etc) are user-specified.  They are almost all implementation details and hence a source of “accidental” rather than “essential” complexity.  You might object that without those things the system can not reasonably be imagined to function but the important thing here is not to ignore the presence of such accidental complexity but rather to carefully distinguish essential from accidental complexity and to make this distinction the overriding principle in designing the system.

So far I’ve only attempted to heavily paraphrase some parts of the problem statement of the paper.  The ideas in this paper, and their implication for our own (as well as others’) software design can easily fuel several blog posts.  But before stopping I want to spend a moment making the above discussion more concrete, lest the reader be left with the impression that this is a purely academic exercise.

In a complex system like Salient we have a large amount of both state and control.  Documents are uploaded into the system, users annotate and interact with them, machine learning systems analyze them extracting entities, labeling types of sentences, users train the machine learning systems both directly and indirectly, etc.  These interactions are all orchestrated by processes invoked directly by users or by background tasks or even chains of tasks.  The flow of data and control logic spans multiple software components and generally runs in a distributed system composed of several physical servers.

At first glance this all sounds like an essential aspect of a system of this scale and complexity (and part of what makes it non-trivial to manage).  But by stepping back and asking ourselves some simple questions we can unravel a lot of this complexity (with the goal of eventually putting it back together in a much smarter way).

  1. What is the absolute minimum amount of data required to rebuild the system from scratch?  Thinking about this question helps a lot: it turns out that the answer to this question corresponds to a very small subset of the data actually stored and used in the system.  The rest is really “accidental state”.
  2. What drives the flow of information and processes in the system and is it canonical (i.e. the only way to do it) or just accidental?  Can we move away from user or agent driven processes and towards a more declarative structure, where the software robustly tries to achieve a certain state derived from the above minimal state and a set of business rules?

Thinking about Salient in these terms has helped drive some very nice design decisions on our part.

For instance an object-oriented way of thinking (something criticized heavily in the paper) would encourage us to encapsulate all data related to a document in one place, both the data uploaded by the user (the original document and annotations about it) as well as a huge amount of derived data (various processing and machine learning outputs, etc).  This tends to lead to a rather complex notion of state where essential state information about a document might be distributed over many data stores (for performance and other reasons) leading to a complex system of synchronization.  This is a good example of accidental complexity that feeds not only into the software but also into infrastructure and even system management processes.  Rethinking this with an eye towards accidental versus essential state lets us design a much cleaner version of the system.

Even in aspects of the system that have been built with very careful separations of concerns we are finding that using the above language helps us clarify and refine the design, mitigating potential flaws down the road.

In follow up blog posts I hope to dig more into this paper (and related ideas that we’ve been exploring at Lore) and also more specific examples of design patterns it has inspired.

Building a high-performance, scalable ML & NLP platform with Python

I just had the opportunity to share some of our experiences building our machine learning and NLP stack at PyParis 2017 today.  I feel like we’ve come a long way and often this involved learning things the hard way so I tried to share the lessons we learned in this talk.  I hope there’s something in here that might be useful for small startups trying to balance complex and changing business requirements with interesting and not entirely standard technical problems.  If you have any thoughts, suggestions or improvements please drop us a line!

Once the recording of the talk is available from PyParis I’ll post a link here.

PyParis2017_talk