How To Fine-Tune LLaMA, OpenLLaMA, And XGen, With JAX On A GPU Or A TPU

LLaMA, OpenLLaMA, and XGen are cutting-edge generative AI models. These models give even much better results when fine-tuned on your own data. In this article let’s see how to fine-tune these models on both a GPU and a TPU, using JAX and the EasyLM library.

LLaMA, OpenLLaMA, and XGen

The LLaMA model was released by Meta in February 2023. This generative AI model is an open-source model proposed in several sizes: 7B parameters, 13B parameters, 33B parameters, and 65B parameters.

In June 2021, when GPT-J was released, the world started to realize that open-source generative AI models could seriously compete with OpenAI GPT-3. Now with LLaMA the bar has clearly been raised again and this model seems to be a very good open-source alternative to OpenAI ChatGPT and GPT-4.

LLaMA’s license is not business friendly though: this model cannot be used for commercial purposes… But good news is that other models now exist.

OpenLLaMA, released in June 2023, is an alternative version of LLaMA, developed by the Berkeley AI Research team that gives very good results and can be used for business. 2 versions are available as of this writing: 7B parameters and 13B parameters.

XGen, released by Salesforce in June 2023, is another very powerful foundational model that can be used in commercial applications. Only a 7B parameters version is available as of this writing. It is worth noting that this model supports an 8k tokens context, while LLaMA and OpenLLaMA only support a 2k tokens context.

Why Fine-Tune Your Own Model?

The above models are foundational models, which means that they have been trained in an unsupervised way on a large corpus of texts.

These foundational AI models usually are a good basis but they need to be tuned to properly understand what you want and return good results. The easiest way to achieve this is by using few-shot learning (also known as “prompt engineering”).

Few-shot learning is convenient as it can be performed on the fly without having to create a new version of the generative AI model, but it is sometimes not enough.

In order to get state-of-the-art results, you will want to fine-tune an AI model for your own use case. Fine-tuning means that you will modify some parameters in the model based on your own data, and then get your own version of the model.

Fine-tuning is much cheaper than training a generative AI model from scratch, but it still requires computation power, so you need advanced hardware in order to fine-tune your own model. Some recent alternative fine-tuning techniques require less computation power (see p-tuning, prompt tuning, soft tuning, parameter efficient fine-tuning, adapters, LoRA, QLoRA…) but so far I have not managed to get the same level of quality with these techniques so I am not going to mention them in this tutorial.

Fine-Tuning LLaMA On A TPU With JAX And EasyLM

In this tutorial I focus on fine-tuning LLaMA with the EasyLM library, released by the Berkeley AI Research team: https://github.com/young-geng/EasyLM. This library is based on JAX which makes the fine-tuning process fast and compatible with both GPUs and Google TPUs.

You can also fine-tune OpenLLaMA or XGen using the same technique.

I fine-tune LLaMA 7B on a Google TPU V3-8 here, but you can perfectly do the same on an A100 GPU (simply carefully read the “Installation” part in the EasyLM documentation that is slightly different). Of course you can also fine-tune bigger versions of LLaMA (13B, 33B, 65B…) but you will need much more than a TPU V3-8 or a single A100 GPU.

First, create a text generation dataset for your use case, in JSONL format, using “text” as a key for each example. Here is a simple sentiment analysis dataset:

{"text":"[Content]: I love NLP Cloud, this company is awesome!\n[Sentiment]: Positive"}
{"text":"[Content]: Training LLMs is a complex but rewarding process.\n[Sentiment]: Neutral"}
{"text":"[Content]: My fine-tuning keeps crashing because of an OOM error! It just does not work at all!\n[Sentiment]: Negative"}

Please note a couple of important things. First, this dataset only contains 3 examples for the sake of simplicity, but in real life you will need many more examples. 300 examples is usually a good start. Secondly, when you will use your fine-tuned model for inference, you will need to strictly follow the same formatting, using “[Content]:” and “[Sentiment]:” prefixes. Last of all, the </s> token is important because it means that the model should stop generating here.

Create a TPU V3-8 VM on Google Cloud with the V2 Alpha software version:

Creating a TPU v3-8 VM on Google Cloud

SSH into the VM and install EasyLM:

git clone https://github.com/young-geng/EasyLM
cd EasyLM
bash ./scripts/tpu_vm_setup.sh

You can now download and convert the LLaMA weights. First option is to ask Meta for the official weights: https://ai.facebook.com/blog/large-language-model-llama-meta-ai/. Then convert the weights to EasyLM with this script: https://github.com/young-geng/EasyLM/blob/main/EasyLM/models/llama/convert_torch_to_easylm.py. Second option is to use the LLaMA weights on HuggingFace: https://huggingface.co/decapoda-research/llama-7b-hf. Then convert the weights to EasyLM with this script: https://github.com/young-geng/EasyLM/blob/main/EasyLM/models/llama/convert_hf_to_easylm.py.

Upload your dataset to the VM, count how many tokens it contains, using the HF LLaMA tokenizer:

