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 +13 -26
handler.py
CHANGED
|
@@ -5,18 +5,6 @@ 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 |
class EndpointHandler():
|
| 21 |
def __init__(self, path=""):
|
| 22 |
self.model = AutoModelForCausalLM.from_pretrained(
|
|
@@ -25,9 +13,9 @@ class EndpointHandler():
|
|
| 25 |
torch_dtype=torch.bfloat16,
|
| 26 |
device_map="auto"
|
| 27 |
)
|
| 28 |
-
self.
|
| 29 |
|
| 30 |
-
def parse_and_validate_json(output):
|
| 31 |
output = output.replace("\n\n", "\n").strip()
|
| 32 |
outputs = output.split("\n")
|
| 33 |
|
|
@@ -39,10 +27,9 @@ class EndpointHandler():
|
|
| 39 |
return True, corrected_json
|
| 40 |
except (json.JSONDecodeError, ValidationError):
|
| 41 |
continue
|
| 42 |
-
|
| 43 |
return False, "No se encontr贸 ning煤n JSON v谩lido seg煤n el esquema requerido."
|
| 44 |
|
| 45 |
-
def model_inference(
|
| 46 |
default_parameters = {
|
| 47 |
"max_new_tokens": 300,
|
| 48 |
"temperature": 0.5,
|
|
@@ -51,20 +38,22 @@ class EndpointHandler():
|
|
| 51 |
"repetition_penalty": 1.2
|
| 52 |
}
|
| 53 |
default_parameters.update(parameters)
|
| 54 |
-
inputs = tokenizer(text, return_tensors="pt").to("cuda:0")
|
| 55 |
inputs_length = len(inputs["input_ids"][0])
|
| 56 |
with torch.inference_mode():
|
| 57 |
-
outputs = model.generate(**inputs, **default_parameters)
|
| 58 |
-
return tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)
|
| 59 |
|
| 60 |
-
def model_inference_with_validation(filled_template, **parameters):
|
| 61 |
while True:
|
| 62 |
-
result = self.model_inference(
|
| 63 |
is_valid, response_or_error = self.parse_and_validate_json(result)
|
| 64 |
if is_valid:
|
| 65 |
-
return {'generated_text': [
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
def __call__(self, data: Dict[str, Any]) -> Dict[str,
|
| 68 |
input_data = data.pop("inputs", data)
|
| 69 |
parameters = data.pop("parameters", {})
|
| 70 |
|
|
@@ -78,6 +67,4 @@ class EndpointHandler():
|
|
| 78 |
data_text = json.dumps(input_data, indent=4)
|
| 79 |
filled_template = template.replace("{data}", data_text)
|
| 80 |
|
| 81 |
-
return self.model_inference_with_validation(filled_template, **parameters)
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 5 |
import torch
|
| 6 |
import json
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
class EndpointHandler():
|
| 9 |
def __init__(self, path=""):
|
| 10 |
self.model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 13 |
torch_dtype=torch.bfloat16,
|
| 14 |
device_map="auto"
|
| 15 |
)
|
| 16 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
| 17 |
|
| 18 |
+
def parse_and_validate_json(self, output):
|
| 19 |
output = output.replace("\n\n", "\n").strip()
|
| 20 |
outputs = output.split("\n")
|
| 21 |
|
|
|
|
| 27 |
return True, corrected_json
|
| 28 |
except (json.JSONDecodeError, ValidationError):
|
| 29 |
continue
|
|
|
|
| 30 |
return False, "No se encontr贸 ning煤n JSON v谩lido seg煤n el esquema requerido."
|
| 31 |
|
| 32 |
+
def model_inference(self, text, **parameters):
|
| 33 |
default_parameters = {
|
| 34 |
"max_new_tokens": 300,
|
| 35 |
"temperature": 0.5,
|
|
|
|
| 38 |
"repetition_penalty": 1.2
|
| 39 |
}
|
| 40 |
default_parameters.update(parameters)
|
| 41 |
+
inputs = self.tokenizer(text, return_tensors="pt").to("cuda:0")
|
| 42 |
inputs_length = len(inputs["input_ids"][0])
|
| 43 |
with torch.inference_mode():
|
| 44 |
+
outputs = self.model.generate(**inputs, **default_parameters)
|
| 45 |
+
return self.tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True)
|
| 46 |
|
| 47 |
+
def model_inference_with_validation(self, filled_template, **parameters):
|
| 48 |
while True:
|
| 49 |
+
result = self.model_inference(filled_template, **parameters)
|
| 50 |
is_valid, response_or_error = self.parse_and_validate_json(result)
|
| 51 |
if is_valid:
|
| 52 |
+
return {'generated_text': [response_or_error]}
|
| 53 |
+
else:
|
| 54 |
+
continue
|
| 55 |
|
| 56 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 57 |
input_data = data.pop("inputs", data)
|
| 58 |
parameters = data.pop("parameters", {})
|
| 59 |
|
|
|
|
| 67 |
data_text = json.dumps(input_data, indent=4)
|
| 68 |
filled_template = template.replace("{data}", data_text)
|
| 69 |
|
| 70 |
+
return self.model_inference_with_validation(filled_template, **parameters)
|
|
|
|
|
|