iTranslated by AI
Fine-tuning the rinna Generative AI Model and Publishing a Demo
Introduction
I have successfully finished the Generative AI Passport exam! Since the results will be out in two months, I'll wait patiently for them.
Now that I've put in the effort to study Generative AI and machine learning, I wanted to actually run models locally and try creating my own custom model by training publicly available models with datasets.
However, my current iMac is not well-suited for developing Generative AI, so I can't do anything very large-scale. Still, I really wanted to give it a try, so I decided to go through the entire process from fine-tuning a model to creating and publishing my own!
Execution Environment
My thoughts after trying it out were:
- Choosing the smallest model size was definitely the right call
- It was difficult to create a dataset and fine-tune it in a way that fit the chosen text generation model
- I was surprised at how quickly I could publish my custom model and create a demo!
Now, let me introduce the workflow from fine-tuning a public model to publishing a demo!
The goal is to create a business-oriented text generation AI and publish a demo app!
First, I'll set a goal for what I want to create. This time, I will try building a bot by tuning the smallest size of the Rinna text generation model for business use.
The rinna model I used this time is here: Rinna is under the MIT license, so it can also be used commercially!
Fine-tuning the Model Locally
I will proceed with fine-tuning by loading a dataset of about 100 business-related Q&A pairs prepared in a CSV file. Although the amount of data is small because I'm starting with the minimum requirements, I'll continue to learn the workflow of creating a custom model.
I had ChatGPT write all the code for me. Through repeated trial and error, I ended up with some good code.
from transformers import Trainer, TrainingArguments
from transformers import AutoTokenizer, AutoModelForCausalLM
import pandas as pd
from datasets import Dataset
# First, load the tokenizer. In this example, "rinna/japanese-gpt2-xsmall" is used
tokenizer = AutoTokenizer.from_pretrained("rinna/japanese-gpt2-xsmall")
# Load data from the CSV file.
data = pd.read_csv('data.csv')
# Convert from a pandas DataFrame to a Hugging Face dataset.
dataset = Dataset.from_pandas(data)
def add_prompt_and_format(example):
example = f"入力:\n{example['input']}\n\n出力:\n{example['output']}"
example = example.replace("\n", "<NL>")
# input and output tokens need to match for causal language models
encoded_example = tokenizer.encode_plus(
example,
truncation=True,
max_length=512, # Specify the maximum length here. Adjust as needed
padding='max_length',
)
return {"input_ids": encoded_example['input_ids'],
"attention_mask": encoded_example['attention_mask'],
"labels": encoded_example['input_ids']} # Since it's a causal LM, use input IDs directly as labels
# Add a fixed prompt
fixed_prompt = "あなたは優秀なビジネスマンです。以下、部下にアドバイスを送ってください。: \n\n"
dataset = dataset.map(lambda example: {"input": fixed_prompt + ''.join(example["input"])})
tokenized_dataset = dataset.map(add_prompt_and_format)
# Load the "rinna/japanese-gpt2-xsmall" model.
model = AutoModelForCausalLM.from_pretrained("rinna/japanese-gpt2-xsmall")
# Set up the trainer.
training_args = TrainingArguments(output_dir="trainer", num_train_epochs=1, per_device_train_batch_size=1, gradient_accumulation_steps=2)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
)
# Start training.
trainer.train()
# Save the trained model.
trainer.save_model("my_model_directory")
Once execution is finished, your custom model will be created in a directory named "my_model_directory"!
Testing the Custom Model Locally
Once the custom model is ready, let's have it perform inference based on an input!
I also had ChatGPT write the code for this part, and it turned out quite well.
from transformers import AutoTokenizer, AutoModelForCausalLM
# Load the model and tokenizer
model = AutoModelForCausalLM.from_pretrained("my_model_directory")
tokenizer = AutoTokenizer.from_pretrained("my_model_directory")
# Input text
text = "どうしたら仕事が早くできるようになりますか?"
# Tokenize the input text
inputs = tokenizer.encode(text, return_tensors='pt')
# Generate a prediction
outputs = model.generate(inputs, max_length=300, temperature=0.9, do_sample=True)
# Decode the prediction (convert tokens back to text)
predicted_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(predicted_text)
Publishing the Model to Hugging Face
Once testing is complete, upload the model to the Hugging Face Hub to make it public.
The documentation can be found here:
I will commit the custom model locally and push it to Hugging Face.
If you have basic knowledge of Git, it’s incredibly simple.
Detailed steps can be found below:
The model upload was finished in no time!
Here is the model I created this time:
Next, I will create a demo app using the uploaded model.
Publishing a Model Demo on Hugging Face Spaces
You can easily create and publish demos using models hosted on Hugging Face.
Check out the various apps available to try out here:
Now, let's create a demo page on Spaces using the custom model we just made.
We'll need two files: app.py, which is the base of the app, and requirements.txt, which lists the necessary libraries.
# Import transformers, torch, and Gradio
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import gradio as gr
# Load the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("yasunamiura/mr-ja")
model = AutoModelForCausalLM.from_pretrained("yasunamiura/mr-ja")
# Function that takes text input and uses it to generate new text
def generate(prompt):
# Tokenize the input text
inputs = tokenizer.encode(prompt, return_tensors='pt')
# Generate new text using the tokenized text
outputs = model.generate(inputs, max_length=300, temperature=1.0, top_k=50, top_p=0.95, do_sample=True)
# Decode the generated text
predicted_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Return the decoded text from the function
return predicted_text
# Create Gradio UI
iface = gr.Interface(
# Use the text generation function defined above
generate,
# Use a text box for input
inputs = gr.Textbox(label = "Input a question", default = "質問してください"),
# Output as text
outputs="text",
# UI title setting
title = "Mr Bot🤖")
# Launch the Gradio UI
iface.launch()
tensorflow
transformers
torch
sentencepiece
The app is built with just this much code. It's truly simple.
This time, I published the text generation AI demo app under the name "Mr Bot." Since I set the CPU size for running the demo to the minimum free tier, there are no costs involved.
Now, let's try out the demo app immediately.

Oh?? It surprisingly gave advice aimed at me as someone currently raising a child—it's a coincidence, but it makes me happy (lol).
I was able to go from creating a custom model to publishing it in just three days! This is quite interesting!
Summary
In this post, I shared the process of fine-tuning the rinna model to create a custom model and publishing a demo app!
To be honest, the amount of data was so insufficient that it felt like adding a fixed prompt to the input had more of an impact than the actual fine-tuning (lol).
I've started wanting a powerful Windows PC to further master generative AI.
I'm happy that I could go all the way from creating a custom model to publishing an app, so I will continue my studies!
Discussion