pip install -U transformers
python -c "from transformers import LlamaTokenizer; tokenizer = LlamaTokenizer.from_pretrained('decapoda-research/llama-7b-hf'); f = open('/path/to/your/dataset', 'r'); print(len(tokenizer.encode(f.read())))"

If you train your model for a 1024 tokens context, you will need to divide the returned number of tokens by 1024.

If you train your model for a 2048 tokens context, you will need to divide the returned number of tokens by 2048.

This number will be the number of steps per epoch. So for example if you want to train for 5 epochs (which is usually a good setting) you will need to multiply this number by 5 and put the resulting value in –total_steps below.

Here is a concrete example: if your dataset contains 100,000 tokens, and you want a 1024 tokens context and 5 epochs, your total number of steps will be (100,000/1024)*5 = 488.

Depending on your context length, set –train_dataset.json_dataset.seq_length as 1024 or 2048 below. Note that fine-tuning a model for a 2048 tokens context requires more memory, so if this is not strictly necessary I recommend that you stick to a 1024 tokens context.

You can now launch the fine-tuning process:

nohup python -u EasyLM/EasyLM/models/llama/llama_train.py \
--total_steps=your number of steps \
--save_model_freq=usually same as your number of steps \
--optimizer.adamw_optimizer.lr_warmup_steps=usually 10% of total steps \
--train_dataset.json_dataset.path='/path/to/your/dataset' \
--train_dataset.json_dataset.seq_length=1024 or 2048 \
--load_checkpoint='params::/path/to/converted/model' \
--tokenizer.vocab_file='/path/to/tokenizer' \
--logger.output_dir=/path/to/output  \
--mesh_dim='1,4,2' \
--load_llama_config='7b' \
--train_dataset.type='json' \
--train_dataset.text_processor.fields='text' \
--optimizer.type='adamw' \
--optimizer.accumulate_gradient_steps=1 \
--optimizer.adamw_optimizer.lr=0.002 \
--optimizer.adamw_optimizer.end_lr=0.002 \
--optimizer.adamw_optimizer.lr_decay_steps=100000000 \
--optimizer.adamw_optimizer.weight_decay=0.001 \
--optimizer.adamw_optimizer.multiply_by_parameter_scale=True \
--optimizer.adamw_optimizer.bf16_momentum=True &

Some explanations:

--save_model_freq: how often you want to save your model during the process. If you only fine-tune on a small dataset you can save at the end of the process only, and in that case this value will be equal to --total_steps.

--optimizer.adamw_optimizer.lr_warmup_steps: 10% of the total steps is usually a good value.

--tokenizer.vocab_file: the path to the tokenizer.model file. For example if you use the decapoda repository on HuggingFace, here is the link to the tokenizer: https://huggingface.co/decapoda-research/llama-7b-hf/resolve/main/tokenizer.model

--logger.output_dir: path to final model and logs

The other parameters can be left untouched.

Once the fine-tuning process is finished, you can retrieve your model at the path you specified in --logger.output_dir.

Using The Fine-Tuned Model For Inference

You now have your own fine-tuned model and you want to use it of course!

A first strategy is to use the EasyLM library for inference. In that case you can launch the inference server like this:

python EasyLM/EasyLM/models/llama/llama_serve.py  \
--mesh_dim='1,1,-1' \
--load_llama_config='7b' \
--load_checkpoint='params::/path/to/your/model' \
--tokenizer.vocab_file='/path/to/tokenizer'

Then simply send your requests with cURL like this:

curl "http://0.0.0.0:5007/generate" \
-H "Content-Type: application/json" \
-X POST -d '{"prefix_text":["[Content]: EasyLM works really well!\n[Sentiment]:"]}'

A second strategy is to export your model to the HuggingFace format in order to perform inference with another framework. Here is how you can export it:

python EasyLM/EasyLM/models/llama/convert_easylm_to_hf.py \
--load_checkpoint='params::/path/to/output/model/streaming_params' \
--tokenizer_path='/path/to/tokenizer' \
--model_size='7b' \
--output_dir='/path/to/converted/model'

Conclusion

2023 has been a great milestone for open-source generative AI models. As of this writing, everyone can use great models like LLaMA, OpenLLaMA, XGen, Orca, Falcon…

Fine-tuning these models is a way to obtain cutting edge results, tailored to your own use case, that can significantly outperform proprietary AI models like ChatGPT (GPT-3.5), GPT-4, Claude…

In this guide I showed you how to fine-tune LLaMA, OpenLLaMA, and XGen.

OpenAI vs NLP Cloud

How does OpenAI compare with NLP Cloud? Both platforms propose advanced AI models for text understanding, text generation, embeddings, text to image, and speech to text. But there are important differences in terms of features, pricing, and terms of service.

In this article, I will make an in-depth comparison between OpenAI and NLP Cloud.

Usage Restrictions

OpenAI is very restrictive about the kind of applications it allows. Until November 2022 you had to explicitly ask OpenAI to review and approve your application before going into production. Since then, here is what they say: “We no longer require you to register your applications with OpenAI. Instead, we’ll be using a combination of automated and manual methods to monitor for policy violations.”

