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