<jupyter_start><jupyter_text>IntroductionIn this notebook, we demonstrate how BlazingText supports hosting of pre-trained Text Classification and Word2Vec models [FastText models](https://fasttext.cc/docs/en/english-vectors.html). BlazingText is a GPU accelerated version of FastText. FastText is a shallow Neural Network model used to perform both word embedding generation (unsupervised) and text classification (supervised). BlazingText uses custom CUDA kernels to accelerate the training process of FastText but the underlying algorithm is same for both the algorithms. Therefore, if you have a model trained with FastText or if one of the pre-trained models made available by FastText team is sufficient for your use case, then you can take advantage of Hosting support for BlazingText to setup SageMaker endpoints for realtime predictions using FastText models. It can help you avoid to train with BlazingText algorithm if your use-case is covered by the pre-trained models available from FastText. To start the proceedings, we will specify few of the important parameter like IAM Role and S3 bucket location which is required for SageMaker to facilitate model hosting. SageMaker Python SDK helps us to retrieve the IAM role and also helps you to operate easily with S3 resources.<jupyter_code>import sagemaker
from sagemaker import get_execution_role
import boto3
import json

sess = sagemaker.Session()

role = get_execution_role()
print(role) # This is the role that SageMaker would use to leverage AWS resources (S3, CloudWatch) on your behalf

bucket = sess.default_bucket() # Replace with your own bucket name if needed
print(bucket)
prefix = 'fasttext/pretrained' #Replace with the prefix under which you want to store the data if needed
region_name = boto3.Session().region_name
container = sagemaker.amazon.amazon_estimator.get_image_uri(region_name, "blazingtext", "latest")
print('Using SageMaker BlazingText container: {} ({})'.format(container, region_name))<jupyter_output>Using SageMaker BlazingText container: 501404015308.dkr.ecr.ap-northeast-1.amazonaws.com/blazingtext:latest (ap-northeast-1)<jupyter_text>Hosting the [Language Idenfication model](https://fasttext.cc/docs/en/language-identification.html) by FastTextFor the example, we will leverage the pre-trained model available by FastText for Language Identification. Language Identification is the first step of many NLP applications where after the language of the input text is identified, specific models for that language needs to be applied for various other downstream tasks. Language Identification underneath is a Text Classification model which uses the language IDs as the class labels and hence FastText can be directly used for the training. FastText pretrained language model supports identification of 176 different languages.  Here we will download the Language Identification (Text Classification) model [1] from [FastText website](https://fasttext.cc/docs/en/language-identification.html).  [1] <NAME>, <NAME>, <NAME>, <NAME>, Bag of Tricks for Efficient Text Classification<jupyter_code>!wget -O model.bin https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin<jupyter_output>--2019-06-17 02:05:54--  https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin
Resolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 192.168.127.12, 172.16.31.10, fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:16a6, ...
Connecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|192.168.127.12|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 131266198 (125M) [application/octet-stream]
Saving to: ‘model.bin’

model.bin           100%[===================>] 125.18M  16.6MB/s    in 8.1s    

2019-06-17 02:06:03 (15.5 MB/s) - ‘model.bin’ saved [131266198/131266198]<jupyter_text>Next we will `tar` the model and upload it to S3 with the help of utilities available from Python SDK. We'll delete the local copies of the data as it's not required anymore.<jupyter_code>!tar -czvf langid.tar.gz model.bin
model_location = sess.upload_data("langid.tar.gz", bucket=bucket, key_prefix=prefix)
!rm langid.tar.gz model.bin<jupyter_output>model.bin<jupyter_text>Creating SageMaker Inference EndpointNext we'll create a SageMaker inference endpoint with the BlazingText container. This endpoint will be compatible with the pre-trained models available from FastText and can be used for inference directly without any modification. The inference endpoint works with content-type of `application/json`.<jupyter_code>lang_id = sagemaker.Model(model_data=model_location, image=container, role=role, sagemaker_session=sess)
lang_id.deploy(initial_instance_count = 1,instance_type = 'ml.m4.xlarge')
predictor = sagemaker.RealTimePredictor(endpoint=lang_id.endpoint_name, 
                                   sagemaker_session=sess,
                                   serializer=json.dumps,
                                   deserializer=sagemaker.predictor.json_deserializer)<jupyter_output>---------------------------------------------------------------------------------------!<jupyter_text>Next we'll pass few sentences from various languages to the endpoint to verify that the language identification works as expected.<jupyter_code>sentences = ["hi which language is this?",
             "mon nom est Pierre",
             "Dem Jungen gab ich einen Ball.",
             "আমি বাড়ি যাবো."]
payload = {"instances" : sentences}
predictions = predictor.predict(payload)
print(predictions)<jupyter_output>[{'prob': [0.9948582053184509], 'label': ['__label__en']}, {'prob': [0.9984669089317322], 'label': ['__label__fr']}, {'prob': [0.9946573972702026], 'label': ['__label__de']}, {'prob': [0.9997219443321228], 'label': ['__label__bn']}]<jupyter_text>FastText expects the class label to be prefixed by `__label__` and that's why when we are performing inference with pre-trained model provided by FastText, we can see that the output label is prefixed with `__label__`. With a little preprocessing, we can strip the `__label__` prefix from the response.<jupyter_code>import copy
predictions_copy = copy.deepcopy(predictions) # Copying predictions object because we want to change the labels in-place
for output in predictions_copy:
    output['label'] = output['label'][0][9:].upper() #__label__ has length of 9

print(predictions_copy)<jupyter_output>[{'prob': [0.9948582053184509], 'label': 'EN'}, {'prob': [0.9984669089317322], 'label': 'FR'}, {'prob': [0.9946573972702026], 'label': 'DE'}, {'prob': [0.9997219443321228], 'label': 'BN'}]<jupyter_text>Stop / Close the Endpoint (Optional)Finally, we should delete the endpoint before we close the notebook if we don't need to keep the endpoint running for serving realtime predictions.<jupyter_code>sess.delete_endpoint(predictor.endpoint)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10453216374269006, 'fraction_numerical': 0.04473684210526316, 'mean_word_length': 4.897413793103448, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 28, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 3, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '265400', 'license': 'Apache-2.0', 'n_tokens_mistral': 2161, 'n_tokens_neox': 1921, 'n_words': 689, 'path': 'introduction_to_amazon_algorithms/blazingtext_hosting_pretrained_fasttext/blazingtext_hosting_pretrained_fasttext.ipynb', 'repo_name': 'whn09/amazon-sagemaker-examples', 'size': '6833'}