Britania commited on
Commit
43d5672
路
verified 路
1 Parent(s): 2494ab2

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +22 -38
handler.py CHANGED
@@ -1,52 +1,36 @@
1
- from typing import Dict, List, Any
2
- import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
4
 
5
  class EndpointHandler():
6
- def __init__(self):
7
- # Descargar el modelo y el tokenizador
8
- self.model_name = "Britania/AthelticRoutinesModel"
9
  self.bnb_config = BitsAndBytesConfig(
10
  load_in_4bit=True,
11
  bnb_4bit_quant_type="nf4",
12
  bnb_4bit_compute_dtype=torch.float16,
13
  )
14
- self.model = AutoModelForCausalLM.from_pretrained(
15
- self.model_name,
16
  quantization_config=self.bnb_config,
17
  trust_remote_code=True,
18
  torch_dtype=torch.bfloat16,
19
- device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
  )
21
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
22
-
23
- def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
24
- """
25
- data args:
26
- inputs (:obj: `str`): Cadena de texto de entrada
27
- kwargs: Otros argumentos opcionales que puedas necesitar
28
- Return:
29
- A :obj:`list` | `dict`: ser谩 serializado y devuelto
30
- """
31
- input_text = data.get("inputs", "") # Obtener el texto de entrada de los datos
32
 
33
- # Definir los par谩metros para la generaci贸n de texto
 
 
 
 
 
 
 
 
 
 
34
  max_new_tokens = 1600
35
  temperature = 0.000001
36
-
37
- # Generar texto con el modelo
38
- generated_text = self.model_inference(input_text, max_new_tokens, temperature)
39
-
40
- return [{"generated_text": generated_text}]
41
-
42
- def model_inference(self, text: str, max_new_tokens: int, temperature: float) -> str:
43
- inputs = self.tokenizer(text, return_tensors="pt").to(self.model.device)
44
- inputs_length = len(inputs["input_ids"][0])
45
-
46
- with torch.inference_mode():
47
- outputs = self.model.generate(**inputs,
48
- max_new_tokens=max_new_tokens,
49
- temperature=temperature)
50
-
51
- return self.tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)
52
-
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ from typing import Dict, Any, List
 
3
 
4
  class EndpointHandler():
5
+ def __init__(self, path=""):
6
+ # Carga el modelo y el tokenizer
7
+ self.my_model_name = "Britania/AthelticRoutinesModel"
8
  self.bnb_config = BitsAndBytesConfig(
9
  load_in_4bit=True,
10
  bnb_4bit_quant_type="nf4",
11
  bnb_4bit_compute_dtype=torch.float16,
12
  )
13
+ self.fine_tuned_model = AutoModelForCausalLM.from_pretrained(
14
+ self.my_model_name,
15
  quantization_config=self.bnb_config,
16
  trust_remote_code=True,
17
  torch_dtype=torch.bfloat16,
18
+ device_map="auto"
19
  )
20
+ self.my_tokenizer = AutoTokenizer.from_pretrained(self.my_model_name, trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
21
 
22
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
23
+ # Procesa la entrada y llama al modelo para generar texto
24
+ input_data = data["input"]
25
+ template = """
26
+ [INST] <<SYS>>
27
+ A continuaci贸n se presentan par谩metros fisiol贸gicos y ambientales capturados por los sensores de un smartwatch utilizado por un atleta. Bas谩ndote en estos datos y en tu conocimiento de las rutinas de entrenamiento para atletas, crea una rutina diaria de entrenamiento personalizada para el atleta.
28
+ <</SYS>>
29
+ {data} [/INST]
30
+ """.strip()
31
+ data_text = json.dumps(input_data, indent=4)
32
+ filled_template = template.replace("{data}", data_text)
33
  max_new_tokens = 1600
34
  temperature = 0.000001
35
+ result = model_inference(self.fine_tuned_model, self.my_tokenizer, filled_template, max_new_tokens, temperature)
36
+ return [{"generated_text": result}]