Text Generation
Transformers
Safetensors
English
mistral
text-generation-inference
unsloth
trl
sft
conversational
4-bit precision
bitsandbytes
Instructions to use ChevalierJoseph/typtop4 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ChevalierJoseph/typtop4 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="ChevalierJoseph/typtop4") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("ChevalierJoseph/typtop4") model = AutoModelForCausalLM.from_pretrained("ChevalierJoseph/typtop4", 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=40) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use ChevalierJoseph/typtop4 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "ChevalierJoseph/typtop4" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ChevalierJoseph/typtop4", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/ChevalierJoseph/typtop4
- SGLang
How to use ChevalierJoseph/typtop4 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 "ChevalierJoseph/typtop4" \ --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": "ChevalierJoseph/typtop4", "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 "ChevalierJoseph/typtop4" \ --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": "ChevalierJoseph/typtop4", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Unsloth Studio
How to use ChevalierJoseph/typtop4 with Unsloth Studio:
Install Unsloth Studio (macOS, Linux, WSL)
curl -fsSL https://unsloth.ai/install.sh | sh # Run unsloth studio unsloth studio -H 0.0.0.0 -p 8888 # Then open http://localhost:8888 in your browser # Search for ChevalierJoseph/typtop4 to start chatting
Install Unsloth Studio (Windows)
irm https://unsloth.ai/install.ps1 | iex # Run unsloth studio unsloth studio -H 0.0.0.0 -p 8888 # Then open http://localhost:8888 in your browser # Search for ChevalierJoseph/typtop4 to start chatting
Using HuggingFace Spaces for Unsloth
# No setup required # Open https://huggingface.co/spaces/unsloth/studio in your browser # Search for ChevalierJoseph/typtop4 to start chatting
Load model with FastModel
pip install unsloth from unsloth import FastModel model, tokenizer = FastModel.from_pretrained( model_name="ChevalierJoseph/typtop4", max_seq_length=2048, ) - Docker Model Runner
How to use ChevalierJoseph/typtop4 with Docker Model Runner:
docker model run hf.co/ChevalierJoseph/typtop4
| from typing import Dict, List, Any | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| import logging | |
| # Set up logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class EndpointHandler: | |
| def __init__(self, path: str = ""): | |
| """ | |
| Initialize the model and tokenizer when the endpoint starts. | |
| Args: | |
| path (str): Path to the model files | |
| """ | |
| logger.info(f"Loading model from {path}") | |
| # Load tokenizer and model | |
| self.tokenizer = AutoTokenizer.from_pretrained(path) | |
| # Try to load without quantization first | |
| try: | |
| self.model = AutoModelForCausalLM.from_pretrained( | |
| path, | |
| torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, | |
| device_map="auto" if torch.cuda.is_available() else None, | |
| trust_remote_code=True, | |
| load_in_8bit=False, | |
| load_in_4bit=False | |
| ) | |
| except Exception as e: | |
| logger.warning(f"Failed to load without quantization: {e}") | |
| # Fallback: try with different settings | |
| self.model = AutoModelForCausalLM.from_pretrained( | |
| path, | |
| torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, | |
| device_map="auto" if torch.cuda.is_available() else None, | |
| trust_remote_code=True, | |
| use_safetensors=True | |
| ) | |
| # Set pad token if it doesn't exist | |
| if self.tokenizer.pad_token is None: | |
| self.tokenizer.pad_token = self.tokenizer.eos_token | |
| logger.info("Model loaded successfully") | |
| def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: | |
| """ | |
| Process the inference request. | |
| Args: | |
| data (Dict[str, Any]): Request data containing: | |
| - inputs (str): The input text/prompt | |
| - parameters (dict, optional): Generation parameters | |
| - max_new_tokens (int): Maximum tokens to generate (default: 256) | |
| - temperature (float): Sampling temperature (default: 0.7) | |
| - top_p (float): Top-p sampling (default: 0.9) | |
| - do_sample (bool): Whether to use sampling (default: True) | |
| - repetition_penalty (float): Repetition penalty (default: 1.1) | |
| - return_full_text (bool): Return full text including input (default: False) | |
| Returns: | |
| List[Dict[str, Any]]: Generated text response | |
| """ | |
| try: | |
| # Extract inputs | |
| inputs = data.get("inputs", "") | |
| if not inputs: | |
| return [{"error": "No input text provided"}] | |
| # Extract generation parameters | |
| parameters = data.get("parameters", {}) | |
| max_new_tokens = parameters.get("max_new_tokens", 256) | |
| temperature = parameters.get("temperature", 0.7) | |
| top_p = parameters.get("top_p", 0.9) | |
| do_sample = parameters.get("do_sample", True) | |
| repetition_penalty = parameters.get("repetition_penalty", 1.1) | |
| return_full_text = parameters.get("return_full_text", False) | |
| # Format the input as a chat message if it doesn't already contain instruction formatting | |
| if not any(marker in inputs.lower() for marker in ["[inst]", "<s>", "### instruction", "user:", "assistant:"]): | |
| formatted_input = f"[INST] {inputs} [/INST]" | |
| else: | |
| formatted_input = inputs | |
| # Tokenize input | |
| input_ids = self.tokenizer.encode( | |
| formatted_input, | |
| return_tensors="pt", | |
| truncation=True, | |
| max_length=2048 # Reasonable limit for input | |
| ) | |
| # Move to GPU if available | |
| if torch.cuda.is_available(): | |
| input_ids = input_ids.cuda() | |
| # Generate response | |
| with torch.no_grad(): | |
| output_ids = self.model.generate( | |
| input_ids, | |
| max_new_tokens=max_new_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| do_sample=do_sample, | |
| repetition_penalty=repetition_penalty, | |
| pad_token_id=self.tokenizer.pad_token_id, | |
| eos_token_id=self.tokenizer.eos_token_id, | |
| use_cache=True | |
| ) | |
| # Decode the response | |
| if return_full_text: | |
| generated_text = self.tokenizer.decode(output_ids[0], skip_special_tokens=True) | |
| else: | |
| # Only return the newly generated tokens | |
| new_tokens = output_ids[0][input_ids.shape[-1]:] | |
| generated_text = self.tokenizer.decode(new_tokens, skip_special_tokens=True) | |
| # Clean up the response | |
| generated_text = generated_text.strip() | |
| # Return in the expected format | |
| return [{ | |
| "generated_text": generated_text, | |
| "input_length": input_ids.shape[-1], | |
| "output_length": len(output_ids[0]) - input_ids.shape[-1] | |
| }] | |
| except Exception as e: | |
| logger.error(f"Error during inference: {str(e)}") | |
| return [{"error": f"Inference failed: {str(e)}"}] | |
| def __del__(self): | |
| """Clean up resources when the handler is destroyed.""" | |
| if hasattr(self, 'model'): | |
| del self.model | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() |