Some applications are simply not allowed by default, like applications based on paraphrasing and rewriting (considered as “plagiarism”), multi-level marketing, sexual discussions… Moreover, they often require that you explicitly tell your end users that you are using AI in your application (this is the case for summarization, news generation, and anything related to the medical, legal, and financial industries). Here are the OpenAI’s usage policies:

OpenAI Restrictions

OpenAI Restrictions

At NLP Cloud, I believe customers should use their best judgement to decide how to use the AI models based on their local laws and their personal ethics. I do not think it is NLP Cloud’s role to inspect and filter customer requests.

Data Privacy

There is a significant difference between OpenAI and NLP Cloud when it comes to data privacy.

OpenAI does many things out of customers’ data. Data sent to OpenAI is reviewed and used for all sorts of things. The most important part is that your data is stored for an unlimited period and used to train and improve OpenAI’s AI models like ChatGPT. See an extract from OpenAI’s privacy policy below:

OpenAI Privacy Policy

These privacy considerations can be critical for many businesses, especially those dealing with data-sensitive industries like healthcare, legal, finance…

NLP Cloud is HIPAA / GDPR / CCPA compliant, and working on the SOC 2 certification. NLP Cloud cannot see your data, does not store your data, and does not use your data to train its own AI models.

Pricing Differences

OpenAI and NLP Cloud both propose pay-as-you-go prices. It means that you can pay after the fact, only for the number of requests or tokens you actually consumed.

NLP Cloud also proposes standard packages paid upfront. These plans give you access to a specific number of requests per minute. These plans are more cost-effective than pay-as-you-go if you have a large volume of requests to perform, as they help NLP Cloud predict consumption and scale the service accordingly in advance.

See OpenAI’s pricing below:

OpenAI Pricing

OpenAI Pricing

OpenAI Pricing

Let’s make a simple simulation. ChatDolphin is equivalent to ChatGPT (GPT 3.5 Turbo), so I am going to compare both prices.

On NLP Cloud, making 20 requests per minute on ChatDolphin, using 2048 tokens each, will cost you $699/month (Enterprise GPU plan).

On OpenAI, it will cost you 0.002/1000 x 2048 x 20 x 60 x 24 x 31 = $3,656/month.

The price difference is very significant, and it is actually even more important when comparing other features like fine-tuning, semantic search, embeddings, speech-to-text, text-to-image…

For example, making 5 speech-to-text requests per minute on Whisper Large, each audio file lasting 200 seconds, will cost you $699/month (Enterprise GPU plan).

On OpenAI it will cost you (0.006/60) x 200 x 5 x 60 x 24 x 31 = $4,464/month.

One last example with image generation. NLP Cloud uses Stable Diffusion, which is equivalent to OpenAI DALL-E. Making 5 image generation requests per minute on Stable Diffusion in 768 x 768 px format will cost you $699/month (Enterprise GPU plan).

On OpenAI, using the 512 x 512 px format (which is lower than 768 x 768) it will cost you 0.018 x 5 x 60 x 31 x 24 = $4,017/month.

Features And Models Available

OpenAI and NLP Cloud adopted 2 very different strategies: OpenAI builds a couple of in-house models (GPT-3, ChatGPT, GPT-4, DALL-E…) while NLP Cloud mixes open-source AI models (Bart, MPNet, Stable Diffusion…) with in-house models (Dolphin, ChatDolphin, …) on the same platform.

It means that on NLP Cloud you can of course use some ChatGPT competitors like GPT-NeoX and ChatDolphin, but you can also use many other models like Bart, T5, Distilbert, spaCy, etc.

Using specialized smaller models is often much more cost effective and much faster than using huge generative AI models.

Sometimes, some use cases just cannot be covered by regular AI models. That’s the case with multilingual AI for example. If you want to use AI in 200 languages, you can use NLP Cloud’s multilingual addon (free of charge). OpenAI does not propose so many languages for the moment.

Leveraging specialized models is also a good way to decrease complexity. For example, performing summarization with GPT-3 or ChatGPT will require some prompt engineering, while you can very simply get advanced results thanks to dedicated pre-trained models like Facebook’s Bart Large CNN.

Last of all, NLP Cloud proposes an “asynchronous” mode, meaning that you can trigger long running background jobs. It is useful for example if you want to summarize very large documents (up to 1 million tokens), or transcribe very long audio files. OpenAI doesn’t propose such a feature.

Reliability, Quota, And Quality Of Support

When comparing OpenAI and NLP Cloud I encourage you to look into 3 additional aspects: reliability of the API, quota, and quality of support.

OpenAI has experienced many severe service interruptions these last months, especially since the release of ChatGPT and GPT-4. They also faced bugs that led to critical security breaches recently, which scared many customers.

Learn more about recent OpenAI security issues here.

NLP Cloud provides a robust infrastructure and has not faced any significant service outage since March 2020 (caused by a fire in an OVH datacenter).

Also, it is important to note that OpenAI automatically applies severe quotas to new users. Basically, if you are a new user, you will need to wait for a while and apply for additional quotas before moving your application to production. NLP Cloud does not apply such quotas, so you can go to production instantly.

Last of all, it is in general quite difficult to get a prompt and elaborate response from the OpenAI support. NLP Cloud answers questions about prompt engineering, model selection, fine-tuning, and similar topics.

