tangzhy commited on
Commit
c0766e6
·
verified ·
1 Parent(s): 027f332

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -36
app.py CHANGED
@@ -8,28 +8,24 @@ import torch
8
  from transformers import (
9
  AutoModelForCausalLM,
10
  BitsAndBytesConfig,
11
- GemmaTokenizerFast,
12
  TextIteratorStreamer,
13
  )
14
 
15
  DESCRIPTION = """\
16
- # Gemma 2 9B IT
17
 
18
- Gemma 2 is Google's latest iteration of open LLMs.
19
- This is a demo of [`google/gemma-2-9b-it`](https://huggingface.co/google/gemma-2-9b-it), fine-tuned for instruction following.
20
- For more details, please check [our post](https://huggingface.co/blog/gemma2).
21
-
22
- 👉 Looking for a larger and more powerful version? Try the 27B version in [HuggingChat](https://huggingface.co/chat/models/google/gemma-2-27b-it).
23
  """
24
 
25
- MAX_MAX_NEW_TOKENS = 2048
26
- DEFAULT_MAX_NEW_TOKENS = 1024
27
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
28
 
29
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
30
 
31
- model_id = "google/gemma-2-9b-it"
32
- tokenizer = GemmaTokenizerFast.from_pretrained(model_id)
33
  model = AutoModelForCausalLM.from_pretrained(
34
  model_id,
35
  device_map="auto",
@@ -39,7 +35,7 @@ model.config.sliding_window = 4096
39
  model.eval()
40
 
41
 
42
- @spaces.GPU(duration=90)
43
  def generate(
44
  message: str,
45
  chat_history: list[tuple[str, str]],
@@ -49,20 +45,11 @@ def generate(
49
  top_k: int = 50,
50
  repetition_penalty: float = 1.2,
51
  ) -> Iterator[str]:
52
- conversation = []
53
- for user, assistant in chat_history:
54
- conversation.extend(
55
- [
56
- {"role": "user", "content": user},
57
- {"role": "assistant", "content": assistant},
58
- ]
59
- )
60
- conversation.append({"role": "user", "content": message})
61
 
62
- input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
63
- if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
64
- input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
65
- gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
66
  input_ids = input_ids.to(model.device)
67
 
68
  streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
@@ -70,7 +57,7 @@ def generate(
70
  {"input_ids": input_ids},
71
  streamer=streamer,
72
  max_new_tokens=max_new_tokens,
73
- do_sample=True,
74
  top_p=top_p,
75
  top_k=top_k,
76
  temperature=temperature,
@@ -83,7 +70,9 @@ def generate(
83
  outputs = []
84
  for text in streamer:
85
  outputs.append(text)
86
- yield "".join(outputs)
 
 
87
 
88
 
89
  chat_interface = gr.ChatInterface(
@@ -98,17 +87,17 @@ chat_interface = gr.ChatInterface(
98
  ),
99
  gr.Slider(
100
  label="Temperature",
101
- minimum=0.1,
102
  maximum=4.0,
103
  step=0.1,
104
- value=0.6,
105
  ),
106
  gr.Slider(
107
  label="Top-p (nucleus sampling)",
108
  minimum=0.05,
109
  maximum=1.0,
110
  step=0.05,
111
- value=0.9,
112
  ),
113
  gr.Slider(
114
  label="Top-k",
@@ -127,17 +116,15 @@ chat_interface = gr.ChatInterface(
127
  ],
128
  stop_btn=None,
129
  examples=[
130
- ["Hello there! How are you doing?"],
131
- ["Can you explain briefly to me what is the Python programming language?"],
132
- ["Explain the plot of Cinderella in a sentence."],
133
- ["How many hours does it take a man to eat a Helicopter?"],
134
- ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
135
  ],
136
  )
137
 
138
  with gr.Blocks(css="style.css", fill_height=True) as demo:
139
  gr.Markdown(DESCRIPTION)
140
- gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
141
  chat_interface.render()
142
 
143
  if __name__ == "__main__":
 
8
  from transformers import (
9
  AutoModelForCausalLM,
10
  BitsAndBytesConfig,
11
+ AutoTokenizer,
12
  TextIteratorStreamer,
13
  )
14
 
15
  DESCRIPTION = """\
16
+ # ORLM LLaMA-3-8B
17
 
18
+ Hello! I'm ORLM-LLaMA-3-8B, here to automate your optimization modeling tasks! Check our [paper](https://arxiv.org/abs/2405.17743)!
 
 
 
 
19
  """
20
 
21
+ MAX_MAX_NEW_TOKENS = 4096
22
+ DEFAULT_MAX_NEW_TOKENS = 4096
23
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
24
 
25
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
26
 
27
+ model_id = "CardinalOperations/ORLM-LLaMA-3-8B"
28
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
29
  model = AutoModelForCausalLM.from_pretrained(
30
  model_id,
31
  device_map="auto",
 
35
  model.eval()
36
 
37
 
38
+ @spaces.GPU(duration=120)
39
  def generate(
40
  message: str,
41
  chat_history: list[tuple[str, str]],
 
45
  top_k: int = 50,
46
  repetition_penalty: float = 1.2,
47
  ) -> Iterator[str]:
48
+ if chat_history != []:
49
+ yield "Sorry, I am an instruction-tuned model and currently do not support chatting. Please try clearing the chat history or refreshing the page to ask a new question."
 
 
 
 
 
 
 
50
 
51
+ tokenized_example = tokenizer(message, return_tensors='pt', max_length=MAX_INPUT_TOKEN_LENGTH, truncation=True)
52
+ input_ids = tokenized_example.input_ids
 
 
53
  input_ids = input_ids.to(model.device)
54
 
55
  streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
 
57
  {"input_ids": input_ids},
58
  streamer=streamer,
59
  max_new_tokens=max_new_tokens,
60
+ do_sample=False if temperature == 0.0 else True,
61
  top_p=top_p,
62
  top_k=top_k,
63
  temperature=temperature,
 
70
  outputs = []
71
  for text in streamer:
72
  outputs.append(text)
73
+ to_yield = "".join(outputs)
74
+ to_yield += "\n\nI have now attempted to solve the optimization modeling task! Please try executing the code in your environment, making sure it is equipped with `coptpy`."
75
+ yield to_yield
76
 
77
 
78
  chat_interface = gr.ChatInterface(
 
87
  ),
88
  gr.Slider(
89
  label="Temperature",
90
+ minimum=0.0,
91
  maximum=4.0,
92
  step=0.1,
93
+ value=0.0,
94
  ),
95
  gr.Slider(
96
  label="Top-p (nucleus sampling)",
97
  minimum=0.05,
98
  maximum=1.0,
99
  step=0.05,
100
+ value=1.0,
101
  ),
102
  gr.Slider(
103
  label="Top-k",
 
116
  ],
117
  stop_btn=None,
118
  examples=[
119
+ ["Below is an operations research question. Build a mathematical model and corresponding python code using `coptpy` that appropriately addresses the question.\n\n# Question:\nA lab has 1000 units of medicinal ingredients to make two pills, a large pill and a small pill. A large pill requires 3 units of medicinal ingredients and 2 units of filler. A small pill requires 2 units of medicinal ingredients and 1 unit of filler. The lab has to make at least 100 large pills. However, since small pills are more popular at least 60% of the total number of pills must be small. How many of each should be made to minimize the total number of filler material needed?\n\n# Response:"],
120
+ ["Below is an operations research question. Build a mathematical model and corresponding python code using `coptpy` that appropriately addresses the question.\n\n# Question:\nLet's say you're on a mission to create the perfect meal plan for yourself. You're focused on getting the right balance of nutrients without digging too deep into your pockets. You have six different food options to consider: Chicken, Oats, Tofu, Rice, Beef, and Salmon. Each of these foods provides a certain amount of protein, carbohydrates, and calories, and they all come with their own distinct prices.\n\nHere's a detailed breakdown of the nutritional content and cost of each food item:\n\n- Chicken: Delivers 14 grams of protein, a single gram of carbohydrates, and 164 calories at a cost of $6.\n- Oats: Gives you 11 grams of protein, 6 grams of carbohydrates, and 210 calories for just $2.\n- Tofu: Offers 8 grams of protein, 12 grams of carbohydrates, and 98 calories at a cost of $9.\n- Rice: Provides 1 gram of protein, a generous 17 grams of carbohydrates, and 92 calories for $3.\n- Beef: Comes packed with 16 grams of protein, 11 grams of carbohydrates, and 211 calories, priced at $7.\n- Salmon: Brings a hefty 19 grams of protein, 13 grams of carbohydrates, and 211 calories but costs $9.\n\nYou want to make sure your meal plan meets the following nutritional targets: at least 70 grams of protein, 117 grams of carbohydrates, and 1837 calories. Considering these six foods, what is the least amount of money you need to spend to meet these dietary needs?\nRemember, your response should only contain the optimal value of the cost to meet the requirements.\n\n# Response:"],
121
+ ["Below is an operations research question. Build a mathematical model and corresponding python code using `coptpy` that appropriately addresses the question.\n\n# Question:\nHaus Toys can manufacture and sell toy trucks, toy planes, toy boats, and toy trains. The profit from selling one truck is $5, from one plane is $10, from one boat is $8, and from one train is $7. How many types of toys should Haus Toys manufacture to maximize profit?\n\nThere are 890 units of wood available. Manufacturing one truck requires 12 units of wood, one plane requires 20 units of wood, one boat requires 15 units of wood, and one train requires 10 units of wood.\n\nThere are 500 units of steel available. Manufacturing one plane requires 3 units of steel, one boat requires 5 units of steel, one train requires 4 units of steel, and one truck requires 6 units of steel.\n\nIf Haus Toys manufactures trucks, then they will not manufacture trains.\n\nHowever, if they manufacture boats, they will also manufacture planes.\n\nThe number of toy boats manufactured cannot exceed the number of toy trains manufactured.\n\n# Response:"],
 
 
122
  ],
123
  )
124
 
125
  with gr.Blocks(css="style.css", fill_height=True) as demo:
126
  gr.Markdown(DESCRIPTION)
127
+ # gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
128
  chat_interface.render()
129
 
130
  if __name__ == "__main__":