Package: ai-serving-server
This README.md is a mirror for PyPI. Please visithttps://github.com/hanxiao/bert-as-service/blob/master/README.mdfor the latest README.md.Are you looking for X-as-service? TryJina!where X can be albert, pytorch-transformer, vgg, resnet, videobert, orANYdeep learning representation model?► Jina 101: First Thing to Learn About JinaEnglish•日本語•français•Deutsch•Русский язык•中文► From BERT-as-Service to X-as-ServiceLearn how to use Jina to extract feature vector using any deep learning representationbert-as-serviceUsing BERT model as a sentence encoding service, i.e. mapping a variable-length sentence to a fixed-length vector.Highlights•What is it•Install•Getting Started•API•Tutorials•FAQ•Benchmark•BlogMade by Han Xiao • :globe_with_meridians:https://hanxiao.github.ioWhat is itBERTis a NLP modeldeveloped by Googlefor pre-training language representations. It leverages an enormous amount of plain text data publicly available on the web and is trained in an unsupervised manner. Pre-training a BERT model is a fairly expensive yet one-time procedure for each language. Fortunately, Google released several pre-trained models whereyou can download from here.Sentence Encoding/Embeddingis a upstream task required in many NLP applications, e.g. sentiment analysis, text classification. The goal is to represent a variable length sentence into a fixed length vector, e.g.hello worldto[0.1, 0.3, 0.9]. Each element of the vector should "encode" some semantics of the original sentence.Finally,bert-as-serviceuses BERT as a sentence encoder and hosts it as a service via ZeroMQ, allowing you to map sentences into fixed-length representations in just two lines of code.Highlights:telescope:State-of-the-art: build on pretrained 12/24-layer BERT models released by Google AI, which is considered as a milestone in the NLP community.:hatching_chick:Easy-to-use: require only two lines of code to get sentence/token-level encodes.:zap:Fast: 900 sentences/s on a single Tesla M40 24GB. Low latency, optimized for speed. Seebenchmark.:octopus:Scalable: scale nicely and smoothly on multiple GPUs and multiple clients without worrying about concurrency. Seebenchmark.:gem:Reliable: tested on multi-billion sentences; days of running without a break or OOM or any nasty exceptions.More features:XLA & FP16 support; mix GPU-CPU workloads; optimized graph;tf.datafriendly; customized tokenizer; flexible pooling strategy;build-in HTTP serverand dashboard;async encoding;multicasting; etc.InstallInstall the server and client viapip. They can be installed separately or even ondifferentmachines:pipinstallbert-serving-server# serverpipinstallbert-serving-client# client, independent of `bert-serving-server`Note that the server MUST be running onPython >= 3.5withTensorflow >= 1.10(one-point-ten). Again, the server does not support Python 2!:point_up: The client can be running on both Python 2 and 3for the following consideration.Getting Started1. Download a Pre-trained BERT ModelDownload a model listed below, then uncompress the zip file into some folder, say/tmp/english_L-12_H-768_A-12/List of released pretrained BERT models (click to expand...)BERT-Base, Uncased12-layer, 768-hidden, 12-heads, 110M parametersBERT-Large, Uncased24-layer, 1024-hidden, 16-heads, 340M parametersBERT-Base, Cased12-layer, 768-hidden, 12-heads , 110M parametersBERT-Large, Cased24-layer, 1024-hidden, 16-heads, 340M parametersBERT-Base, Multilingual Cased (New)104 languages, 12-layer, 768-hidden, 12-heads, 110M parametersBERT-Base, Multilingual Cased (Old)102 languages, 12-layer, 768-hidden, 12-heads, 110M parametersBERT-Base, ChineseChinese Simplified and Traditional, 12-layer, 768-hidden, 12-heads, 110M parametersOptional:fine-tuning the model on your downstream task.Why is it optional?2. Start the BERT serviceAfter installing the server, you should be able to usebert-serving-startCLI as follows:bert-serving-start-model_dir/tmp/english_L-12_H-768_A-12/-num_worker=4This will start a service with four workers, meaning that it can handle up to fourconcurrentrequests. More concurrent requests will be queued in a load balancer. Details can be found in ourFAQandthe benchmark on number of clients.Below shows what the server looks like when starting correctly:Alternatively, one can start the BERT Service in a Docker Container (click to expand...)dockerbuild-tbert-as-service-f./docker/Dockerfile.NUM_WORKER=1PATH_MODEL=/PATH_TO/_YOUR_MODEL/
dockerrun--runtimenvidia-dit-p5555:5555-p5556:5556-v$PATH_MODEL:/model-tbert-as-service$NUM_WORKER3. Use Client to Get Sentence EncodesNow you can encode sentences simply as follows:frombert_serving.clientimportBertClientbc=BertClient()bc.encode(['First do it','then do it right','then do it better'])It will return andarray(orList[List[float]]if you wish), in which each row is a fixed-length vector representing a sentence. Having thousands of sentences? Justencode!Don't even bother to batch, the server will take care of it.As a feature of BERT, you may get encodes of a pair of sentences by concatenating them with|||(with whitespace before and after), e.g.bc.encode(['First do it ||| then do it right'])Below shows what the server looks like while encoding:Use BERT Service RemotelyOne may also start the service on one (GPU) machine and call it from another (CPU) machine as follows:# on another CPU machinefrombert_serving.clientimportBertClientbc=BertClient(ip='xx.xx.xx.xx')# ip address of the GPU machinebc.encode(['First do it','then do it right','then do it better'])Note that you only needpip install -U bert-serving-clientin this case, the server side is not required. You may alsocall the service via HTTP requests.:bulb:Want to learn more? Checkout our tutorials:Building a QA semantic search engine in 3 min.Serving a fine-tuned BERT modelGetting ELMo-like contextual word embeddingUsing your own tokenizerUsingBertClientwithtf.dataAPITraining a text classifier using BERT features and tf.estimator APISaving and loading with TFRecord dataAsynchronous encodingBroadcasting to multiple clientsMonitoring the service status in a dashboardUsingbert-as-serviceto serve HTTP requests in JSONStartingBertServerfrom PythonServer and Client API▴ Back to topThe best way to learnbert-as-servicelatest APIisreading the documentation.Server APIPlease always refer to the latest server-side API documented here., you may get the latest usage via:bert-serving-start--help
bert-serving-terminate--help
bert-serving-benchmark--helpArgumentTypeDefaultDescriptionmodel_dirstrRequiredfolder path of the pre-trained BERT model.tuned_model_dirstr(Optional)folder path of a fine-tuned BERT model.ckpt_namestrbert_model.ckptfilename of the checkpoint file.config_namestrbert_config.jsonfilename of the JSON config file for BERT model.graph_tmp_dirstrNonepath to graph temp filemax_seq_lenint25maximum length of sequence, longer sequence will be trimmed on the right side. Set it to NONE for dynamically using the longest sequence in a (mini)batch.cased_tokenizationboolFalseWhether tokenizer should skip the default lowercasing and accent removal. Should be used for e.g. the multilingual cased pretrained BERT model.mask_cls_sepboolFalsemasking the embedding on [CLS] and [SEP] with zero.num_workerint1number of (GPU/CPU) worker runs BERT model, each works in a separate process.max_batch_sizeint256maximum number of sequences handled by each worker, larger batch will be partitioned into small batches.priority_batch_sizeint16batch smaller than this size will be labeled as high priority, and jumps forward in the job queue to get result fasterportint5555port for pushing data from client to serverport_outint5556port for publishing results from server to clienthttp_portintNoneserver port for receiving HTTP requestscorsstr*setting "Access-Control-Allow-Origin" for HTTP requestspooling_strategystrREDUCE_MEANthe pooling strategy for generating encoding vectors, valid values areNONE,REDUCE_MEAN,REDUCE_MAX,REDUCE_MEAN_MAX,CLS_TOKEN,FIRST_TOKEN,SEP_TOKEN,LAST_TOKEN. Explanation of these strategiescan be found here. To get encoding for each token in the sequence, please set this toNONE.pooling_layerlist[-2]the encoding layer that pooling operates on, where-1means the last layer,-2means the second-to-last,[-1, -2]means concatenating the result of last two layers, etc.gpu_memory_fractionfloat0.5the fraction of the overall amount of memory that each GPU should be allocated per workercpuboolFalserun on CPU instead of GPUxlaboolFalseenableXLA compilerfor graph optimization (experimental!)fp16boolFalseuse float16 precision (experimental)device_maplist[]specify the list of GPU device ids that will be used (id starts from 0)show_tokens_to_clientboolFalsesending tokenization results to clientClient APIPlease always refer to the latest client-side API documented here.Client-side provides a Python class calledBertClient, which accepts arguments as follows:ArgumentTypeDefaultDescriptionipstrlocalhostIP address of the serverportint5555port for pushing data from client to server,must be consistent with the server side configport_outint5556port for publishing results from server to client,must be consistent with the server side configoutput_fmtstrndarraythe output format of the sentence encodes, either in numpy array or python List[List[float]] (ndarray/list)show_server_configboolFalsewhether to show server configs when first connectedcheck_versionboolTruewhether to force client and server to have the same versionidentitystrNonea UUID that identifies the client, useful in multi-castingtimeoutint-1set the timeout (milliseconds) for receive operation on the clientABertClientimplements the following methods and properties:MethodDescription.encode()Encode a list of strings to a list of vectors.encode_async()Asynchronous encode batches from a generator.fetch()Fetch all encoded vectors from server and return them in a generator, use it with.encode_async()or.encode(blocking=False). Sending order is NOT preserved..fetch_all()Fetch all encoded vectors from server and return them in a list, use it with.encode_async()or.encode(blocking=False). Sending order is preserved..close()Gracefully close the connection between the client and the server.statusGet the client status in JSON format.server_statusGet the server status in JSON format:book: Tutorial▴ Back to topThe full list of examples can be found inexample/. You can run each viapython example/example-k.py. Most of examples require you to start a BertServer first, please followthe instruction here. Note that althoughBertClientworks universally on both Python 2.x and 3.x, examples are only tested on Python 3.6.Table of contents (click to expand...)Building a QA semantic search engine in 3 min.Serving a fine-tuned BERT modelGetting ELMo-like contextual word embeddingUsing your own tokenizerUsingBertClientwithtf.dataAPITraining a text classifier using BERT features and tf.estimator APISaving and loading with TFRecord dataAsynchronous encodingBroadcasting to multiple clientsMonitoring the service status in a dashboardUsingbert-as-serviceto serve HTTP requests in JSONStartingBertServerfrom PythonBuilding a QA semantic search engine in 3 minutesThe complete example canbe found example8.py.As the first example, we will implement a simple QA search engine usingbert-as-servicein just three minutes. No kidding! The goal is to find similar questions to user's input and return the corresponding answer. To start, we need a list of question-answer pairs. Fortunately, this README file already containsa list of FAQ, so I will just use that to make this example perfectly self-contained. Let's first load all questions and show some statistics.prefix_q='##### **Q:** 'withopen('README.md')asfp:questions=[v.replace(prefix_q,'').strip()forvinfpifv.strip()andv.startswith(prefix_q)]print('%dquestions loaded, avg. len of%d'%(len(questions),np.mean([len(d.split())fordinquestions])))This gives33 questions loaded, avg. len of 9. So looks like we have enough questions. Now start a BertServer withuncased_L-12_H-768_A-12pretrained BERT model:bert-serving-start-num_worker=1-model_dir=/data/cips/data/lab/data/model/uncased_L-12_H-768_A-12Next, we need to encode our questions into vectors:bc=BertClient(port=4000,port_out=4001)doc_vecs=bc.encode(questions)Finally, we are ready to receive new query and perform a simple "fuzzy" search against the existing questions. To do that, every time a new query is coming, we encode it as a vector and compute its dot product withdoc_vecs; sort the result descendingly; and return the top-k similar questions as follows:whileTrue:query=input('your question: ')query_vec=bc.encode([query])[0]# compute normalized dot product as scorescore=np.sum(query_vec*doc_vecs,axis=1)/np.linalg.norm(doc_vecs,axis=1)topk_idx=np.argsort(score)[::-1][:topk]foridxintopk_idx:print('>%s\t%s'%(score[idx],questions[idx]))That's it! Now run the code and type your query, see how this search engine handles fuzzy match:Serving a fine-tuned BERT modelPretrained BERT models often show quite "okayish" performance on many tasks. However, to release the true power of BERT a fine-tuning on the downstream task (or on domain-specific data) is necessary. In this example, I will show you how to serve a fine-tuned BERT model.We follow the instruction in"Sentence (and sentence-pair) classification tasks"and userun_classifier.pyto fine tuneuncased_L-12_H-768_A-12model on MRPC task. The fine-tuned model is stored at/tmp/mrpc_output/, which can be changed by specifying--output_dirofrun_classifier.py.If you look into/tmp/mrpc_output/, it contains something like:checkpoint128eval4.0K
eval_results.txt86eval.tf_record219K
events.out.tfevents.1545202214.TENCENT64.site6.1M
events.out.tfevents.1545203242.TENCENT64.site14M
graph.pbtxt9.0M
model.ckpt-0.data-00000-of-000011.3G
model.ckpt-0.index23K
model.ckpt-0.meta3.9M
model.ckpt-343.data-00000-of-000011.3G
model.ckpt-343.index23K
model.ckpt-343.meta3.9M
train.tf_record2.0MDon't be afraid of those mysterious files, as the only important one to us ismodel.ckpt-343.data-00000-of-00001(looks like my training stops at the 343 step. One may getmodel.ckpt-123.data-00000-of-00001ormodel.ckpt-9876.data-00000-of-00001depending on the total training steps). Now we have collected all three pieces of information that are needed for serving this fine-tuned model:The pretrained model is downloaded to/path/to/bert/uncased_L-12_H-768_A-12Our fine-tuned model is stored at/tmp/mrpc_output/;Our fine-tuned model checkpoint is named asmodel.ckpt-343something something.Now start a BertServer by putting three pieces together:bert-serving-start-model_dir=/pretrained/uncased_L-12_H-768_A-12-tuned_model_dir=/tmp/mrpc_output/-ckpt_name=model.ckpt-343After the server started, you should find this line in the log:I:GRAPHOPT:[gra:opt: 50]:checkpoint (override by fine-tuned model): /tmp/mrpc_output/model.ckpt-343Which means the BERT parameters is overrode and successfully loaded from our fine-tuned/tmp/mrpc_output/model.ckpt-343. Done!In short, find your fine-tuned model path and checkpoint name, then feed them to-tuned_model_dirand-ckpt_name, respectively.Getting ELMo-like contextual word embeddingStart the server withpooling_strategyset to NONE.bert-serving-start-pooling_strategyNONE-model_dir/tmp/english_L-12_H-768_A-12/To get the word embedding corresponds to every token, you can simply use slice index as follows:# max_seq_len = 25# pooling_strategy = NONEbc=BertClient()vec=bc.encode(['hey you','whats up?'])vec# [2, 25, 768]vec[0]# [1, 25, 768], sentence embeddings for `hey you`vec[0][0]# [1, 1, 768], word embedding for `[CLS]`vec[0][1]# [1, 1, 768], word embedding for `hey`vec[0][2]# [1, 1, 768], word embedding for `you`vec[0][3]# [1, 1, 768], word embedding for `[SEP]`vec[0][4]# [1, 1, 768], word embedding for padding symbolvec[0][25]# error, out of index!Note that no matter how long your original sequence is, the service will always return a[max_seq_len, 768]matrix for every sequence. When using slice index to get the word embedding, beware of the special tokens padded to the sequence, i.e.[CLS],[SEP],0_PAD.Using your own tokenizerOften you want to use your own tokenizer to segment sentences instead of the default one from BERT. Simply callencode(is_tokenized=True)on the client slide as follows:texts=['hello world!','good day']# a naive whitespace tokenizertexts2=[s.split()forsintexts]vecs=bc.encode(texts2,is_tokenized=True)This gives[2, 25, 768]tensor where the first[1, 25, 768]corresponds to the token-level encoding of "hello world!". If you look into its values, you will find that only the first four elements, i.e.[1, 0:3, 768]have values, all the others are zeros. This is due to the fact that BERT considers "hello world!" as four tokens:[CLS]helloworld![SEP], the rest are padding symbols and are masked out before output.Note that there is no need to start a separate server for handling tokenized/untokenized sentences. The server can tell and handle both cases automatically.Sometimes you want to know explicitly the tokenization performed on the server side to have better understanding of the embedding result. One such case is asking word embedding from the server (with-pooling_strategy NONE), one wants to tell which word is tokenized and which is unrecognized. You can get such information with the following steps:enabling-show_tokens_to_clienton the server side;calling the server viaencode(..., show_tokens=True).For example, a basic usage likebc.encode(['hello world!','thisis it'],show_tokens=True)returns a tuple, where the first element is the embedding and the second is the tokenization result from the server:(array([[[ 0.        , -0.        ,  0.        , ...,  0.        , -0.        , -0.        ],
        [ 1.1100919 , -0.20474958,  0.9895898 , ...,  0.3873255  , -1.4093989 , -0.47620595],
        ..., -0.        , -0.        ]],

       [[ 0.        , -0.        ,  0.        , ...,  0.        , 0.        ,  0.        ],
        [ 0.6293478 , -0.4088499 ,  0.6022662 , ...,  0.41740108, 1.214456  ,  1.2532915 ],
        ..., 0.        ,  0.        ]]], dtype=float32),
         
          [['[CLS]', 'hello', 'world', '!', '[SEP]'], ['[CLS]', 'this', '##is', 'it', '[SEP]']])When using your own tokenization, you may still want to check if the server respects your tokens. For example,bc.encode([['hello','world!'],['thisis','it']],show_tokens=True,is_tokenized=True)returns:(array([[[ 0.        , -0.        ,  0.        , ...,  0.       ,  -0.        ,  0.        ],
        [ 1.1111546 , -0.56572634,  0.37183186, ...,  0.02397121,  -0.5445367 ,  1.1009651 ],
        ..., -0.        ,  0.        ]],

       [[ 0.        ,  0.        ,  0.        , ...,  0.        ,  -0.        ,  0.        ],
        [ 0.39262453,  0.3782491 ,  0.27096173, ...,  0.7122045 ,  -0.9874849 ,  0.9318679 ],
        ..., -0.        ,  0.        ]]], dtype=float32),
         
         [['[CLS]', 'hello', '[UNK]', '[SEP]'], ['[CLS]', '[UNK]', 'it', '[SEP]']])One can observe thatworld!andthisisare not recognized on the server, hence they are set to[UNK].Finally, beware that the pretrained BERT Chinese from Google is character-based, i.e. its vocabulary is made of single Chinese characters. Therefore it makes no sense if you use word-level segmentation algorithm to pre-process the data and feed to such model.Extremely curious readers may notice that the first row in the above example is all-zero even though the tokenization result includes[CLS](well done, detective!). The reason is that the tokenization result willalwaysincludes[CLS]and[UNK]regardless the setting of-mask_cls_sep. This could be useful when you want to align the tokens afterwards. Remember,-mask_cls_seponly masks[CLS]and[SEP]out of the computation. It doesn't affect the tokenization algorithm.UsingBertClientwithtf.dataAPIThe complete example canbe found example4.py. There is alsoan example in Keras.Thetf.dataAPI enables you to build complex input pipelines from simple, reusable pieces. One can also useBertClientto encode sentences on-the-fly and use the vectors in a downstream model. Here is an example:batch_size=256num_parallel_calls=4num_clients=num_parallel_calls*2# should be at least greater than `num_parallel_calls`# start a pool of clientsbc_clients=[BertClient(show_server_config=False)for_inrange(num_clients)]defget_encodes(x):# x is `batch_size` of lines, each of which is a json objectsamples=[json.loads(l)forlinx]text=[s['raw_text']forsinsamples]# List[List[str]]labels=[s['label']forsinsamples]# List[str]# get a client from available clientsbc_client=bc_clients.pop()features=bc_client.encode(text)# after use, put it backbc_clients.append(bc_client)returnfeatures,labelsds=(tf.data.TextLineDataset(train_fp).batch(batch_size).map(lambdax:tf.py_func(get_encodes,[x],[tf.float32,tf.string]),num_parallel_calls=num_parallel_calls).map(lambdax,y:{'feature':x,'label':y}).make_one_shot_iterator().get_next())The trick here is to start a pool ofBertClientand reuse them one by one. In this way, we can fully harness the power ofnum_parallel_callsofDataset.map()API.Training a text classifier using BERT features andtf.estimatorAPIThe complete example canbe found example5.py.Following the last example, we can easily extend it to a full classifier usingtf.estimatorAPI. One only need minor change on the input function as follows:estimator=DNNClassifier(hidden_units=[512],feature_columns=[tf.feature_column.numeric_column('feature',shape=(768,))],n_classes=len(laws),config=run_config,label_vocabulary=laws_str,dropout=0.1)input_fn=lambdafp:(tf.data.TextLineDataset(fp).apply(tf.contrib.data.shuffle_and_repeat(buffer_size=10000)).batch(batch_size).map(lambdax:tf.py_func(get_encodes,[x],[tf.float32,tf.string]),num_parallel_calls=num_parallel_calls).map(lambdax,y:({'feature':x},y)).prefetch(20))train_spec=TrainSpec(input_fn=lambda:input_fn(train_fp))eval_spec=EvalSpec(input_fn=lambda:input_fn(eval_fp),throttle_secs=0)train_and_evaluate(estimator,train_spec,eval_spec)The complete example canbe found example5.py, in which a simple MLP is built on BERT features for predicting the relevant articles according to the fact description in the law documents. The problem is a part of theChinese AI and Law Challenge Competition.Saving and loading with TFRecord dataThe complete example canbe found example6.py.The TFRecord file format is a simple record-oriented binary format that many TensorFlow applications use for training data. You can also pre-encode all your sequences and store their encodings to a TFRecord file, then later load it to build atf.Dataset. For example, to write encoding into a TFRecord file:bc=BertClient()list_vec=bc.encode(lst_str)list_label=[0for_inlst_str]# a dummy list of all-zero labels# write to tfrecordwithtf.python_io.TFRecordWriter('tmp.tfrecord')aswriter:defcreate_float_feature(values):returntf.train.Feature(float_list=tf.train.FloatList(value=values))defcreate_int_feature(values):returntf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))for(vec,label)inzip(list_vec,list_label):features={'features':create_float_feature(vec),'labels':create_int_feature([label])}tf_example=tf.train.Example(features=tf.train.Features(feature=features))writer.write(tf_example.SerializeToString())Now we can load from it and build atf.Dataset:def_decode_record(record):"""Decodes a record to a TensorFlow example."""returntf.parse_single_example(record,{'features':tf.FixedLenFeature([768],tf.float32),'labels':tf.FixedLenFeature([],tf.int64),})ds=(tf.data.TFRecordDataset('tmp.tfrecord').repeat().shuffle(buffer_size=100).apply(tf.contrib.data.map_and_batch(lambdarecord:_decode_record(record),batch_size=64)).make_one_shot_iterator().get_next())To save word/token-level embedding to TFRecord, one needs to first flatten[max_seq_len, num_hidden]tensor into an 1D array as follows:defcreate_float_feature(values):returntf.train.Feature(float_list=tf.train.FloatList(value=values.reshape(-1)))And later reconstruct the shape when loading it:name_to_features={"feature":tf.FixedLenFeature([max_seq_length*num_hidden],tf.float32),"label_ids":tf.FixedLenFeature([],tf.int64),}def_decode_record(record,name_to_features):"""Decodes a record to a TensorFlow example."""example=tf.parse_single_example(record,name_to_features)example['feature']=tf.reshape(example['feature'],[max_seq_length,-1])returnexampleBe careful, this will generate a huge TFRecord file.Asynchronous encodingThe complete example canbe found example2.py.BertClient.encode()offers a nice synchronous way to get sentence encodes. However,   sometimes we want to do it in an asynchronous manner by feeding all textual data to the server first, fetching the encoded results later. This can be easily done by:# an endless data stream, generating data in an extremely fast speeddeftext_gen():whileTrue:yieldlst_str# yield a batch of text linesbc=BertClient()# get encoded vectorsforjinbc.encode_async(text_gen(),max_num_batch=10):print('received%dx%d'%(j.shape[0],j.shape[1]))Broadcasting to multiple clientsThe complete example canbe found in example3.py.The encoded result is routed to the client according to its identity. If you have multiple clients with same identity, then they all receive the results! You can use thismulticastfeature to do some cool things, e.g. training multiple different models (some usingscikit-learnsome usingtensorflow) in multiple separated processes while only callBertServeronce. In the example below,bcand its two clones will all receive encoded vector.# clone a client by reusing the identitydefclient_clone(id,idx):bc=BertClient(identity=id)forjinbc.listen():print('clone-client-%d: received%dx%d'%(idx,j.shape[0],j.shape[1]))bc=BertClient()# start two cloned clients sharing the same identity as bcforjinrange(2):threading.Thread(target=client_clone,args=(bc.identity,j)).start()for_inrange(3):bc.encode(lst_str)Monitoring the service status in a dashboardThe complete example canbe found in plugin/dashboard/.As a part of the infrastructure, one may also want to monitor the service status and show it in a dashboard. To do that, we can use:bc=BertClient(ip='server_ip')json.dumps(bc.server_status,ensure_ascii=False)This gives the current status of the server including number of requests, number of clients etc. in JSON format. The only thing remained is to start a HTTP server for returning this JSON to the frontend that renders it.Alternatively, one may simply expose an HTTP port when starting a server via:bert-serving-start-http_port8081-model_dir...This will allow one to use javascript orcurlto fetch the server status at port 8081.plugin/dashboard/index.htmlshows a simple dashboard based on Bootstrap and Vue.js.Usingbert-as-serviceto serve HTTP requests in JSONBesides callingbert-as-servicefrom Python, one can also call it via HTTP request in JSON. It is quite useful especially when low transport layer is prohibited. Behind the scene,bert-as-servicespawns a Flask server in a separate process and then reuse aBertClientinstance as a proxy to communicate with the ventilator.To enable the build-in HTTP server, we need to first (re)install the server with some extra Python dependencies:pipinstall-Ubert-serving-server[http]Then simply start the server with:bert-serving-start-model_dir=/YOUR_MODEL-http_port8125Done! Your server is now listening HTTP and TCP requests at port8125simultaneously!To send a HTTP request, first prepare the payload in JSON as following:{"id":123,"texts":["hello world","good day!"],"is_tokenized":false}, whereidis a unique identifier helping you to synchronize the results;is_tokenizedfollows the meaning inBertClientAPIandfalseby default.Then simply call the server at/encodevia HTTP POST request. You can use javascript or whatever, here is an example usingcurl:curl-XPOSThttp://xx.xx.xx.xx:8125/encode\-H'content-type: application/json'\-d'{"id": 123,"texts": ["hello world"], "is_tokenized": false}', which returns a JSON:{"id":123,"results":[[768float-list],[768float-list]],"status":200}To get the server's status and client's status, you can send GET requests at/status/serverand/status/client, respectively.Finally, one may also config CORS to restrict the public access of the server by specifying-corswhen startingbert-serving-start. By default-cors=*, meaning the server is public accessible.StartingBertServerfrom PythonBesides shell, one can also start aBertServerfrom python. Simply dofrombert_serving.server.helperimportget_args_parserfrombert_serving.serverimportBertServerargs=get_args_parser().parse_args(['-model_dir','YOUR_MODEL_PATH_HERE','-port','5555','-port_out','5556','-max_seq_len','NONE','-mask_cls_sep','-cpu'])server=BertServer(args)server.start()Note that it's basically mirroring the arg-parsing behavior in CLI, so everything in that.parse_args([])list should be string, e.g.['-port', '5555']not['-port', 5555].To shutdown the server, you may call the static method inBertServerclass via:BertServer.shutdown(port=5555)Or via shell CLI:bert-serving-terminate-port5555This will terminate the server running on localhost at port 5555. You may also use it to terminate a remote server, seebert-serving-terminate --helpfor details.:speech_balloon: FAQ▴ Back to topQ:Do you have a paper or other written explanation to introduce your model's details?The design philosophy and technical details can be foundin my blog post.Q:Where is the BERT code come from?A:BERT code of this repois forked from theoriginal BERT repowith necessary modification,especially in extract_features.py.Q:How large is a sentence vector?In general, each sentence is translated to a 768-dimensional vector. Depending on the pretrained BERT you are using,pooling_strategyandpooling_layerthe dimensions of the output vector could be different.Q:How do you get the fixed representation? Did you do pooling or something?A:Yes, pooling is required to get a fixed representation of a sentence. In the default strategyREDUCE_MEAN, I take the second-to-last hidden layer of all of the tokens in the sentence and do average pooling.Q:Are you suggesting using BERT without fine-tuning?A:Yes and no. On the one hand, Google pretrained BERT on Wikipedia data, thus should encode enough prior knowledge of the language into the model. Having such feature is not a bad idea. On the other hand, these prior knowledge is not specific to any particular domain. It should be totally reasonable if the performance is not ideal if you are using it on, for example, classifying legal cases. Nonetheless, you can always first fine-tune your own BERT on the downstream task and then usebert-as-serviceto extract the feature vectors efficiently. Keep in mind thatbert-as-serviceis just a feature extraction service based on BERT. Nothing stops you from using a fine-tuned BERT.Q:Can I get a concatenation of several layers instead of a single layer ?A:Sure! Just use a list of the layer you want to concatenate when calling the server. Example:bert-serving-start-pooling_layer-4-3-2-1-model_dir/tmp/english_L-12_H-768_A-12/Q:What are the available pooling strategies?A:Here is a table summarizes all pooling strategies I implemented. Choose your favorite one by specifyingbert-serving-start -pooling_strategy.StrategyDescriptionNONEno pooling at all, useful when you want to use word embedding instead of sentence embedding. This will results in a[max_seq_len, 768]encode matrix for a sequence.REDUCE_MEANtake the average of the hidden state of encoding layer on the time axisREDUCE_MAXtake the maximum of the hidden state of encoding layer on the time axisREDUCE_MEAN_MAXdoREDUCE_MEANandREDUCE_MAXseparately and then concat them together on the last axis, resulting in 1536-dim sentence encodesCLS_TOKENorFIRST_TOKENget the hidden state corresponding to[CLS], i.e. the first tokenSEP_TOKENorLAST_TOKENget the hidden state corresponding to[SEP], i.e. the last tokenQ:Why not use the hidden state of the first token as default strategy, i.e. the[CLS]?A:Because a pre-trained model is not fine-tuned on any downstream tasks yet. In this case, the hidden state of[CLS]is not a good sentence representation. If later you fine-tune the model, you may use[CLS]as well.Q:BERT has 12/24 layers, so which layer are you talking about?A:By default this service works on the second last layer, i.e.pooling_layer=-2. You can change it by settingpooling_layerto other negative values, e.g. -1 corresponds to the last layer.Q:Why not the last hidden layer? Why second-to-last?A:The last layer is too closed to the target functions (i.e. masked language model and next sentence prediction) during pre-training, therefore may be biased to those targets. If you question about this argument and want to use the last hidden layer anyway, please feel free to setpooling_layer=-1.Q:So which layer and which pooling strategy is the best?A:It depends. Keep in mind that different BERT layers capture different information. To see that more clearly, here is a visualization onUCI-News Aggregator Dataset, where I randomly sample 20K news titles; get sentence encodes from different layers and with different pooling strategies, finally reduce it to 2D via PCA (one can of course do t-SNE as well, but that's not my point). There are only four classes of the data, illustrated in red, blue, yellow and green. To reproduce the result, please runexample7.py.Intuitively,pooling_layer=-1is close to the training output, so it may be biased to the training targets. If you don't fine tune the model, then this could lead to a bad representation.pooling_layer=-12is close to the word embedding, may preserve the very original word information (with no fancy self-attention etc.). On the other hand, you may achieve the very same performance by simply using a word-embedding only. That said, anything in-between [-1, -12] is then a trade-off.Q:Could I use other pooling techniques?A:For sure. But if you introduce newtf.variablesto the graph, then you need to train those variables before using the model. You may also want to checksome pooling techniques I mentioned in my blog post.Q:Do I need to batch the data beforeencode()?No, not at all. Just doencodeand let the server handles the rest. If the batch is too large, the server will do batching automatically and it is more efficient than doing it by yourself. No matter how many sentences you have, 10K or 100K, as long as you can hold it in client's memory, just send it to the server. Please also readthe benchmark on the client batch size.Q:Can I start multiple clients and send requests to one server simultaneously?A:Yes! That's the purpose of this repo. In fact you can start as many clients as you want. One server can handle all of them (given enough time).Q:How many requests can one service handle concurrently?A:The maximum number of concurrent requests is determined bynum_workerinbert-serving-start. If you a sending more thannum_workerrequests concurrently, the new requests will be temporally stored in a queue until a free worker becomes available.Q:So one request means one sentence?A:No. One request means a list of sentences sent from a client. Think the size of a request as the batch size. A request may contain 256, 512 or 1024 sentences. The optimal size of a request is often determined empirically. One large request can certainly improve the GPU utilization, yet it also increases the overhead of transmission. You may runpython example/example1.pyfor a simple benchmark.Q:How about the speed? Is it fast enough for production?A:It highly depends on themax_seq_lenand the size of a request. On a single Tesla M40 24GB withmax_seq_len=40, you should get about 470 samples per second using a 12-layer BERT. In general, I'd suggest smallermax_seq_len(25) and larger request size (512/1024).Q:Did you benchmark the efficiency?A:Yes. SeeBenchmark.To reproduce the results, please runbert-serving-benchmark.Q:What is backend based on?A:ZeroMQ.Q:What is the parallel processing model behind the scene?Q:Why does the server need two ports?One port is for pushing text data into the server, the other port is for publishing the encoded result to the client(s). In this way, we get rid of back-chatter, meaning that at every level recipients never talk back to senders. The overall message flow is strictly one-way, as depicted in the above figure. Killing back-chatter is essential to real scalability, allowing us to useBertClientin an asynchronous way.Q:Do I need Tensorflow on the client side?A:No. Think ofBertClientas a general feature extractor, whose output can be fed toanyML models, e.g.scikit-learn,pytorch,tensorflow. The only file that client need isclient.py. Copy this file to your project and import it, then you are ready to go.Q:Can I use multilingual BERT model provided by Google?A:Yes.Q:Can I use my own fine-tuned BERT model?A:Yes. In fact, this is suggested. Make sure you have the following three items inmodel_dir:A TensorFlow checkpoint (bert_model.ckpt) containing the pre-trained weights (which is actually 3 files).A vocab file (vocab.txt) to map WordPiece to word id.A config file (bert_config.json) which specifies the hyperparameters of the model.Q:Can I run it in python 2?A:Server side no, client side yes. This is based on the consideration that python 2.x might still be a major piece in some tech stack. Migrating the whole downstream stack to python 3 for supportingbert-as-servicecan take quite some effort. On the other hand, setting upBertServeris just a one-time thing, which can be evenrun in a docker container. To ease the integration, we support python 2 on the client side so that you can directly useBertClientas a part of your python 2 project, whereas the server side should always be hosted with python 3.Q:Do I need to do segmentation for Chinese?No, if you are usingthe pretrained Chinese BERT released by Googleyou don't need word segmentation. As this Chinese BERT is character-based model. It won't recognize word/phrase even if you intentionally add space in-between. To see that more clearly, this is what the BERT model actually receives after tokenization:bc.encode(['hey you','whats up?','你好么？','我 还 可以'])tokens: [CLS] hey you [SEP]