Conclusion

Many customers are looking for alternatives to OpenAI, mainly because of their use case restrictions, data privacy policy, pricing, and service disruptions.

Effectively Using ChatDolphin, The ChatGPT Alternative, With Simple Instructions

NLP Cloud has developed a powerful alternative to OpenAI ChatGPT, called ChatDolphin. These AI models are interesting because they understand very well simple instructions made in natural language without having to use few-shot learning and complex prompt engineering. Let’s see how to craft such instructions in order to make the most of ChatDolphin and ChatGPT.

ChatGPT and ChatDolphin

ChatGPT was released in December 2022 by OpenAI as a small generative model that is very good at understanding human instructions, optimized for conversations and large detailed answers. It appears that ChatGPT is very good at handling many use cases, not only conversations. Like GPT-3, you can use ChatGPT to perform summarization, paraphrasing, entity extraction, etc. Thanks to its small size, ChatGPT is also cheaper than GPT-3.

In April 2023, NLP Cloud released ChatDolphin, a powerful alternative to ChatGPT. ChatDolphin is an in-house NLP Cloud model that is very good at understanding human instructions, handling conversations, and behaves exactly like ChatGPT. ChatDolphin is cheap too.

Below, I’m showing you examples obtained using the text generation endpoint on NLP Cloud with ChatDolphin, with the Python client. If you want to copy paste the examples, please don’t forget to add your own API token. In order to install the Python client, first run the following: pip install nlpcloud.

Few-Shot Learning VS Simple Instructions

When the first large language models were released, like GPT-J, OPT, Bloom, etc. it quickly appeared that - despite being very powerful - these models were not able to understand simple human instructions made in natural language.

For example, if you want to extract a name, a position, and a company, from a piece of text, you need to do something like this using GPT-J on NLP Cloud:

import nlpcloud
client = nlpcloud.Client("gpt-j", "<your API token>", gpu=True)
generation = client.generation("""[Text]: Fred is a serial entrepreneur. Co-founder and CEO of Platform.sh, he previously co-founded Commerce Guys, a leading Drupal ecommerce provider. His mission is to guarantee that as we continue on an ambitious journey to profoundly transform how cloud computing is used and perceived, we keep our feet well on the ground continuing the rapid growth we have enjoyed up until now. 
[Name]: Fred
[Position]: Co-founder and CEO
[Company]: Platform.sh
###
[Text]: Microsoft (the word being a portmanteau of "microcomputer software") was founded by Bill Gates on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800. Steve Ballmer replaced Gates as CEO in 2000, and later envisioned a "devices and services" strategy.
[Name]:  Steve Ballmer
[Position]: CEO
[Company]: Microsoft
###
[Text]: Franck Riboud was born on 7 November 1955 in Lyon. He is the son of Antoine Riboud, the previous CEO, who transformed the former European glassmaker BSN Group into a leading player in the food industry. He is the CEO at Danone.
[Name]:  Franck Riboud
[Position]: CEO
[Company]: Danone
###
[Text]: David Melvin is working for CITIC CLSA with over 30 years’ experience in investment banking and private equity. He is currently a Senior Adviser of CITIC CLSA.
""",
    top_p=0,
    length_no_input=True,
    end_sequence="###",
    remove_end_sequence=True,
    remove_input=True)
print(generation["generated_text"])

This technique is known as few-shot learning, or prompt engineering.

Few-shot learning works very well on ChatGPT and ChatDolphin and allows you to get very advanced results. But in most cases few-shot learning is not needed and unnecessarily complex. Besides, as the generative AI models only allow for a limited input length, the few-shot examples sometimes simply don’t fit into the request.

Good news is that, when properly fine-tuned, the large language models can learn how to understand human instructions without using few-shot learning. This is the case of ChatGPT and ChatDolphin.

With these models, here is how your query would look like:

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Extract name, position, and company, from the following text.

David Melvin working for CITIC CLSA with over 30 years’ experience in investment banking and private equity. He is currently a Senior Adviser of CITIC CLSA.""")
print(generation["generated_text"])

Output:

Name: David Melvin
Position: Senior Adviser
Company: CITIC CLSA

Much simpler isn’t it? Now what if I want the result to be formatted as JSON? Here is a simple instruction:

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Extract name, position, and company, from the following text. Format the result as JSON.

David Melvin working for CITIC CLSA with over 30 years’ experience in investment banking and private equity. He is currently a Senior Adviser of CITIC CLSA.""")
print(generation["generated_text"])

Output:

{
"name": "David Melvin",
"position": "Senior Adviser",
"company": "CITIC CLSA"
}

I think you get the idea don’t you?

Note that these models are trained to generate large responses. If you need short and concise responses, you can mention it in your prompt (with something like “Make a short response.”).

Sentiment Analysis with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""What is the sentiment in the following text? Positive, negative, or neutral? Answer with one word only.

The reactivity of your team has been amazing, thanks!""")
print(generation["generated_text"])

Output:

Positive

HTML code generation with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Generate the HTML code for a a Headline saying "Welcome to AI"""")
print(generation["generated_text"])

