Spaces:
Runtime error
Runtime error
Benjamin Gonzalez commited on
Commit ·
c4f947a
1
Parent(s): 62a0c90
try to implement streaming
Browse files123457 unmodified lines13141516171819202122233 unmodified lines2728293031323316 unmodified lines505152535455import torchfrom transformers import AutoTokenizer, AutoModelForCausalLMimport gradio as grif torch.cuda.is_available():7 unmodified lines)def generate(prompt, length):inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=False)input_token_len = len(inputs.tokens())outputs = model.generate(**inputs, max_length=length if length >= input_token_len else input_token_len)return tokenizer.batch_decode(outputs)[0]demo = gr.Interface(3 unmodified lineslabel="prompt",value="Write a detailed analogy between mathematics and a lighthouse.",),gr.Number(value=100, label="max length", maximum=500),],outputs="text",examples=[16 unmodified lines"""\n''',100,],],title="Microsoft Phi-2",description="Unofficial demo of Microsoft Phi-2, a high performing model with only 2.7B parameters.",12345678910117 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556573 unmodified lines6162636465666716 unmodified lines848586878889909192import torchfrom transformers import (AutoTokenizer,AutoModelForCausalLM,TextIteratorStreamer,StoppingCriteriaList,)from threading import Threadimport gradio as grif torch.cuda.is_available():7 unmodified lines)def Phi2StoppingCriteria(input_ids: torch.LongTensor, score: torch.FloatTensor, **kwargs) -> bool:stop_list = ["Exercise", "Exercises", "<|endoftext|>"]stop_tokens = []for stop in stop_list:stop_tokens.append(tokenizer(stop, add_special_tokens=False, return_tensors="pt").input_ids)return input_ids[-1] in stop_tokensstopping_criteria = StoppingCriteriaList([Phi2StoppingCriteria])def generate(prompt, max_new_tokens):inputs = tokenizer(prompt, return_tensors="pt")# thanks https://huggingface.co/spaces/joaogante/transformers_streaming/blob/main/app.pystreamer = TextIteratorStreamer(inputs)generation_kwargs = dict(inputs,streamer=streamer,max_new_tokens=max_new_tokens,do_sample=True,stopping_criteria=stopping_criteria,)thread = Thread(target=model.generate, kwargs=generation_kwargs)thread.start()model_output = ""for new_text in streamer:model_output += new_textyield model_outputreturn model_outputdemo = gr.Interface(3 unmodified lineslabel="prompt",value="Write a detailed analogy between mathematics and a lighthouse.",),gr.Number(value=100, label="max new tokens", maximum=500),],outputs="text",examples=[16 unmodified lines"""\n''',100,],["User: How does sleep affect mood?\nAI:", 125],["Who was Ada Lovelace?", 100],["Explain the concept of skip lists.", 125],],title="Microsoft Phi-2",description="Unofficial demo of Microsoft Phi-2, a high performing model with only 2.7B parameters.",
app.py+44-7