input_ids: 101 13153 8357 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
input_mask: 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

tokens: [CLS] what ##s up ? [SEP]
input_ids: 101 9100 8118 8644 136 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
input_mask: 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

tokens: [CLS] 你 好 么 ？ [SEP]
input_ids: 101 872 1962 720 8043 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
input_mask: 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

tokens: [CLS] 我 还 可 以 [SEP]
input_ids: 101 2769 6820 1377 809 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
input_mask: 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0That means the word embedding is actually the character embedding for Chinese-BERT.Q:Why my (English) word is tokenized to##something?Because your word is out-of-vocabulary (OOV). The tokenizer from Google uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary.For example:input="unaffable"tokenizer_output=["un","##aff","##able"]Q:Can I use my own tokenizer?Yes. If you already tokenize the sentence on your own, simply send useencodewithList[List[Str]]as input and turn onis_tokenized, i.e.bc.encode(texts, is_tokenized=True).Q:I encounterzmq.error.ZMQError: Operation cannot be accomplished in current statewhen usingBertClient, what should I do?A:This is often due to the misuse ofBertClientin multi-thread/process environment. Note that you can’t reuse oneBertClientamong multiple threads/processes, you have to make a separate instance for each thread/process. For example, the following won't work at all:# BAD examplebc=BertClient()# in Proc1/Thread1 scope:bc.encode(lst_str)# in Proc2/Thread2 scope:bc.encode(lst_str)Instead, please do:# in Proc1/Thread1 scope:bc1=BertClient()bc1.encode(lst_str)# in Proc2/Thread2 scope:bc2=BertClient()bc2.encode(lst_str)Q:After running the server, I have several garbagetmpXXXXfolders. How can I change this behavior ?A:These folders are used by ZeroMQ to store sockets. You can choose a different location by setting the environment variableZEROMQ_SOCK_TMP_DIR:export ZEROMQ_SOCK_TMP_DIR=/tmp/Q:The cosine similarity of two sentence vectors is unreasonably high (e.g. always > 0.8), what's wrong?A:A decent representation for a downstream task doesn't mean that it will be meaningful in terms of cosine distance. Since cosine distance is a linear space where all dimensions are weighted equally. if you want to use cosine distance anyway, then please focus on the rank not the absolute value. Namely, do not use:if cosine(A, B) > 0.9, then A and B are similarPlease consider the following instead:if cosine(A, B) > cosine(A, C), then A is more similar to B than C.The graph below illustrates the pairwise similarity of 3000 Chinese sentences randomly sampled from web (char. length < 25). We compute cosine similarity based on the sentence vectors andRouge-Lbased on the raw text. The diagonal (self-correlation) is removed for the sake of clarity. As one can see, there is some positive correlation between these two metrics.Q:I'm getting bad performance, what should I do?A:This often suggests that the pretrained BERT could not generate a decent representation of your downstream task. Thus, you can fine-tune the model on the downstream task and then usebert-as-serviceto serve the fine-tuned BERT. Note that,bert-as-serviceis just a feature extraction service based on BERT. Nothing stops you from using a fine-tuned BERT.Q:Can I run the server side on CPU-only machine?A:Yes, please runbert-serving-start -cpu -max_batch_size 16. Note that, CPUs do not scale as well as GPUs to large batches, therefore themax_batch_sizeon the server side needs to be smaller, e.g. 16 or 32.Q:How can I choosenum_worker?A:Generally, the number of workers should be less than or equal to the number of GPUs or CPUs that you have. Otherwise, multiple workers will be allocated to one GPU/CPU, which may not scale well (and may cause out-of-memory on GPU).Q:Can I specify which GPU to use?A:Yes, you can specifying-device_mapas follows:bert-serving-start-device_map014-num_worker4-model_dir...This will start four workers and allocate them to GPU0, GPU1, GPU4 and again GPU0, respectively. In general, ifnum_worker>device_map, then devices will be reused and shared by the workers (may scale suboptimally or cause OOM); ifnum_worker<device_map, onlydevice_map[:num_worker]will be used.Note,device_mapis ignored when running on CPU.:zap: Benchmark▴ Back to topThe primary goal of benchmarking is to test the scalability and the speed of this service, which is crucial for using it in a dev/prod environment. Benchmark was done on Tesla M40 24GB, experiments were repeated 10 times and the average value is reported.To reproduce the results, please runbert-serving-benchmark--helpCommon arguments across all experiments are:ParameterValuenum_worker1,2,4max_seq_len40client_batch_size2048max_batch_size256num_client1Speed wrt.max_seq_lenmax_seq_lenis a parameter on the server side, which controls the maximum length of a sequence that a BERT model can handle. Sequences larger thanmax_seq_lenwill be truncated on the left side. Thus, if your client want to send long sequences to the model, please make sure the server can handle them correctly.Performance-wise, longer sequences means slower speed and  more chance of OOM, as the multi-head self-attention (the core unit of BERT) needs to do dot products and matrix multiplications between every two symbols in the sequence.max_seq_len1 GPU2 GPU4 GPU20903177432544047391916878023143576816011923746432054108212Speed wrt.client_batch_sizeclient_batch_sizeis the number of sequences from a client when invokingencode(). For performance reason, please consider encoding sequences in batch rather than encoding them one by one.For example, do:# prepare your sent in advancebc=BertClient()my_sentences=[sforsinmy_corpus.iter()]# doing encoding in one-shotvec=bc.encode(my_sentences)DON'T:bc=BertClient()vec=[]forsinmy_corpus.iter():vec.append(bc.encode(s))It's even worse if you putBertClient()inside the loop. Don't do that.client_batch_size1 GPU2 GPU4 GPU1757472420620520182742702671633232933064365365365256382383383512432766762102445986215172048473917168140964819431809Speed wrt.num_clientnum_clientrepresents the number of concurrent clients connected to the server at the same time.num_client1 GPU2 GPU4 GPU1473919175922615121028413326753386713627016346813632173468As one can observe, 1 clients 1 GPU = 381 seqs/s, 2 clients 2 GPU 402 seqs/s, 4 clients 4 GPU 413 seqs/s. This shows the efficiency of our parallel pipeline and job scheduling, as the service can leverage the GPU time  more exhaustively as concurrent requests increase.Speed wrt.max_batch_sizemax_batch_sizeis a parameter on the server side, which controls the maximum number of samples per batch per worker. If a incoming batch from client is larger thanmax_batch_size, the server will split it into small batches so that each of them is less or equal thanmax_batch_sizebefore sending it to workers.max_batch_size1 GPU2 GPU4 GPU324508871726644598971759128473931181625647391916885124648661483Speed wrt.pooling_layerpooling_layerdetermines the encoding layer that pooling operates on. For example, in a 12-layer BERT model,-1represents the layer closed to the output,-12represents the layer closed to the embedding layer. As one can observe below, the depth of the pooling layer affects the speed.pooling_layer1 GPU2 GPU4 GPU[-1]4388441568[-2]4759161686[-3]5169951823[-4]56910761986[-5]63311932184[-6]71113402430[-7]82015282729[-8]94517723104[-9]112820473622[-10]139225424241[-11]152327374752[-12]156829855303Speed wrt.-fp16and-xlabert-as-servicesupports two additional optimizations: half-precision and XLA, which can be turned on by adding-fp16and-xlatobert-serving-start, respectively. To enable these two options, you have to meet the following requirements:your GPU supports FP16 instructions;your Tensorflow is self-compiled with XLA and-march=native;your CUDA and cudnn are not too old.On Tesla V100 withtensorflow=1.13.0-rc0it gives:FP16 achieves ~1.4x speedup (round-trip) comparing to the FP32 counterpart. To reproduce the result, please runpython example/example1.py.Citing▴ Back to topIf you use bert-as-service in a scientific publication, we would appreciate references to the following BibTex entry:@misc{xiao2018bertservice,
  title={bert-as-service},
  author={Xiao, Han},
  howpublished={\url{https://github.com/hanxiao/bert-as-service}},
  year={2018}}