Output:

<h1>Welcome to AI</h1>

Question Answering With ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Answer this question using the below context: Which plan is recommended for GPT-J? Make a short response.

Context: The main challenge with GPT-J is memory consumption. Using a GPU plan is recommended.""")
print(generation["generated_text"])

Output:

Since the main challenge with GPT-J is memory consumption, using a GPU plan is recommended to address this issue. Therefore, the recommended plan for GPT-J is the GPU plan.

Tutorial Creation With ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Create a tutorial about how to make a cake.""")
print(generation["generated_text"])

Output:

Here's a step-by-step guide to making a cake:

Ingredients:

* 2 cups all-purpose flour
* 2 teaspoons baking powder
* 1 teaspoon salt
* 1 cup unsalted butter, at room temperature
* 1 cup granulated sugar
* 2 large eggs
* 2 teaspoons vanilla extract
* 1 cup whole milk, at room temperature

Equipment:

* 9-inch round cake pan
* Rubber spatula
* Whisk
* Measuring cups and spoons
* Mixing bowls

Instructions:

1. Preheat your oven to 350°F (180°C). Grease and flour your 9-inch round cake pan.
2. In a mixing bowl, whisk together flour, baking powder, and salt. Set aside.
3. In another mixing bowl, using an electric mixer, beat together the butter and sugar until light and fluffy. Add the eggs, one at a time, beating well after each addition. Stir in the vanilla extract.
4. Gradually add the dry ingredients to the butter mixture, alternating with the milk and mixing until just combined.
5. Pour the batter into the prepared cake pan.
6. Bake the cake for 30-35 minutes, or until a toothpick inserted into the center comes out clean.
7. Remove the cake from the oven and let it cool in the pan for 5-10 minutes. Then, remove the cake from the pan and let it cool completely on a wire rack.
8. Once the cake is completely cool, you can ice and decorate it if you like. Enjoy!

Note: You can also use other types of flour, such as almond or coconut flour, and substitute other sweetener for the sugar, like honey or maple syrup. You can also add other ingredients like chocolate chips, nuts, or dried fruits to the batter for added flavor and texture.

Grammar and Spelling Correction with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Correct spelling and grammar mistakes from the following text.

I do not wan to go""")
print(generation["generated_text"])

Output:

I do not wan to go

Machine Translation with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Translate the following content to English.

NLP Cloud permet de deployer le NLP en production facilement.""")
print(generation["generated_text"])

Output:

NLP Cloud makes it easy to deploy NLP in production.

Tweet Generation with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Generate a Tweet about NLP.""")
print(generation["generated_text"])

Output:

NLP is revolutionizing the way we communicate with computers. From voice assistants to chatbots, natural language processing is making interactions with technology more human-like than ever before. Exciting times ahead for this field! #NLP #AI #Technology

Intent Classification with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""What is the main intent in the following text?

Hello

I spent some time on your documentation but I could not figure how to add a new credit card.
It is a problem because my current card is going to expire soon and I'm affraid that it will cause a service disruption.
How can I update my credit card?

Thanks in advance,

Looking forward to hearing from you,

John Doe""")
print(generation["generated_text"])

Output:

The main intent behind the text is to inquire about the process for updating a credit card in a service.

Paraphrasing with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Paraphrase the following text.

After a war lasting 20 years, following the decision taken first by President Trump and then by President Biden to withdraw American troops, Kabul, the capital of Afghanistan, fell within a few hours to the Taliban, without resistance.""")
print(generation["generated_text"])

Output:

Following a 20-year war that was initially approved by President Trump and then continued under President Biden's leadership, American soldiers were withdrawn from Afghanistan. As a result, the Taliban was able to easily seize control of Kabul, the capital of Afghanistan, without encountering any resistance.

Summarization with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Summarize the following text.

For all its whizz-bang caper-gone-wrong energy, and for all its subsequent emotional troughs, this week’s Succession finale might have been the most important in its entire run. Because, unless I am very much wrong, Succession – a show about people trying to forcefully mount a succession – just had its succession. And now everything has to change.
The episode ended with Logan Roy defying his children by selling Waystar Royco to idiosyncratic Swedish tech bro Lukas Matsson. It’s an unexpected twist, like if King Lear contained a weird new beat where Lear hands the British crown to Jack Dorsey for a laugh, but it sets up a bold new future for the show. What will happen in season four? Here are some theories.
Season three of Succession picked up seconds after season two ended. It was a smart move, showing the immediate swirl of confusion that followed Kendall Roy’s decision to undo his father, and something similar could happen here. This week’s episode ended with three of the Roy siblings heartbroken and angry at their father’s grand betrayal. Perhaps season four could pick up at that precise moment, and show their efforts to reorganise their rebellion against him. This is something that Succession undoubtedly does very well – for the most part, its greatest moments have been those heart-thumping scenes where Kendall scraps for support to unseat his dad – and Jesse Armstrong has more than enough dramatic clout to centre the entire season around the battle to stop the Matsson deal dead in its tracks.""")
print(generation["generated_text"])

Output:

