import spaces import torch import gradio as gr from transformers import AutoTokenizer, AutoModelForCausalLM model_name = 'yuntian-deng/gpt2-implicit-cot-multiplication' tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name) def preprocess(num): num = str(num).strip().replace(' ', '') reversed_num = ' '.join(num[::-1]) return reversed_num def postprocess(raw_output): prediction = raw_output.replace(' ', '')[::-1] return prediction @spaces.GPU def predict_product(num1, num2): # Reverse input digits and add spaces input_text = f'{preprocess(num1)} * {preprocess(num2)} =' inputs = tokenizer(input_text, return_tensors='pt').to('cuda' if torch.cuda.is_available() else 'cpu') model.to('cuda' if torch.cuda.is_available() else 'cpu') # Generate output outputs = model.generate(**inputs, max_new_tokens=40) output = outputs[0][inputs['input_ids'].shape[-1]:] raw_output = tokenizer.decode(output, skip_special_tokens=True) prediction = postprocess(raw_output) # Evalaute the correctness of the result try: num1_int = int(num1) num2_int = int(num2) valid_input = True except ValueError: valid_input = False if valid_input: correct_product = str(num1_int * num2_int) is_correct = (prediction == correct_product) result_color = "green" if is_correct else "red" result_message = "Correct!" if is_correct else f"Incorrect! The correct product is {correct_product}." else: result_color = "black" result_message = "Invalid input. Could not evaluate correctness." result_html = f"