Views
No views yet
transformers library:1from transformers import AutoModelForCausalLM, AutoTokenizer
2import torch
3
4# Load the model and tokenizer
5model_name = "huihui-ai/Qwen2.5-Code-32B-Instruct-abliterated"
6model = AutoModelForCausalLM.from_pretrained(
7 model_name,
8 torch_dtype=torch.bfloat16,
9 device_map="auto"
10)
11tokenizer = AutoTokenizer.from_pretrained(model_name)
12
13# Initialize conversation context
14initial_messages = [
15 {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."}
16]
17messages = initial_messages.copy() # Copy the initial conversation context
18
19# Enter conversation loop
20while True:
21 # Get user input
22 user_input = input("User: ").strip() # Strip leading and trailing spaces
23
24 # If the user types '/exit', end the conversation
25 if user_input.lower() == "/exit":
26 print("Exiting chat.")
27 break
28
29 # If the user types '/clean', reset the conversation context
30 if user_input.lower() == "/clean":
31 messages = initial_messages.copy() # Reset conversation context
32 print("Chat history cleared. Starting a new conversation.")
33 continue
34
35 # If input is empty, prompt the user and continue
36 if not user_input:
37 print("Input cannot be empty. Please enter something.")
38 continue
39
40 # Add user input to the conversation
41 messages.append({"role": "user", "content": user_input})
42
43 # Build the chat template
44 text = tokenizer.apply_chat_template(
45 messages,
46 tokenize=False,
47 add_generation_prompt=True
48 )
49
50 # Tokenize input and prepare it for the model
51 model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
52
53 # Generate a response from the model
54 generated_ids = model.generate(
55 **model_inputs,
56 max_new_tokens=8192
57 )
58
59 # Extract model output, removing special tokens
60 generated_ids = [
61 output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
62 ]
63 response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
64
65 # Add the model's response to the conversation
66 messages.append({"role": "assistant", "content": response})
67
68 # Print the model's response
69 print(f"Qwen: {response}")
70