felipecaspol commited on
Commit
64c73b1
·
1 Parent(s): cade9d6
Files changed (1) hide show
  1. app.py +16 -15
app.py CHANGED
@@ -10,15 +10,15 @@ MODEL_REPO = os.getenv("MODEL_REPO", "fcp2207/Modelo_Phi2_fusionado")
10
  CACHE_DIR = os.getenv("HF_HOME", "/app/cache")
11
  FEEDBACK_FILE = os.path.join(CACHE_DIR, "feedback.json")
12
 
13
- # ✅ Configurar caché en Hugging Face correctamente
14
  os.makedirs(CACHE_DIR, exist_ok=True)
15
  os.environ["HF_HOME"] = CACHE_DIR
16
  os.environ["TRANSFORMERS_CACHE"] = CACHE_DIR
17
 
18
  # ✅ Inicializar FastAPI
19
- app = FastAPI(title="Phi-2 API", description="API optimizada en Hugging Face Spaces con GPU", version="3.6.0")
20
 
21
- # ✅ Clase para entrada de datos
22
  class InputData(BaseModel):
23
  input_text: str
24
 
@@ -32,7 +32,7 @@ def load_feedback():
32
  return json.load(f)
33
  return {
34
  "temperature": 0.6, "top_p": 0.85, "top_k": 50,
35
- "max_new_tokens": 50, # 🔹 Reducimos tokens generados para evitar errores de memoria
36
  "repetition_penalty": 1.2,
37
  "positivo": 0, "negativo": 0
38
  }
@@ -46,31 +46,30 @@ user_feedback = load_feedback()
46
  # ✅ Detectar si hay GPU
47
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
48
 
49
- # ✅ Cargar modelo en GPU si está disponible (SIN `.to(device)`)
50
  try:
51
- print("🔄 Descargando y cargando el modelo en Hugging Face Spaces con GPU...")
52
  model = AutoModelForCausalLM.from_pretrained(
53
  MODEL_REPO,
54
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
55
- device_map="auto", # 🔹 Dejar que accelerate maneje la asignación de GPU
56
  cache_dir=CACHE_DIR
57
  )
58
 
59
  tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, cache_dir=CACHE_DIR)
60
 
61
- # ✅ Asegurar que haya un token de padding
62
  if tokenizer.pad_token is None:
63
  tokenizer.pad_token = tokenizer.eos_token
64
  model.config.pad_token_id = tokenizer.eos_token_id
65
 
66
- print(f"✅ Modelo cargado correctamente en Hugging Face Spaces con {device}.")
67
  except Exception as e:
68
- print(f"❌ Error al cargar el modelo en Hugging Face Spaces: {str(e)}")
69
  model, tokenizer = None, None
70
 
71
  @app.get("/")
72
  def home():
73
- return {"message": "API con modelo fusionado ejecutándose en Hugging Face Spaces con GPU 🚀"}
74
 
75
  @app.post("/predict/")
76
  async def predict(data: InputData):
@@ -79,7 +78,6 @@ async def predict(data: InputData):
79
 
80
  try:
81
  num_tokens = len(data.input_text.split())
82
- timeout_value = min(120, 10 + (num_tokens * 2))
83
 
84
  # ✅ Ajustamos parámetros dinámicamente con base en feedback recibido
85
  generation_params = {
@@ -90,7 +88,8 @@ async def predict(data: InputData):
90
  "do_sample": True
91
  }
92
 
93
- input_text = f"Responde en español: {data.input_text.strip()}"
 
94
  inputs = tokenizer(input_text, return_tensors="pt", padding=True, truncation=True, max_length=512)
95
 
96
  # ✅ Mover inputs manualmente a la GPU si está disponible
@@ -99,9 +98,10 @@ async def predict(data: InputData):
99
  with torch.no_grad():
100
  outputs = model.generate(**inputs, **generation_params)
101
 
102
- response_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
103
 
104
- return {"response": response_text, "timeout": timeout_value}
105
 