The Succession finale had a succession, with Logan Roy selling Waystar Royco to Lukas Matsson, which sets up a bold new future for the show. The third season picked up seconds after the second season ended, and the next season could pick up at the moment where the Roy siblings are heartbroken and angry at their father's betrayal, centering the season around their rebellion against him.

Zero-shot text classification with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""In one word, what is the main topic in the following text?

After a war lasting 20 years, following the decision taken first by President Trump and then by President Biden to withdraw American troops, Kabul, the capital of Afghanistan, fell within a few hours to the Taliban, without resistance.""")
print(generation["generated_text"])

Output:

war

Keyword and Keyphrase Extraction with ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Extract the main keywords from the following text.

Since transformer models have a token limit, you might run into some errors when inputting large documents. In that case, you could consider splitting up your document into paragraphs and mean pooling (taking the average of) the resulting vectors.""")
print(generation["generated_text"])

Output:

Token limit, large documents, transformer models, splitting, paragraphs, mean pooling, tokenizing, vectorization.

Product Description and Ad Generation With ChatDolphin

import nlpcloud
client = nlpcloud.Client("chatdolphin", "<your API token>", gpu=True)
generation = client.generation("""Generate a product description out of the following keywords: t-shirt, men, $39""")
print(generation["generated_text"])

Output:

Introducing our premium t-shirt for men, made with high-quality materials and craftsmanship. This $39 t-shirt is designed to provide comfort and style, making it the perfect addition to any man's wardrobe. With a range of colors and sizes to choose from, you're sure to find the perfect t-shirt to suit your style. Whether you're running errands or hanging out with friends, our t-shirt is the perfect choice for any occasion.

Blog Post Generation With GPT-J

import nlpcloud
client = nlpcloud.Client("gpt-j", "<your API token>", gpu=True)
generation = client.generation("""Generate a whole blog article in HTML format about the following topic: 4 Best Tips to Find a Girlfriend
The article should contain the following keywords: Paris, romance, love""")
print(generation["generated_text"])

Output:

<html>
<head>
<title>4 Best Tips to Find a Girlfriend</title>
<meta charset="UTF-8">
<meta name="description" content="Looking for love in Paris? Follow these four tips to find your perfect girlfriend.">
</head>
<body>
<h1>4 Best Tips to Find a Girlfriend in Paris</h1>
<p>Are you tired of the dating scene in Paris and ready to find a serious relationship? Finding a girlfriend in the City of Love can seem like a daunting task, but with these four tips, you can increase your chances of finding lasting love.</p>
<h2>1. Be Open-Minded</h2>
<p>One of the biggest mistakes people make when looking for a girlfriend is being too picky. Instead of focusing on the little things that might be deal breakers, be open to different types of people and personalities. You never know who you might hit it off with if you keep an open mind.</p>
<h2>2. Join a Social Club or Group</h2>
<p>Joining a social club or group that aligns with your interests can be a great way to meet new people and potentially find a girlfriend. Whether it's a book club, a sports team, or a Language exchange group, there are plenty of options to choose from in Paris. You can also sign up for online dating apps, but the chances of finding a meaningful connection are higher when you have something in common.</p>
<h2>3. Take Romantic Strolls</h2>
<p>Paris is known for its romantic atmosphere, and taking a stroll along the Seine or through the Luxembourg Gardens can be a great way to impress a potential girlfriend. Pack a picnic basket and enjoy a romantic lunch in the park, or take a boat ride down the Seine for a unique date. These memorable experiences can help you build a strong bond with someone special.</p>
<h2>4. Be Patient</h2>
<p>Finding a girlfriend in Paris takes time, just like finding love anywhere else. Don't get discouraged if things don't happen right away. Instead, focus on building genuine connections and getting to know people. The right person will come along when you least expect it, so be patient and keep an open mind.</p>
<p>By following these four tips, you can increase your chances of finding a girlfriend in Paris and experiencing the joys of lasting love. Remember to be open-minded, join social clubs or groups, take romantic strolls, and be patient. Good luck!</p>
<p>If you are looking for a girlfriend, here are some more tips to consider:<br><br>- Have a clear idea of what you want in a partner.<br>- Be confident and approachable.<br>- Show genuine interest in the person you're dating.<br>- Be respectful and treat your date with kindness and attention.</p>
<p>If you enjoyed this article, please like it on social media and share it with your friends. Your support helps us continue to provide valuable content.</p>
<p>For more tips and advice on dating and relationships, check out our blog.</p>
</body>
</html>

Conclusion

As you can see, ChatGPT and ChatDolphin can be easily used for many use cases without having to use few-shot learning!

The possibilities are countless! The idea is to be very clear and explicit in your instruction so the model correctly understands what you want.

Hope you found it useful!

An Instruct Version Of GPT-J Using Stanford Alpaca's Dataset

I wanted to see if GPT-J could be fine-tuned as an instruct model in order to properly understand human instructions in natural language, without using few-shot learning. Other attempts have given interesting results in the open-source community, like Flan-T5, BloomZ, or Stanford Alpaca, so I wanted to do the same on GPT-J using Alpaca’s dataset. Results are very good!

Few-Shot Learning VS Natural Language Instructions

Generative AI models are not good at understanding human requests, by default.

