awinml commited on
Commit
6627aee
1 Parent(s): 94a67ea

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +97 -27
  2. utils.py +101 -15
app.py CHANGED
@@ -12,8 +12,15 @@ from utils import (
12
  create_sparse_embeddings,
13
  extract_entities,
14
  format_query,
15
- generate_flant5_prompt,
 
 
 
 
 
16
  generate_gpt_prompt,
 
 
17
  get_context_list_prompt,
18
  get_data,
19
  get_flan_t5_model,
@@ -46,9 +53,9 @@ spacy_model = get_spacy_model()
46
 
47
  with col1:
48
  st.subheader("Question")
49
- query_text = st.text_input(
50
  "Input Query",
51
- value="What was discussed regarding Wearables revenue performance in Q1 2020?",
52
  )
53
 
54
  company_ent, quarter_ent, year_ent = extract_entities(query_text, spacy_model)
@@ -60,12 +67,26 @@ with col1:
60
  years_choice = ["2020", "2019", "2018", "2017", "2016", "All"]
61
 
62
  with col1:
63
- year = st.selectbox("Year", years_choice, index=year_index)
 
 
 
 
 
 
 
64
 
65
  with col1:
66
- quarter = st.selectbox(
67
- "Quarter", ["Q1", "Q2", "Q3", "Q4", "All"], index=quarter_index
68
- )
 
 
 
 
 
 
 
69
 
70
  with col1:
71
  participant_type = st.selectbox("Speaker", ["Company Speaker", "Analyst"])
@@ -84,7 +105,14 @@ ticker_choice = [
84
  ]
85
 
86
  with col1:
87
- ticker = st.selectbox("Company", ticker_choice, ticker_index)
 
 
 
 
 
 
 
88
 
89
  with st.sidebar:
90
  st.subheader("Select Options:")
@@ -104,11 +132,7 @@ with st.sidebar:
104
 
105
  # Choose decoder model
106
 
107
- decoder_models_choice = [
108
- "GPT3 - (text-davinci-003)",
109
- "T5",
110
- "FLAN-T5",
111
- ]
112
 
113
  with st.sidebar:
114
  decoder_model = st.selectbox("Select Decoder Model", decoder_models_choice)
@@ -227,7 +251,7 @@ if decoder_model == "GPT3 - (text-davinci-003)":
227
 
228
 
229
  elif decoder_model == "T5":
230
- prompt = generate_flant5_prompt(query_text, context_list)
231
  t5_pipeline = get_t5_model()
232
  output_text = []
233
  with col2:
@@ -247,27 +271,73 @@ elif decoder_model == "T5":
247
  st.markdown(f"- {text}")
248
 
249
  elif decoder_model == "FLAN-T5":
250
- prompt = generate_flant5_prompt(query_text, context_list)
251
- flan_t5_pipeline = get_flan_t5_model()
252
  output_text = []
253
  with col2:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  with st.form("my_form"):
255
  edited_prompt = st.text_area(
256
  label="Model Prompt", value=prompt, height=270
257
  )
258
- context_list = get_context_list_prompt(edited_prompt)
259
  submitted = st.form_submit_button("Submit")
260
  if submitted:
261
- for context_text in context_list:
262
- output_text.append(
263
- flan_t5_pipeline("Summarize: " + context_text)[0][
264
- "summary_text"
265
- ]
266
- )
267
- st.subheader("Answer:")
268
- for text in output_text:
269
- if "(iii)" not in text:
270
- st.markdown(f"- {text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
 
273
  with col1:
 
12
  create_sparse_embeddings,
13
  extract_entities,
14
  format_query,
15
+ generate_flant5_prompt_instruct_chunk_context,
16
+ generate_flant5_prompt_instruct_complete_context,
17
+ generate_flant5_prompt_instruct_chunk_context_single,
18
+ generate_flant5_prompt_summ_chunk_context_single,
19
+ generate_flant5_prompt_summ_chunk_context,
20
+ generate_text_flan_t5,
21
  generate_gpt_prompt,
22
+ generate_gpt_j_two_shot_prompt_1,
23
+ generate_gpt_j_two_shot_prompt_2,
24
  get_context_list_prompt,
25
  get_data,
26
  get_flan_t5_model,
 
53
 
54
  with col1:
55
  st.subheader("Question")
56
+ query_text = st.text_area(
57
  "Input Query",
58
+ value="What was discussed regarding Wearables revenue performance?",
59
  )
60
 
61
  company_ent, quarter_ent, year_ent = extract_entities(query_text, spacy_model)
 
67
  years_choice = ["2020", "2019", "2018", "2017", "2016", "All"]
68
 
69
  with col1:
70
+ # Hardcoding the defaults for a question without metadata
71
+ if (
72
+ query_text
73
+ == "What was discussed regarding Wearables revenue performance?"
74
+ ):
75
+ year = st.selectbox("Year", years_choice)
76
+ else:
77
+ year = st.selectbox("Year", years_choice, index=year_index)
78
 
79
  with col1:
80
+ # Hardcoding the defaults for a question without metadata
81
+ if (
82
+ query_text
83
+ == "What was discussed regarding Wearables revenue performance?"
84
+ ):
85
+ quarter = st.selectbox("Quarter", ["Q1", "Q2", "Q3", "Q4", "All"])
86
+ else:
87
+ quarter = st.selectbox(
88
+ "Quarter", ["Q1", "Q2", "Q3", "Q4", "All"], index=quarter_index
89
+ )
90
 
91
  with col1:
92
  participant_type = st.selectbox("Speaker", ["Company Speaker", "Analyst"])
 
105
  ]
106
 
107
  with col1:
108
+ # Hardcoding the defaults for a question without metadata
109
+ if (
110
+ query_text
111
+ == "What was discussed regarding Wearables revenue performance?"
112
+ ):
113
+ ticker = st.selectbox("Company", ticker_choice)
114
+ else:
115
+ ticker = st.selectbox("Company", ticker_choice, ticker_index)
116
 
117
  with st.sidebar:
118
  st.subheader("Select Options:")
 
132
 
133
  # Choose decoder model
134
 
135
+ decoder_models_choice = ["GPT3 - (text-davinci-003)", "T5", "FLAN-T5", "GPT-J"]
 
 
 
 
136
 
137
  with st.sidebar:
138
  decoder_model = st.selectbox("Select Decoder Model", decoder_models_choice)
 
251
 
252
 
253
  elif decoder_model == "T5":
254
+ prompt = generate_flant5_prompt_instruct_complete_context(query_text, context_list)
255
  t5_pipeline = get_t5_model()
256
  output_text = []
257
  with col2:
 
271
  st.markdown(f"- {text}")
272
 
273
  elif decoder_model == "FLAN-T5":
274
+ flan_t5_model, flan_t5_tokenizer = get_flan_t5_model()
 
275
  output_text = []
276
  with col2:
277
+ prompt_type = st.selectbox(
278
+ "Select prompt type", ["Complete Text QA", "Chunkwise QA", "Chunkwise Summarize"]
279
+ )
280
+ if prompt_type == "Complete Text QA":
281
+ prompt = generate_flant5_prompt_instruct_complete_context(
282
+ query_text, context_list
283
+ )
284
+ elif prompt_type == "Chunkwise QA":
285
+ st.write("The following prompt is not editable.")
286
+ prompt = generate_flant5_prompt_instruct_chunk_context(
287
+ query_text, context_list
288
+ )
289
+ elif prompt_type == "Chunkwise Summarize":
290
+ st.write("The following prompt is not editable.")
291
+ prompt = generate_flant5_prompt_summ_chunk_context(
292
+ query_text, context_list
293
+ )
294
+ else:
295
+ prompt = ""
296
  with st.form("my_form"):
297
  edited_prompt = st.text_area(
298
  label="Model Prompt", value=prompt, height=270
299
  )
 
300
  submitted = st.form_submit_button("Submit")
301
  if submitted:
302
+ if prompt_type == "Complete Text QA":
303
+ output_text_string = generate_text_flan_t5(flan_t5_model, flan_t5_tokenizer, prompt)
304
+ st.subheader("Answer:")
305
+ st.write(output_text_string)
306
+ elif prompt_type == "Chunkwise QA":
307
+ for context_text in context_list:
308
+ model_input = generate_flant5_prompt_instruct_chunk_context_single(query_text, context_text)
309
+ output_text.append(
310
+ generate_text_flan_t5(flan_t5_model, flan_t5_tokenizer, model_input))
311
+ st.subheader("Answer:")
312
+ for text in output_text:
313
+ if "(iii)" not in text:
314
+ st.markdown(f"- {text}")
315
+ elif prompt_type == "Chunkwise Summarize":
316
+ for context_text in context_list:
317
+ model_input = generate_flant5_prompt_summ_chunk_context_single(query_text, context_text)
318
+ output_text.append(
319
+ generate_text_flan_t5(flan_t5_model, flan_t5_tokenizer, model_input))
320
+ st.subheader("Answer:")
321
+ for text in output_text:
322
+ if "(iii)" not in text:
323
+ st.markdown(f"- {text}")
324
+
325
+ if decoder_model == "GPT-J":
326
+ if ticker in ["AAPL", "AMD"]:
327
+ prompt = generate_gpt_j_two_shot_prompt_1(query_text, context_list)
328
+ elif ticker in ["NVDA", "INTC", "AMZN"]:
329
+ prompt = generate_gpt_j_two_shot_prompt_2(query_text, context_list)
330
+ else:
331
+ prompt = generate_gpt_j_two_shot_prompt_1(query_text, context_list)
332
+ with col2:
333
+ with st.form("my_form"):
334
+ edited_prompt = st.text_area(
335
+ label="Model Prompt", value=prompt, height=270
336
+ )
337
+ st.write(
338
+ "The app currently just shows the prompt. The app does not load the model due to memory limitations."
339
+ )
340
+ submitted = st.form_submit_button("Submit")
341
 
342
 
343
  with col1:
utils.py CHANGED
@@ -14,6 +14,8 @@ from transformers import (
14
  AutoTokenizer,
15
  pipeline,
16
  )
 
 
17
 
18
  import streamlit as st
19
 
@@ -42,13 +44,9 @@ def get_t5_model():
42
 
43
  @st.experimental_singleton
44
  def get_flan_t5_model():
45
- return pipeline(
46
- "summarization",
47
- model="google/flan-t5-small",
48
- tokenizer="google/flan-t5-small",
49
- max_length=512,
50
- # length_penalty = 0
51
- )
52
 
53
 
54
  @st.experimental_singleton
@@ -353,17 +351,69 @@ def generate_gpt_prompt_2(query_text, context_list):
353
  return prompt
354
 
355
 
356
- def generate_flant5_prompt(query_text, context_list):
357
- context = " \n".join(context_list)
358
- prompt = f"""Given the context information and prior knowledge, answer this question:
359
- {query_text}
360
- Context information is below:
361
- ---------------------
362
- {context}
363
- ---------------------"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  return prompt
365
 
366
 
 
 
 
 
 
 
 
 
 
 
 
367
  def get_context_list_prompt(prompt):
368
  prompt_list = prompt.split("---------------------")
369
  context = prompt_list[-2].strip()
@@ -381,6 +431,42 @@ def gpt_model(prompt):
381
  return response.choices[0].text
382
 
383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  # Entity Extraction
385
 
386
 
 
14
  AutoTokenizer,
15
  pipeline,
16
  )
17
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
18
+
19
 
20
  import streamlit as st
21
 
 
44
 
45
  @st.experimental_singleton
46
  def get_flan_t5_model():
47
+ tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-large")
48
+ model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-large")
49
+ return model, tokenizer
 
 
 
 
50
 
51
 
52
  @st.experimental_singleton
 
351
  return prompt
352
 
353
 
354
+ def generate_flant5_prompt_instruct_complete_context(query_text, context_list):
355
+ context = " ".join(context_list)
356
+ prompt = f"""Answer the question in long detailed sentences using the context.
357
+ Question: {query_text}
358
+ Context: {context}
359
+ Answer: """
360
+ return prompt
361
+
362
+
363
+ def generate_flant5_prompt_instruct_chunk_context(query_text, context_list):
364
+ prompt = """"""
365
+ for chunk in context_list:
366
+ prompt_chunk = f"""Answer the question in long detailed sentences using the context.
367
+ Question: {query_text}
368
+ Context: {chunk}
369
+ Answer: """
370
+ prompt = (
371
+ prompt
372
+ + "\n"
373
+ + "---------"
374
+ + "Separate Model API Calls"
375
+ + "---------"
376
+ + "\n"
377
+ + prompt_chunk
378
+ )
379
+ return prompt
380
+
381
+
382
+ def generate_flant5_prompt_summ_chunk_context(query_text, context_list):
383
+ prompt = """"""
384
+ for chunk in context_list:
385
+ prompt_chunk = f"""Summarize: {chunk}"""
386
+ prompt = (
387
+ prompt
388
+ + "\n"
389
+ + "---------"
390
+ + "Separate Model API Calls"
391
+ + "---------"
392
+ + "\n"
393
+ + prompt_chunk
394
+ )
395
+ return prompt
396
+
397
+
398
+ def generate_flant5_prompt_instruct_chunk_context_single(query_text, chunk):
399
+ prompt = f"""Answer the question in long detailed sentences using the context.
400
+ Question: {query_text}
401
+ Context: {chunk}
402
+ Answer: """
403
  return prompt
404
 
405
 
406
+ def generate_flant5_prompt_summ_chunk_context_single(query_text, chunk):
407
+ prompt = f"""summarize: {chunk}"""
408
+ return prompt
409
+
410
+
411
+ def generate_text_flan_t5(model, tokenizer, input_text):
412
+ input_ids = tokenizer(input_text, return_tensors="pt").input_ids
413
+ outputs = model.generate(input_ids, temperature=0.5, max_length=512)
414
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
415
+
416
+
417
  def get_context_list_prompt(prompt):
418
  prompt_list = prompt.split("---------------------")
419
  context = prompt_list[-2].strip()
 
431
  return response.choices[0].text
432
 
433
 
434
+ def generate_gpt_j_two_shot_prompt_1(query_text, context_list):
435
+ context = " \n".join(context_list)
436
+ prompt = f"""Answer the Question in detail based on the Context in 7-9 descriptive and summarized sentences.
437
+
438
+ Question: What is Nvidia's visibility in the data center business?
439
+ Context: People still saw it as something esoteric. But today, data centers all over the world expect a very significant part of their data center being accelerated with GPUs. The number of workloads that we've accelerated since in the last 5 years have expanded tremendously, whether it's imaging or video or conversational AI or deep recommender systems that probably unquestionably, at this point, the most important machine learning model in the world. When we came -- when we started to introduce Ampere to the data center, it was very commonsensical to them that they would adopt it. They have a large amount of workload that's already accelerated by NVIDIA GPUs. And as you know, our GPUs are architecturally compatible from generation to generation. And I think every nation and government and scientific lab is now gearing up to think about what does it take to create a national defense system for each country that is based on computational methods? And NVIDIA is an accelerated computing company. We take something that otherwise would take a year in the case of Oak Ridge, and they filter 1 billion compounds in a day. And so notice, I've said 3 different architecture in a data center today. Most data centers today has a storage server, has CPU servers, and it has scale-up acceleration service with Voltas has scaled out servers with GeForce and then it has scale cloud computing, flexible servers based on V100. And so the ability to predict workload is so hard, and therefore, the utilization of these systems will be spiky. And then the second thing is we'd like to be able to innovate across the entire stack. You know that NVIDIA is just supremely obsessed about software stacks. And the reason for that is because software creates markets.
440
+ Answer: Nvidia has become a very significant part of the data center business in the last 5 years, with its GPUs being used to accelerate a wide range of workloads, from imaging and video to conversational AI and deep recommender systems. Data centers have been quick to adopt Nvidia's Ampere architecture, as it is architecturally compatible with previous generations of GPUs. Nvidia is also being used to create national defense systems for countries, with Oak Ridge National Laboratory using it to filter 1 billion compounds in a day. Data centers today typically have a combination of storage servers, CPU servers, and scale-up acceleration servers with Volta and GeForce, as well as scale cloud computing servers based on V100. Nvidia is focused on software stacks, as they believe software creates markets. Overall, Nvidia has become a major player in the data center business, with its GPUs being used to accelerate a wide range of workloads and its software stacks creating markets.
441
+ ###
442
+ Question: What is the update on the server chip roadmap and strategy?
443
+ Context: Navin, any... Maybe the only thing I'd add, John, is that from a product point of view, the dynamic to think about in 2019 is that, as Bob mentioned, we began shipping for production Cascade Lake, our next-generation Xeon. And really, that product is going to ramp -- start to ramp in the middle part of the year and into the second half of the year. The product features look very compelling. The AI capability we have with DL Boost, the support for Optane persistent memory, the security, hardware mitigation fixes, so that the customer momentum around that product line looks very strong. But it really doesn't ramp until the middle to the second half of the year. During the course of '19, our expectations are, of that mix, that we'll be more logic-oriented. And that's really driven by a couple of things: one, ensuring we have the capacity to meet the 14-nanometer demand for our customers; secondly, as we ramp 10-nanometer in 2019 and position for 10- in 2020, we'll invest additional capital there; and then third, obviously, our expectations are to continue to invest in next-node technology, in particular, 7-nanometer. So logic capital is going to be going up year-on-year. Again, 10-nanometer ramp, not really any different. I highlighted in the prepared remarks, we feel very good about kind of where we are in ramping 10-nanometer during the course of the year to get systems on the shelf for the holiday season, so no real change there. And modem and memory growth will be a little bit slower today versus where we were 90 days ago. I think, as Bob said, and I think we talked about a little bit, we had 3 quarters of really, really strong growth in 2018 in the cloud. And that was driven by a product cycle as well as a typical multiyear build-out pattern with Xeon Scalable. And if you look back at all the historical trends we've had in the cloud business, we've always said there's some lumpiness to the business.
444
+ Answer: Intel began shipping for production Cascade Lake, their next-generation Xeon, in 2019 and the product features look very compelling with AI capability, support for Optane persistent memory, and security hardware mitigation fixes. The product is expected to ramp up in the middle part of the year and into the second half of the year. Intel is investing in 14-nanometer capacity to meet customer demand, 10-nanometer technology for 2019 and 2020, and 7-nanometer technology. Logic capital is expected to increase year-on-year. Intel is investing in 10-nanometer technology to get systems on the shelf for the holiday season. Modem and memory growth is expected to be slower than it was 90 days ago due to the 3 quarters of strong growth in 2018 in the cloud.
445
+ ###
446
+ Question: {query_text}
447
+ Context: {context}
448
+ Answer:?"""
449
+ return prompt
450
+
451
+
452
+ def generate_gpt_j_two_shot_prompt_2(query_text, context_list):
453
+ context = " \n".join(context_list)
454
+ prompt = f"""Answer the Question in detail based on the Context in 7-9 descriptive and summarized sentences.
455
+
456
+ Question: What was discussed regarding Wearables revenue performance?
457
+ Context: Products revenue $79.1b. Up 8%, as iPhone returned to growth. Had incredibly strong results in Wearables, where Co. set all-time records for Apple Watch and AirPods. Services revenue grew 17% to new all-time record $12.7b with double-digit growth in every geographic segment, a new all-time records across portfolio. Among consumers and businesses, planning to purchase tablets in March qtr., 78% plan to purchase iPads. Wearables, Home & Accessories: Established new all-time record with revenue of $10b, up 37% YoverY with strong double-digit performance across all five geographic segments and growth across Wearables, Accessories and Home. Set all-time records for Wearables in virtually every market Co. tracks, even as it experienced some product shortages due to strong customer demand for Apple Watch and AirPods during the qtr. Continued to see strong demand for products in enterprise market, as technology solutions enabled businesses to do their best work. 100% of Fortune 500 companies in healthcare sector use AAPL technology in areas like patient experience, clinical communications and nursing workflows. Seeing smaller companies in this sector drive innovation with technology and apps. One example is Gauss Surgical, which uses Core ML in iOS to more accurately estimate blood loss during childbirth and surgery. This helps clinicians have more complete and timely information on whether a patient needs an intervention, which can impact both clinical outcomes and costs. Amit, it's Tim. If you look at the Apple -- or the Wearables as a category within the Wearables, Home and Accessories revenue, Wearables grew 44%, so it was very strong, as you say. The -- both Apple Watch and AirPods did very well in terms of collecting new customers. Apple Watch, in particular, 75% of the customers are new to the Apple Watch, and so it's still very much selling to new customers at this point. For the results from last quarter, we had double-digit growth for iPhone in Mainland China, so that was an important change from where we had been running. We also had double-digit growth in Services in Mainland China, and we had extremely strong double-digit on Wearables. And so really, there were a number of different factors.
458
+ Answer: Wearables revenue was part of the overall Products revenue of $79.1b, which was up 8%. Wearables, Home & Accessories revenue established a new all-time record with revenue of $10b, up 37% year-over-year. Wearables experienced strong double-digit performance across all five geographic segments and growth across Wearables, Accessories and Home. Apple Watch and AirPods set all-time records for Wearables in virtually every market the company tracks, despite some product shortages due to strong customer demand. Apple Watch had 75% of customers being new to the product. Wearables had double-digit growth in Mainland China.
459
+ ###
460
+ Question: How has the growth been for the PC market?
461
+ Context: Yes. So when we look at the PC market, we finished 2019 very strong in the overall PC market, both mobile and desktop. I think that's primarily on the strength of the product portfolio and the expanding customer platforms that we have. So let me talk first about the market, and then talk a little bit about how we're seeing the full year. So if you look at the PC market, I think, the discussion so far has been, let's call it, 2020, flat to maybe down slightly. There has been some concern raised about the second half of '20 perhaps be weakened -- weaker than normal seasonality just due to some of the enterprise refresh cycles that are strong in the first half. So we feel good about that. In the data center market, again, I would say that the growth of computing continues. From our standpoint, we see it as a good market environment for data center in both cloud as well as enterprise. I think the CPU opportunity is very immediate and in front of us as we look at the opportunities with Rome and the expanding opportunities. I think the data center GPU market continues to be an important growth vector for us, and now I call that over the several-year horizon. So when you look at the opportunities that we have, when we combine our CPU and GPU IP together, they're very, very strong. So I'm not sure I'm going to forecast a share target for 2020. I will say though, if you take a look back at the last 8 quarters, we've been on a fairly steady share gain in PCs, somewhere between -- depending on the quarter, let's call it, 50 to 100 basis points per quarter, and that changes between desktop and notebook. I think we grew somewhere on the order of 4 points a share.
462
+ Answer: AMD finished 2019 very strong in the overall PC market, both mobile and desktop, primarily due to the strength of their product portfolio and expanding customer platforms. The discussion for 2020 is that the PC market will be flat to slightly down, due to some concern about weaker than normal seasonality in the second half of the year. The data center market is a good environment for AMD, with CPU opportunities being very immediate and GPU opportunities being a growth vector over the next several years. Over the last 8 quarters, AMD has seen a steady share gain in PCs, ranging from 50 to 100 basis points per quarter, and growing 4 points of share overall. This share gain has been seen in both desktop and notebook PCs. AMD has seen strong growth in the PC market due to their product portfolio and expanding customer platforms, as well as their CPU and GPU IP.
463
+ ###
464
+ Question: {query_text}
465
+ Context: {context}
466
+ Answer:?"""
467
+ return prompt
468
+
469
+
470
  # Entity Extraction
471
 
472