Instructions to use Britania/m2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Britania/m2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Britania/m2") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Britania/m2") model = AutoModelForCausalLM.from_pretrained("Britania/m2", device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Britania/m2 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Britania/m2" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Britania/m2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Britania/m2
- SGLang
How to use Britania/m2 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Britania/m2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Britania/m2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Britania/m2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Britania/m2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Britania/m2 with Docker Model Runner:
docker model run hf.co/Britania/m2
Update handler.py
Browse files- handler.py +57 -12
handler.py
CHANGED
|
@@ -1,23 +1,65 @@
|
|
| 1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
|
| 2 |
from typing import Dict, Any, List
|
|
|
|
| 3 |
import torch
|
| 4 |
import json
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"temperature": 0.5,
|
| 10 |
-
"top_p": 0.
|
| 11 |
-
"top_k":
|
| 12 |
-
"repetition_penalty": 1.
|
| 13 |
}
|
| 14 |
-
|
| 15 |
inputs = tokenizer(text, return_tensors="pt").to("cuda:0")
|
| 16 |
inputs_length = len(inputs["input_ids"][0])
|
| 17 |
with torch.inference_mode():
|
| 18 |
-
outputs = model.generate(**inputs, **
|
| 19 |
return tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
class EndpointHandler():
|
| 22 |
def __init__(self, path=""):
|
| 23 |
self.model = AutoModelForCausalLM.from_pretrained(
|
|
@@ -31,14 +73,17 @@ class EndpointHandler():
|
|
| 31 |
def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
|
| 32 |
input_data = data.pop("inputs", data)
|
| 33 |
parameters = data.pop("parameters", {})
|
|
|
|
| 34 |
template = """
|
| 35 |
-
|
| 36 |
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.
|
| 37 |
<</SYS>>
|
| 38 |
{data} [/INST]
|
| 39 |
""".strip()
|
|
|
|
| 40 |
data_text = json.dumps(input_data, indent=4)
|
| 41 |
filled_template = template.replace("{data}", data_text)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
| 1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 2 |
+
from jsonschema import validate, ValidationError
|
| 3 |
from typing import Dict, Any, List
|
| 4 |
+
import jsonschema
|
| 5 |
import torch
|
| 6 |
import json
|
| 7 |
|
| 8 |
+
schema = {
|
| 9 |
+
"type": "object",
|
| 10 |
+
"properties": {
|
| 11 |
+
"objetivoDistancia": {"type": "string"},
|
| 12 |
+
"calentamiento": {"type": "string"},
|
| 13 |
+
"drills": {"type": "array", "items": {"type": "object"}},
|
| 14 |
+
"sprints": {"type": "array", "items": {"type": "object"}},
|
| 15 |
+
"enfriamiento": {"type": "string"}
|
| 16 |
+
},
|
| 17 |
+
"required": ["objetivoDistancia", "calentamiento", "drills", "sprints", "enfriamiento"]
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
def parse_and_validate_json(output):
|
| 21 |
+
output = output.replace("\n\n", "\n").strip()
|
| 22 |
+
outputs = output.split("\n")
|
| 23 |
+
|
| 24 |
+
for single_output in outputs:
|
| 25 |
+
try:
|
| 26 |
+
corrected_json = single_output.replace('}\n"', '}, "')
|
| 27 |
+
data = json.loads(corrected_json)
|
| 28 |
+
validate(instance=data, schema=schema)
|
| 29 |
+
return True, corrected_json
|
| 30 |
+
except (json.JSONDecodeError, ValidationError):
|
| 31 |
+
continue
|
| 32 |
+
|
| 33 |
+
return False, "No se encontr贸 ning煤n JSON v谩lido seg煤n el esquema requerido."
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def model_inference(model, tokenizer, text, **parameters):
|
| 39 |
+
default_parameters = {
|
| 40 |
+
"max_new_tokens": 300,
|
| 41 |
"temperature": 0.5,
|
| 42 |
+
"top_p": 0.99,
|
| 43 |
+
"top_k": 20,
|
| 44 |
+
"repetition_penalty": 1.2
|
| 45 |
}
|
| 46 |
+
default_parameters.update(parameters)
|
| 47 |
inputs = tokenizer(text, return_tensors="pt").to("cuda:0")
|
| 48 |
inputs_length = len(inputs["input_ids"][0])
|
| 49 |
with torch.inference_mode():
|
| 50 |
+
outputs = model.generate(**inputs, **default_parameters)
|
| 51 |
return tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)
|
| 52 |
|
| 53 |
+
|
| 54 |
+
def model_inference_with_validation(filled_template, **parameters):
|
| 55 |
+
while True:
|
| 56 |
+
result = model_inference(self.model, self.my_tokenizer, filled_template, **parameters)
|
| 57 |
+
is_valid, response_or_error = parse_and_validate_json(result)
|
| 58 |
+
if is_valid:
|
| 59 |
+
return {'generated_text': [result]}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
|
| 63 |
class EndpointHandler():
|
| 64 |
def __init__(self, path=""):
|
| 65 |
self.model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 73 |
def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
|
| 74 |
input_data = data.pop("inputs", data)
|
| 75 |
parameters = data.pop("parameters", {})
|
| 76 |
+
|
| 77 |
template = """
|
| 78 |
+
[INST] <<SYS>>
|
| 79 |
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.
|
| 80 |
<</SYS>>
|
| 81 |
{data} [/INST]
|
| 82 |
""".strip()
|
| 83 |
+
|
| 84 |
data_text = json.dumps(input_data, indent=4)
|
| 85 |
filled_template = template.replace("{data}", data_text)
|
| 86 |
+
|
| 87 |
+
return model_inference_with_validation(filled_template, **parameters)
|
| 88 |
+
|
| 89 |
+
|