In order to have these text generation models understand what you want, the best solution is to use few-shot learning. GPT-J is a good example of a very capable model that only works correctly with few-shot learning.

Even if building these examples is usually not taking too much time, it is still very confusing for newcomers who want to use these AI models correctly. It is much easier to ask things naturally like you would do with a human.

For example let’s say that you want to correct spelling mistakes with GPT-J. Here is an example of a prompt you have to use:

I love goin to the beach.
Correction: I love going to the beach.
###
Let me hav it!
Correction: Let me have it!
###
It have too many drawbacks.
Correction: It has too many drawbacks.
###
I do not wan to go
Correction:

As you can see, this is not complex but not straightforward either. If you properly fine-tune GPT-J, it can be turned into an “instruct” model, which means that you can now ask the following:

Correct spelling and grammar from the following text.
I do not wan to go

And it would return the following:

I do not want to go.

Much better isn’t it? How can I achieve this?

Stanford Alpaca

Stanford Alpaca has been released a couple of days ago. This is a fine-tuned version of the Llama model, developed by Facebook. See more here about this project here.

Basically, the Stanford Alpaca team managed to come up with a state-of-the-art instruct model by fine-tuning Llama on a fairly small dataset (52k examples) made up of human instructions. The interesting thing is that they generated this dataset programmatically using a larger language model (GPT-3). You can download the dataset here.

At NLP Cloud I tried to fine-tune GPT-J using this dataset, and I got surprisingly good results!

Instruct GPT-J

The new Instruct GPT-J model is now on the Hugging Face Hub so you can easily use it: click here to see the model.

Here is how you can use the model, using Hugging Face Transformers:

from transformers import pipeline
import torch

generator = pipeline(model="nlpcloud/instruct-gpt-j-fp16", torch_dtype=torch.float16, device=0)

prompt = "Correct spelling and grammar from the following text.\nI do not wan to go\n"

print(generator(prompt))

Here are some prompts that you can try:

Write a short story about space.\n
Generate a C++ program that sorts a list of integers in ascending order.\n
Paraphrase the following text.\nAfter a war lasting 20 years, following the decision taken first by President Trump and then by President Biden to withdraw American troops, Kabul, the capital of Afghanistan, fell within a few hours to the Taliban, without resistance.\n
Summarize the following text.\nFor all its whizz-bang caper-gone-wrong energy, and for all its subsequent emotional troughs, this week’s Succession finale might have been the most important in its entire run. Because, unless I am very much wrong, Succession – a show about people trying to forcefully mount a succession – just had its succession. And now everything has to change. The episode ended with Logan Roy defying his children by selling Waystar Royco to idiosyncratic Swedish tech bro Lukas Matsson. It’s an unexpected twist, like if King Lear contained a weird new beat where Lear hands the British crown to Jack Dorsey for a laugh, but it sets up a bold new future for the show. What will happen in season four? Here are some theories. Season three of Succession picked up seconds after season two ended. It was a smart move, showing the immediate swirl of confusion that followed Kendall Roy’s decision to undo his father, and something similar could happen here. This week’s episode ended with three of the Roy siblings heartbroken and angry at their father’s grand betrayal. Perhaps season four could pick up at that precise moment, and show their efforts to reorganise their rebellion against him. This is something that Succession undoubtedly does very well – for the most part, its greatest moments have been those heart-thumping scenes where Kendall scraps for support to unseat his dad – and Jesse Armstrong has more than enough dramatic clout to centre the entire season around the battle to stop the Matsson deal dead in its tracks.\n

Note that, due to the way this model was fine-tuned, you should always use new lines at the end of your instructions.

Hardware Requirements

This model is an fp16 version of the fine-tuned model, which works very well on a GPU with 16GB of VRAM like an NVIDIA Tesla T4.

I did not notice any difference between the fp32 and fp16 versions in terms of quality.

Conclusion

GPT-J was already a very good model, and it is now even better when used as an instruct model.

Anyone can now turn his AI generative model into an instruct model thanks to this technique!

Question Answering On Domain Knowledge With Semantic Search And Text Generation

Answering questions based on domain knowledge (like internal documentation, contracts, books, etc.) is challenging because it requires to address large documents. In this article I explore an advanced technique in order to achieve question answering on large texts with great accuracy, mixing semantic search and text generation with models like GPT-3, GPT-J, or GPT-NeoX.

The Challenges About Answering Questions On Domain Knowledge

Question answering on domain knowledge requires that you first send some context to the AI model, and then ask a question about it.

For example you could send the following context:

All NLP Cloud plans can be stopped anytime. You only pay for the time you used the service. In case of a downgrade, you will get a discount on your next invoice.

Now you might want to ask the following question:

When can plans be stopped?

The AI would answer something like this:

Anytime

The problem with this approach is that the size of your context is limited. On modern AI models (based on Transformers), the maximum size of such a context is 2048 tokens (which is pretty much equivalent to 1500 words).

Let’s say that you want to build a support chatbot that knows everything about your product documentation, so end users can ask any product-related question to the chatbot without contacting a real support agent. Most likely, your documentation will be made up of several hundreds or thousands of words, or even millions of words…

