Upload 2 files
Browse filesFiles changed (2)
- app_model.pyAdded+116
- requirements.txtAdded+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116#Gardio to create user interface for chat#Pytorch for model porcessing#Pretrained language model and tokenizer#spaces imported to manage GPU memoryimport gradio as grimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer#code addition to handle memery offloadingfrom accelerate import Acceleratorimport spaces
accelerator = Accelerator()'''import spacesMPS (metal Performance Shaders) uses in bfloat16 (torch_dtype) for its low memory usage, quicker inference - which is supported by GPU.if a lower float version is used then device can maintain to cpu without issuesin Original code: "cuda" if torch.cuda.is_available() else "cpu"alterative: "mps" if torch.backends.mps.is_available() else "cpu"if no MPS is used then just use device = 'cpu'I am suing accelerator's device management'''device = accelerator.device
#model used: from transformers library - example used is Qwen/Qwen2–0.5B-Instruct#The tokenizer is loaded to convert the user’s input into a form that the model can understand (tokenization).model = AutoModelForCausalLM.from_pretrained( "Qwen/Qwen2-0.5B-Instruct", torch_dtype=torch.float32, #changed from auto to float32 for my mac compatibility device_map='auto' #can change from auto to none to avoid automatic offloading to cpu) #.to(device)tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
#code addition to handle model placement: instead of .to(device) use the accelerator.prepare to ensure #that the model and data are on the right devices for distributed training or inference.model = accelerator.prepare(model)
#decorator used to signal that the subsequent function “def chatbot()” can use GPU memory@spaces.GPU
#assigning role to chatbot with system message, and message definition. Also checks for history (previous messages)def chatbot(user_input, history): system_message = {"role": "system", "content": "You are a helpful assistant."} messages = history + [{"role": "user", "content": user_input}] if len(history) == 0: messages.insert(0, system_message) text = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True )
#prepared text is converted into tokens the model understands (model_input) and resulting 'pt' is moved to device (CPU/GPU)#the 'important' part of the input is signaled with attention_marsk but in this case it is all input - thats why useing torch.ones model_inputs = tokenizer([text], return_tensors="pt").to(device) attention_mask = torch.ones(model_inputs.input_ids.shape, device=device)
#input forms the base that the model will generate in generated_ids. Set limit for maximum tokens produced in accordance to memory space#the generated text will be converted back into a readable text entered into response#gradio app only understands certain format so to store this new response into chat history we transfer all to gradio_history generated_ids = model.generate( model_inputs.input_ids, attention_mask=attention_mask, max_new_tokens=512 )
generated_ids = [ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) ]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
history.append({"role": "user", "content": user_input}) history.append({"role": "assistant", "content": response}) gradio_history = [[msg["role"], msg["content"]] for msg in history]
return gradio_history, history
#user interface of Gradio web app is created structured in blocks. #containing typical chatbot setting, with history saved and textbox to make entries#If the user makes an input “txt.sumit()”, the function “chatbot()” is called and the output is displayed in the chat window “chatbot_interface”
with gr.Blocks() as demo: chatbot_interface = gr.Chatbot() state = gr.State([])
with gr.Row(): txt = gr.Textbox(show_label=False, placeholder="Gib hier eine Nachricht ein...") txt.submit(chatbot, [txt, state], [chatbot_interface, state])
demo.launch(share=True)
'''this version opens the website but is in german and eror occurs when trying to enter any input. '''
1234gradiotrochtransformersaccelerateapp_model.pyAdded+116
requirements.txtAdded+4