import gradio as gr import torch from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("AIDC-AI/Marco-o1") model = AutoModelForCausalLM.from_pretrained("AIDC-AI/Marco-o1") def load_model_and_tokenizer(path): tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True).to('cuda:0') model.eval() return tokenizer, model def generate_response(model, tokenizer, input_ids, attention_mask, max_new_tokens=4096): generated_ids = input_ids with torch.inference_mode(): for _ in range(max_new_tokens): outputs = model(input_ids=generated_ids, attention_mask=attention_mask) next_token_id = torch.argmax(outputs.logits[:, -1, :], dim=-1).unsqueeze(-1) generated_ids = torch.cat([generated_ids, next_token_id], dim=-1) attention_mask = torch.cat([attention_mask, torch.ones_like(next_token_id)], dim=-1) new_token = tokenizer.decode(next_token_id.squeeze(), skip_special_tokens=True) print(new_token, end='', flush=True) if next_token_id.item() == tokenizer.eos_token_id: break return tokenizer.decode(generated_ids[0][input_ids.shape[-1]:], skip_special_tokens=True) def respond( message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, ): messages = [{"role": "system", "content": system_message}] for val in history: if val[0]: messages.append({"role": "user", "content": val[0]}) if val[1]: messages.append({"role": "assistant", "content": val[1]}) messages.append({"role": "user", "content": message}) text = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=True) model_inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=4096).to('cuda:0') yield generate_response(model, tokenizer, model_inputs.input_ids, model_inputs.attention_mask) """ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface """ demo = gr.ChatInterface( respond, additional_inputs=[ gr.Textbox(value="You are a friendly Chatbot.", label="System message"), gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)", ), ], ) if __name__ == "__main__": demo.launch()