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
Download handler.py from Britania/m2: direct link, hf CLI and curl.
- Browser
- Download file 3.4 kB
-
https://huggingface.co/Britania/m2/resolve/refs%2Fpr%2F1/handler.py
- Command line
-
hf download hf://Britania/m2@refs/pr/1/handler.py
-
curl -L -o handler.py https://huggingface.co/Britania/m2/resolve/refs%2Fpr%2F1/handler.py
3.4 kB
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from jsonschema import validate, ValidationError | |
| from typing import Dict, Any, List | |
| import jsonschema | |
| import torch | |
| import json | |
| class EndpointHandler(): | |
| def __init__(self, path=""): | |
| self.model = AutoModelForCausalLM.from_pretrained( | |
| path, | |
| trust_remote_code=True, | |
| torch_dtype=torch.bfloat16, | |
| device_map="auto" | |
| ) | |
| self.tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True) | |
| self.schema = { | |
| "type": "object", | |
| "properties": { | |
| "objetivoDistancia": {"type": "string"}, | |
| "calentamiento": {"type": "string"}, | |
| "drills": {"type": "array", "items": {"type": "object"}}, | |
| "sprints": {"type": "array", "items": {"type": "object"}}, | |
| "enfriamiento": {"type": "string"} | |
| }, | |
| "required": ["calentamiento", "drills", "enfriamiento"] | |
| } | |
| def parse_and_validate_json(self, output): | |
| output = output.replace("\n\n", "\n").strip() | |
| outputs = output.split("\n") | |
| for single_output in outputs: | |
| try: | |
| corrected_json = single_output.replace('}\n"', '}, "') | |
| data = json.loads(corrected_json) | |
| validate(instance=data, schema=self.schema) | |
| return True, corrected_json | |
| except (json.JSONDecodeError, ValidationError): | |
| continue | |
| return False, "No se encontr贸 ning煤n JSON v谩lido seg煤n el esquema requerido." | |
| def model_inference(self, text, **parameters): | |
| default_parameters = { | |
| "max_new_tokens": 512, | |
| "temperature": 0.5, | |
| "top_p": 0.99, | |
| "top_k": 20, | |
| "repetition_penalty": 1.2 | |
| } | |
| default_parameters.update(parameters) | |
| inputs = self.tokenizer(text, return_tensors="pt").to("cuda:0") | |
| inputs_length = len(inputs["input_ids"][0]) | |
| with torch.inference_mode(): | |
| outputs = self.model.generate(**inputs, **default_parameters) | |
| return self.tokenizer.decode(outputs[0][inputs_length:], skip_special_tokens=True) | |
| def model_inference_with_validation(self, filled_template, **parameters): | |
| while True: | |
| result = self.model_inference(filled_template, **parameters) | |
| is_valid, response_or_error = self.parse_and_validate_json(result) | |
| if is_valid: | |
| return {'generated_text': [response_or_error]} | |
| else: | |
| continue | |
| def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| input_data = data.pop("inputs", data) | |
| parameters = data.pop("parameters", {}) | |
| template = """ | |
| [INST] <<SYS>> | |
| 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. | |
| <</SYS>> | |
| {data} [/INST] | |
| """.strip() | |
| data_text = json.dumps(input_data, indent=4) | |
| filled_template = template.replace("{data}", data_text) | |
| return self.model_inference_with_validation(filled_template, **parameters) |