import gradio as gr import spaces from unsloth import FastLanguageModel import torch # Load the model once at startup max_seq_length = 2048 dtype = None # Auto detect load_in_4bit = True # Use 4bit quantization to reduce memory model, tokenizer = FastLanguageModel.from_pretrained( model_name="cartmoney/CartCode-1", max_seq_length=max_seq_length, dtype=dtype, load_in_4bit=load_in_4bit, ) # Enable inference mode FastLanguageModel.for_inference(model) # Print model info for verification print(f"āœ… Loaded model: cartmoney/CartCode-1") print(f"šŸ“Š Model type: {type(model).__name__}") print(f"šŸ”§ Base model config: {model.config.name_or_path if hasattr(model.config, 'name_or_path') else 'N/A'}") print(f"šŸ’¾ Device: {model.device}") print(f"šŸ“ Tokenizer: {tokenizer.name_or_path}") @spaces.GPU def respond( message, history: list[dict[str, str]], system_message, max_tokens, temperature, top_p, ): """ Generate responses using the CartCode-1 LoRA model via Unsloth """ print(f"\nšŸ”µ Generating response with cartmoney/CartCode-1") print(f"šŸ“ User message: {message[:50]}...") # Build the conversation with system message messages = [{"role": "system", "content": system_message}] messages.extend(history) messages.append({"role": "user", "content": message}) # Format the conversation using the tokenizer's chat template prompt = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) # Tokenize input inputs = tokenizer([prompt], return_tensors="pt").to(model.device) # Generate response with streaming from transformers import TextIteratorStreamer from threading import Thread streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) generation_kwargs = dict( inputs, streamer=streamer, max_new_tokens=max_tokens, temperature=temperature, top_p=top_p, do_sample=True, ) thread = Thread(target=model.generate, kwargs=generation_kwargs) thread.start() response = "" for token in streamer: response += token yield response thread.join() """ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface """ chatbot = gr.ChatInterface( respond, type="messages", additional_inputs=[ gr.Textbox(value="You are a helpful coding assistant named CartCode-1. You were created by cartmoney and are based on a LoRA adapter model.", label="System message"), gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)", ), ], title="CartCode-1 Chat", description=f"šŸ¤– **Model:** cartmoney/CartCode-1 (LoRA adapter)\n\nšŸ”§ **Loaded via:** Unsloth with 4-bit quantization\n\nšŸ’¬ Chat with CartCode-1, a coding assistant!", ) with gr.Blocks() as demo: chatbot.render() if __name__ == "__main__": demo.launch()