Views
No views yet

1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer, BitsAndBytesConfig
3import bitsandbytes
4
5quantization_config = BitsAndBytesConfig(
6 load_in_8bit=True,
7 llm_int8_enable_fp32_cpu_offload=True
8)
9
10model_id = "CreitinGameplays/Llama-3.1-8B-R1-v0.1"
11
12# Initialize model and tokenizer with streaming support
13model = AutoModelForCausalLM.from_pretrained(
14 model_id,
15 torch_dtype=torch.bfloat16,
16 device_map="auto",
17 quantization_config=quantization_config
18)
19tokenizer = AutoTokenizer.from_pretrained(model_id)
20
21# Custom streamer that collects the output into a string while streaming
22class CollectingStreamer(TextStreamer):
23 def __init__(self, tokenizer):
24 super().__init__(tokenizer)
25 self.output = ""
26 def on_llm_new_token(self, token: str, **kwargs):
27 self.output += token
28 print(token, end="", flush=True) # prints the token as it's generated
29
30print("Chat session started. Type 'exit' to quit.\n")
31
32# Initialize chat history as a list of messages
33chat_history = []
34chat_history.append({"role": "system", "content": "You are an AI assistant made by Meta AI."})
35
36while True:
37 user_input = input("You: ")
38 if user_input.strip().lower() == "exit":
39 break
40
41 # Append the user message to the chat history
42 chat_history.append({"role": "user", "content": user_input})
43
44 # Prepare the prompt by formatting the complete chat history
45 inputs = tokenizer.apply_chat_template(
46 chat_history,
47 return_tensors="pt"
48 ).to(model.device)
49
50 # Create a new streamer for the current generation
51 streamer = CollectingStreamer(tokenizer)
52
53 # Generate streamed response
54 model.generate(
55 inputs,
56 streamer=streamer,
57 temperature=0.6,
58 top_p=0.9,
59 top_k=50,
60 repetition_penalty=1.1,
61 max_new_tokens=6112,
62 do_sample=True
63 )
64
65 # The complete response text is stored in streamer.output
66 response_text = streamer.output
67 print("\nAssistant:", response_text)
68
69 # Append the assistant response to the chat history
70 chat_history.append({"role": "assistant", "content": response_text})