106
  except torch.cuda.OutOfMemoryError:
107
  return {"response": "⚠️ Error: Falta de memoria en GPU. Reduce la cantidad de tokens generados."}
@@ -127,3 +127,4 @@ async def receive_feedback(feedback: FeedbackData):
127
  save_feedback(user_feedback)
128
 
129
  return {"message": f"Feedback {feedback.feedback} recibido y parámetros ajustados"}
 
 
10
  CACHE_DIR = os.getenv("HF_HOME", "/app/cache")
11
  FEEDBACK_FILE = os.path.join(CACHE_DIR, "feedback.json")
12
 
13
+ # ✅ Configurar caché en Hugging Face
14
  os.makedirs(CACHE_DIR, exist_ok=True)
15
  os.environ["HF_HOME"] = CACHE_DIR
16
  os.environ["TRANSFORMERS_CACHE"] = CACHE_DIR
17
 
18
  # ✅ Inicializar FastAPI
19
+ app = FastAPI(title="Phi-2 API", description="API optimizada en Hugging Face Spaces con GPU", version="4.2.0")
20
 
21
+ # ✅ Clases para datos de entrada
22
  class InputData(BaseModel):
23
  input_text: str
24
 
 
32
  return json.load(f)
33
  return {
34
  "temperature": 0.6, "top_p": 0.85, "top_k": 50,
35
+ "max_new_tokens": 50,
36
  "repetition_penalty": 1.2,
37
  "positivo": 0, "negativo": 0
38
  }
 
46
  # ✅ Detectar si hay GPU
47
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
48
 
49
+ # ✅ Cargar modelo en GPU si está disponible
50
  try:
51
+ print("🔄 Cargando el modelo en Hugging Face Spaces con GPU...")
52
  model = AutoModelForCausalLM.from_pretrained(
53
  MODEL_REPO,
54
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
55
+ device_map="auto",
56
  cache_dir=CACHE_DIR
57
  )
58
 
59
  tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, cache_dir=CACHE_DIR)
60
 
 
61
  if tokenizer.pad_token is None:
62
  tokenizer.pad_token = tokenizer.eos_token
63
  model.config.pad_token_id = tokenizer.eos_token_id
64
 
65
+ print(f"✅ Modelo cargado correctamente en {device}.")
66
  except Exception as e:
67
+ print(f"❌ Error al cargar el modelo: {str(e)}")
68
  model, tokenizer = None, None
69
 
70
  @app.get("/")
71
  def home():
72
+ return {"message": "API ejecutándose 🚀"}
73
 
74
  @app.post("/predict/")
75
  async def predict(data: InputData):
 
78
 
79
  try:
80
  num_tokens = len(data.input_text.split())
 
81
 
82
  # ✅ Ajustamos parámetros dinámicamente con base en feedback recibido
83
  generation_params = {
 
88
  "do_sample": True
89
  }
90
 
91
+ # Corregimos la entrada para que no agregue "Responde en español:"
92
+ input_text = f"{data.input_text.strip()}"
93
  inputs = tokenizer(input_text, return_tensors="pt", padding=True, truncation=True, max_length=512)
94
 
95
  # ✅ Mover inputs manualmente a la GPU si está disponible
 
98
  with torch.no_grad():
99
  outputs = model.generate(**inputs, **generation_params)
100
 
101
+ # Eliminar la frase "Responde en español:" en caso de que siga apareciendo
102
+ response_text = tokenizer.decode(outputs[0], skip_special_tokens=True).replace("Responde en español:", "").strip()
103
 
104
+ return {"response": response_text}
105
 
106
  except torch.cuda.OutOfMemoryError:
107
  return {"response": "⚠️ Error: Falta de memoria en GPU. Reduce la cantidad de tokens generados."}
 
127
  save_feedback(user_feedback)
128
 
129
  return {"message": f"Feedback {feedback.feedback} recibido y parámetros ajustados"}
130
+