Let’s explore how to overcome this limitation and perform question answering on very large documents.

Semantic Search VS Text Generation

When it comes to question answering, 2 kinds of technologies can be used. Text generation and semantic search.

The first one, text generation, is basically what I just showed above. It usually takes an advanced text generation model like GPT-J, GPT-NeoX, GPT-3, OPT, Bloom… It is able to understand a human question, and respond like a human too. However it does not work on large documents. A strategy could be to fine-tune your own text generation model with your own domain knowledge. This strategy sometimes works well, but in some cases the text generation model tends to “forget” some of the facts mentioned in the dataset. So text generation is more fluent to answer questions, but also a bit less reliable when dealing with open knowledge.

Semantic search is basically about searching a document the same way as Google, but based on your own domain knowledge. In order to achieve that, you need to train your own semantic search model with your own domain knowledge. Then once your model is created, you can ask questions in natural language and your AI model will return the entry in your dataset that best answers your question.

Semantic search is usually very fast and relatively cheap. It is also more reliable than the text generation fine-tuning strategy. But it is not able to properly “answer” a question. It simply returns a piece of text that contains an answer to your question. Then it is up to the user to read the whole piece of text in order to find the answer to his question.

Good news is that it is possible to combine both semantic search and text generation in order to achieve advanced results!

Question Answering Mixing Semantic Search And Text Generation

In order to answer questions on domain knowledge, the strategy I use at NLP Cloud is the following: first make a request with semantic search in order to retrieve the resource that best answers your question, and then use text generation to answer the question based on this resource like a human.

Let’s say that I am an HP printers reseller, and I want to answer my customer’s questions on my website.

First I will need to create my own semantic search model. Here it will be made of 3 examples only, but in real life you can include up to 1 million examples when using semantic search on NLP Cloud. I simply create a CSV file and put the following inside:

HP® LaserJets have unmatched printing speed, performance and reliability that you can trust. Enjoy Low Prices and Free Shipping when you buy now online.
Every HP printer comes with at least a one-year HP commercial warranty (or HP Limited Warranty). Some models automatically benefit from a three-year warranty, which is the case of the HP Color LaserJet Plus, the HP Color LaserJet Pro, and the HP Color LaserJet Expert.
HP LaserJet ; Lowest cost per page on mono laser printing. · $319.99 ; Wireless options available. · $109.00 ; Essential management features. · $209.00.

I then upload my CSV dataset to NLP Cloud and click “Create model”. After a while, my own semantic search model containing my own domain knowledge will be ready and I will receive a private API URL in order to use it.

Let’s ask a question to my brand new model using the NLP Cloud Python client:

import nlpcloud

# The model name below is only an illustration.
client = nlpcloud.Client("custom-model/5d8e6s8w5", "<your API token>", gpu=True)
client.semantic_search("How long is the warranty on the HP Color LaserJet Pro?")

The model quickly returns the following with a short response time:

{
"search_results": [
    {
        "score": 0.99,
        "text": "Every HP printer comes with at least a one-year HP commercial warranty (or HP Limited Warranty). Some models automatically benefit from a three-year warranty, which is the case of the HP Color LaserJet Plus, the HP Color LaserJet Pro, and the HP Color LaserJet Expert."
    },
    {
        "score": 0.74,
        "text": "All consumer PCs and printers come with a standard one-year warranty. Care packs provide an enhanced level of support and/or an extended period of coverage for your HP hardware. All commercial PCs and printers come with either a one-year or three-year warranty."
    },
    {
        "score": 0.68,
        "text": "In-warranty plan · Available in 2-, 3-, or 4-year extension plans · Includes remote problem diagnosis support and Next Business Day Exchange Service."
    },
    ]
}

Now I retrieve the answer that has the highest score: “Every HP printer comes with at least a one-year HP commercial warranty (or HP Limited Warranty). Some models automatically benefit from a three-year warranty, which is the case of the HP Color LaserJet Plus, the HP Color LaserJet Pro, and the HP Color LaserJet Expert.”

This response is correct but it is not very user friendly since the user needs to read quite a long piece of text in order to get the answer. So now I ask the same question again to my question answering endpoint, using the GPT-J model. I will use the semantic search response as a context:

import nlpcloud

client = nlpcloud.Client("fast-gpt-j", "<your API token>", gpu=True)
client.question(
    """How long is the warranty on the HP Color LaserJet Pro?""",
    context="""Every HP printer comes with at least a one-year HP commercial warranty (or HP Limited Warranty). Some models automatically benefit from a three-year warranty, which is the case of the HP Color LaserJet Plus, the HP Color LaserJet Pro, and the HP Color LaserJet Expert."""
)

It returns the following answer:

{
    "answer": "Three years"
}

Pretty good isn’t it?

Conclusion

Despite the recent progress made on Transformer-based AI models like GPT-J, GPT-3, etc. the limited request size makes it impossible to use these great models on specific domain knowledge for question answering. Fine-tuning these models does not always work well for such a use case unfortunately…

A good strategy is to first answer your question with your own semantic search model trained on large documents, and then use a regular question answering model in order to return a human answer to the initial question.