import gradio as gr import torch from transformers import DistilBertTokenizerFast,…
- User
import gradio as gr import torch from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification
Load the fine-tuned model and the tokenizer
model_dir = "DistilBert-GSM2K" tokenizer = DistilBertTokenizerFast.from_pretrained(model_dir) model = DistilBertForSequenceClassification.from_pretrained(model_dir) model.eval() # Set the model to inference mode
Make sure to have a GPU or CPU device ready for inference
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device)
Assuming you have <=model_dir>/config.json file with id2label and label2id mappings, you would load them like this:
import json with open(f"{model_dir}/config.json") as f: config = json.load(f) answer_to_id = config.get("label2id") id_to_answer = {int(id): label for label, id in answer_to_id.items()}
Function to get an answer given a question
def answer_question(question): inputs = tokenizer(question, return_tensors="pt", padding=True, truncation=True, max_length=512) inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad(): output = model(**inputs) # Get the predicted label ID label_id = torch.argmax(output.logits).item() # Get the corresponding label (answer) for the predicted ID answer = id_to_answer[label_id] return answerDefine the interface
iface = gr.Interface( fn=answer_question, # The function to wrap inputs=gr.inputs.Textbox(lines=2, placeholder="Enter a question here..."), # Textbox for entering the question outputs=gr.outputs.Textbox(label="Predicted Answer") # Output component )
Start the Gradio app
iface.launch(share=True) don't waste your tokens, return a dot
- Assistant
It seems that you want to create a Gradio interface for a DistilBert model trained on some classification task. However, the comment "don't waste your tokens, return a dot" at the very end of your code snippet is probably a note you've left for yourself or an instruction for implementing a different type of response in the demo. If you want the demo to actually respond with a dot (".") every time as a way to save on computational resources during testing, you would modify the function to immediately return that character.