DEXTools commited on
Commit
a4fe52a
·
verified ·
1 Parent(s): e5229be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -28
app.py CHANGED
@@ -1,12 +1,12 @@
1
  import gradio as gr
2
  import spaces
3
- from transformers import AutoProcessor, Gemma3ForConditionalGeneration
4
  import torch
5
 
6
- # Carga modelo y processor en CPU (ZeroGPU lo maneja automáticamente)
7
  model_id = "google/gemma-3-4b-it"
8
- processor = AutoProcessor.from_pretrained(model_id)
9
- model = Gemma3ForConditionalGeneration.from_pretrained(
10
  model_id,
11
  torch_dtype=torch.bfloat16,
12
  low_cpu_mem_usage=True
@@ -17,37 +17,39 @@ def generate_response(message, history):
17
  # Mueve el modelo a GPU temporalmente
18
  model.to('cuda')
19
 
20
- # Construye mensajes para formato chat de Gemma-3 (solo texto, ya que el usuario no pidió multimodal explícitamente)
21
- messages = [{"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]}]
22
  for user_msg, ai_msg in history:
23
- messages.append({"role": "user", "content": [{"type": "text", "text": user_msg}]})
24
  if ai_msg:
25
- messages.append({"role": "model", "content": [{"type": "text", "text": ai_msg}]})
26
- messages.append({"role": "user", "content": [{"type": "text", "text": message}]})
27
 
28
  # Aplica template de chat
29
- inputs = processor.apply_chat_template(
30
  messages,
31
- add_generation_prompt=True,
32
- tokenize=True,
33
- return_dict=True,
34
- return_tensors="pt"
35
- ).to('cuda', dtype=torch.bfloat16)
 
36
 
37
  # Genera en GPU
38
- input_len = inputs["input_ids"].shape[-1]
39
  with torch.no_grad():
40
- generation = model.generate(
41
  **inputs,
42
  max_new_tokens=150,
43
  do_sample=True,
44
  temperature=0.7,
45
- pad_token_id=processor.tokenizer.eos_token_id
46
  )
47
- generation = generation[0][input_len:]
48
 
49
  # Decodifica solo tokens nuevos
50
- response = processor.decode(generation, skip_special_tokens=True).strip()
 
 
 
51
 
52
  # Libera GPU: mueve modelo de vuelta a CPU y limpia caché
53
  model.to('cpu')
@@ -55,20 +57,17 @@ def generate_response(message, history):
55
 
56
  return response
57
 
58
- # Interfaz de chat con Gradio (solo texto, para simplicidad)
59
  demo = gr.ChatInterface(
60
  fn=generate_response,
61
- title="Chat Interface para Hugging Face ZeroGPU Space con Gemma-3-4B-IT",
62
- description="Un chatbot usando google/gemma-3-4b-it. Optimizado para ZeroGPU: GPU se asigna dinámicamente solo durante la generación con @spaces.GPU. (Solo texto; ignora multimodal por ahora).",
63
  examples=[
64
  ["Hola, ¿cómo estás?"],
65
- ["Explica qué es la IA."],
66
  ["Cuéntame un chiste."]
67
  ],
68
- cache_examples=True,
69
- retry_btn="Reintentar",
70
- undo_btn="Deshacer",
71
- clear_btn="Limpiar chat"
72
  )
73
 
74
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import spaces
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
  import torch
5
 
6
+ # Carga modelo y tokenizer en CPU (ZeroGPU lo maneja automáticamente)
7
  model_id = "google/gemma-3-4b-it"
8
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
  model_id,
11
  torch_dtype=torch.bfloat16,
12
  low_cpu_mem_usage=True
 
17
  # Mueve el modelo a GPU temporalmente
18
  model.to('cuda')
19
 
20
+ # Construye mensajes para formato chat de Gemma-3 (solo texto)
21
+ messages = []
22
  for user_msg, ai_msg in history:
23
+ messages.append({"role": "user", "content": user_msg})
24
  if ai_msg:
25
+ messages.append({"role": "assistant", "content": ai_msg})
26
+ messages.append({"role": "user", "content": message})
27
 
28
  # Aplica template de chat
29
+ prompt = tokenizer.apply_chat_template(
30
  messages,
31
+ tokenize=False,
32
+ add_generation_prompt=True
33
+ )
34
+
35
+ # Tokeniza
36
+ inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
37
 
38
  # Genera en GPU
 
39
  with torch.no_grad():
40
+ outputs = model.generate(
41
  **inputs,
42
  max_new_tokens=150,
43
  do_sample=True,
44
  temperature=0.7,
45
+ pad_token_id=tokenizer.eos_token_id
46
  )
 
47
 
48
  # Decodifica solo tokens nuevos
49
+ response = tokenizer.decode(
50
+ outputs[0][inputs.input_ids.shape[1]:],
51
+ skip_special_tokens=True
52
+ ).strip()
53
 
54
  # Libera GPU: mueve modelo de vuelta a CPU y limpia caché
55
  model.to('cpu')
 
57
 
58
  return response
59
 
60
+ # Interfaz de chat con Gradio (solo texto)
61
  demo = gr.ChatInterface(
62
  fn=generate_response,
63
+ title="Gemma-3-4B-IT Chat en ZeroGPU",
64
+ description="Chatbot con google/gemma-3-4b-it. GPU dinámica via @spaces.GPU.",
65
  examples=[
66
  ["Hola, ¿cómo estás?"],
67
+ ["Explica qué es la IA en 3 líneas."],
68
  ["Cuéntame un chiste."]
69
  ],
70
+ cache_examples=True
 
 
 
71
  )
72
 
73
  if __name__ == "__main__":