Jeppcode commited on
Commit
a8f20e0
·
verified ·
1 Parent(s): e263e64

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -25
app.py CHANGED
@@ -7,22 +7,23 @@ SUBFOLDER = "merged-model-fp16"
7
 
8
  print(f"Loading model {MODEL_ID}/{SUBFOLDER} ...")
9
 
10
- # Tokenizer
11
  tokenizer = AutoTokenizer.from_pretrained(
12
  MODEL_ID,
13
  subfolder=SUBFOLDER,
14
  )
15
 
16
- # Model fp16 on CPU, memory-friendly
17
  model = AutoModelForCausalLM.from_pretrained(
18
  MODEL_ID,
19
  subfolder=SUBFOLDER,
20
- dtype=torch.float16,
21
  low_cpu_mem_usage=True,
22
  device_map="cpu",
23
  )
24
  model.eval()
25
 
 
26
  STYLE_SYSTEM_PROMPTS = {
27
  "Default": "You are a helpful, polite assistant.",
28
  "Short answer": (
@@ -41,23 +42,26 @@ STYLE_SYSTEM_PROMPTS = {
41
 
42
  def build_prompt(message, history, style):
43
  """
44
- history är i 'messages'-format:
45
- [{"role": "user", "content": "..."},
46
- {"role": "assistant", "content": "..."}, ...]
47
- Vi lägger till en systemprompt + tidigare meddelanden + nuvarande fråga.
48
  """
49
  messages = []
50
 
51
- # System / style prompt (läggs bara i prompten, inte i history)
52
  system_prompt = STYLE_SYSTEM_PROMPTS.get(style, STYLE_SYSTEM_PROMPTS["Default"])
53
  messages.append({"role": "system", "content": system_prompt})
54
 
55
- # Tidigare dialog (bara user/assistant)
56
- messages.extend(history)
 
 
 
 
57
 
58
- # Nuvarande användarmeddelande
59
  messages.append({"role": "user", "content": message})
60
 
 
61
  prompt = tokenizer.apply_chat_template(
62
  messages,
63
  tokenize=False,
@@ -67,7 +71,7 @@ def build_prompt(message, history, style):
67
 
68
 
69
  def chat_fn(message, history, max_new_tokens, temperature, top_p, repetition_penalty, style):
70
- # history är redan i messages-format, vi gör inte om det
71
  prompt = build_prompt(message, history, style)
72
 
73
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
@@ -80,7 +84,7 @@ def chat_fn(message, history, max_new_tokens, temperature, top_p, repetition_pen
80
  "repetition_penalty": float(repetition_penalty),
81
  }
82
 
83
- # Greedy vs sampling beroende temperatur
84
  if temperature <= 0.0:
85
  gen_kwargs.update(
86
  dict(
@@ -106,14 +110,11 @@ def chat_fn(message, history, max_new_tokens, temperature, top_p, repetition_pen
106
  skip_special_tokens=True,
107
  ).strip()
108
 
109
- # Uppdatera history i messages-format:
110
- new_history = history + [
111
- {"role": "user", "content": message},
112
- {"role": "assistant", "content": generated},
113
- ]
114
 
115
- # Töm textboxen, uppdatera chatten
116
- return "", new_history
117
 
118
 
119
  with gr.Blocks() as demo:
@@ -121,14 +122,14 @@ with gr.Blocks() as demo:
121
  "# Lab 2 – Fine-tuned merged model (fp16)\n"
122
  "Chat with our fine-tuned Llama-based model, merged to fp16 and "
123
  "loaded from `Jeppcode/ScalableLab2/merged-model-fp16`.\n\n"
124
- "Use the controls on the right like a DJ board to explore how decoding "
125
  "settings change the behaviour of the model."
126
  )
127
 
128
  with gr.Row():
129
- # Left: chat
130
  with gr.Column(scale=3):
131
- chatbot = gr.Chatbot(label="Chat", type="messages")
132
  msg = gr.Textbox(
133
  label="Your message",
134
  placeholder="Ask the model something...",
@@ -137,7 +138,7 @@ with gr.Blocks() as demo:
137
  send_btn = gr.Button("Send")
138
  clear_btn = gr.Button("Clear chat")
139
 
140
- # Right: generation controls
141
  with gr.Column(scale=1):
142
  gr.Markdown("### Generation controls")
143
 
@@ -181,7 +182,7 @@ with gr.Blocks() as demo:
181
  label="Answer style",
182
  )
183
 
184
- # Koppla knappar / enter
185
  send_btn.click(
186
  chat_fn,
187
  inputs=[msg, chatbot, max_new_tokens, temperature, top_p, repetition_penalty, style],
 
7
 
8
  print(f"Loading model {MODEL_ID}/{SUBFOLDER} ...")
9
 
10
+ # Load tokenizer
11
  tokenizer = AutoTokenizer.from_pretrained(
12
  MODEL_ID,
13
  subfolder=SUBFOLDER,
14
  )
15
 
16
+ # Load model (fp16 on CPU to fit in HF Space)
17
  model = AutoModelForCausalLM.from_pretrained(
18
  MODEL_ID,
19
  subfolder=SUBFOLDER,
20
+ dtype=torch.float16, # use dtype (torch_dtype is deprecated)
21
  low_cpu_mem_usage=True,
22
  device_map="cpu",
23
  )
24
  model.eval()
25
 
26
+ # Predefined “styles” as system prompts
27
  STYLE_SYSTEM_PROMPTS = {
28
  "Default": "You are a helpful, polite assistant.",
29
  "Short answer": (
 
42
 
43
  def build_prompt(message, history, style):
44
  """
45
+ history is a list of [user, bot] pairs (Gradio's default Chatbot format).
46
+ We convert it into a list of role/content messages for the chat template.
 
 
47
  """
48
  messages = []
49
 
50
+ # Add system / style message
51
  system_prompt = STYLE_SYSTEM_PROMPTS.get(style, STYLE_SYSTEM_PROMPTS["Default"])
52
  messages.append({"role": "system", "content": system_prompt})
53
 
54
+ # Add previous conversation
55
+ for user_msg, bot_msg in history:
56
+ if user_msg is not None:
57
+ messages.append({"role": "user", "content": user_msg})
58
+ if bot_msg is not None:
59
+ messages.append({"role": "assistant", "content": bot_msg})
60
 
61
+ # Current user message
62
  messages.append({"role": "user", "content": message})
63
 
64
+ # Use chat_template from your tokenizer
65
  prompt = tokenizer.apply_chat_template(
66
  messages,
67
  tokenize=False,
 
71
 
72
 
73
  def chat_fn(message, history, max_new_tokens, temperature, top_p, repetition_penalty, style):
74
+ # Build full prompt including history + style
75
  prompt = build_prompt(message, history, style)
76
 
77
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
 
84
  "repetition_penalty": float(repetition_penalty),
85
  }
86
 
87
+ # Deterministic if temperature == 0, otherwise sampling
88
  if temperature <= 0.0:
89
  gen_kwargs.update(
90
  dict(
 
110
  skip_special_tokens=True,
111
  ).strip()
112
 
113
+ # Update history in the default (user, bot) format
114
+ history = history + [[message, generated]]
 
 
 
115
 
116
+ # Return empty textbox + updated chat history
117
+ return "", history
118
 
119
 
120
  with gr.Blocks() as demo:
 
122
  "# Lab 2 – Fine-tuned merged model (fp16)\n"
123
  "Chat with our fine-tuned Llama-based model, merged to fp16 and "
124
  "loaded from `Jeppcode/ScalableLab2/merged-model-fp16`.\n\n"
125
+ "Use the controls on the right like a DJ board to see how decoding "
126
  "settings change the behaviour of the model."
127
  )
128
 
129
  with gr.Row():
130
+ # Left side: chatbot
131
  with gr.Column(scale=3):
132
+ chatbot = gr.Chatbot(label="Chat") # no 'type' argument
133
  msg = gr.Textbox(
134
  label="Your message",
135
  placeholder="Ask the model something...",
 
138
  send_btn = gr.Button("Send")
139
  clear_btn = gr.Button("Clear chat")
140
 
141
+ # Right side: generation settings (DJ board)
142
  with gr.Column(scale=1):
143
  gr.Markdown("### Generation controls")
144
 
 
182
  label="Answer style",
183
  )
184
 
185
+ # Hook up buttons / enter key
186
  send_btn.click(
187
  chat_fn,
188
  inputs=[msg, chatbot, max_new_tokens, temperature, top_p, repetition_penalty, style],