File size: 3,967 Bytes
0d58086
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb88fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
try: import torch
except: raise ImportError("Install torch via `pip install torch`")
from packaging.version import Version as V
v = V(torch.__version__)
cuda = str(torch.version.cuda)
is_ampere = torch.cuda.get_device_capability()[0] >= 8
if cuda != "12.1" and cuda != "11.8": raise RuntimeError(f"CUDA = {cuda} not supported!")
if   v <= V('2.1.0'): raise RuntimeError(f"Torch = {v} too old!")
elif v <= V('2.1.1'): x = 'cu{}{}-torch211'
elif v <= V('2.1.2'): x = 'cu{}{}-torch212'
elif v  < V('2.3.0'): x = 'cu{}{}-torch220'
elif v  < V('2.4.0'): x = 'cu{}{}-torch230'
elif v  < V('2.5.0'): x = 'cu{}{}-torch240'
else: raise RuntimeError(f"Torch = {v} too new!")
x = x.format(cuda.replace(".", ""), "-ampere" if is_ampere else "")
print(f'pip install --upgrade pip && pip install "unsloth[{x}] @ git+https://github.com/unslothai/unsloth.git"')

nvcc
python -m xformers.info
python -m bitsandbytes
from unsloth import FastLanguageModel

import torch
max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False


from transformers import AutoTokenizer

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="DipeshChaudhary/ShareGPTChatBot-Counselchat1",  # Your fine-tuned model
    max_seq_length=max_seq_length,
    dtype=dtype,
    load_in_4bit=load_in_4bit,
)


from unsloth.chat_templates import get_chat_template


tokenizer = get_chat_template(
    tokenizer,
    chat_template = "llama-3", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
    mapping = {"role" : "from", "content" : "value", "user" : "human", "assistant" : "gpt"}, # ShareGPT style
)


import re
FastLanguageModel.for_inference(model) # Enable native 2x faster inference

messages = [
    {"from": "human", "value": "hlo"},
]
inputs = tokenizer.apply_chat_template(
    messages,
    tokenize = True,
    add_generation_prompt = True, # Must add for generation
    return_tensors = "pt",
).to("cuda")


from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer)


x= model.generate(input_ids = inputs, streamer = text_streamer, max_new_tokens = 128, use_cache = True)


# Function to generate response
def generate_response(conversation_history):

    inputs = tokenizer.apply_chat_template(conversation_history,
                                           tokenize = True,
                                           add_generation_prompt = True, # Must add for generation
                                           return_tensors = "pt",
                                          ).to("cuda")
    text_streamer = TextStreamer(tokenizer)
    
    
    # Set the pad_token_id to the eos_token_id if it's not set
    if tokenizer.pad_token_id is None:
        tokenizer.pad_token_id = tokenizer.eos_token_id

    # Generate the response
    output = model.generate(
        inputs,
        max_new_tokens=10000,
        use_cache=True,
        pad_token_id=tokenizer.pad_token_id,
        attention_mask=inputs.ne(tokenizer.pad_token_id)
    )
    
    # Decode the output, skipping special tokens
    decoded_output = tokenizer.decode(output[0], skip_special_tokens=True)
    
    # Extract only the bot's response
    bot_response = decoded_output.split("assistant")[-1].strip()
    
    return bot_response

# Example usage
conversation_history = []
while True:
    user_input = input("User: ")
    if user_input.lower() == "exit":
        print("Exiting...")
        break
    
    # Append user message to history
    conversation_history.append({"from": "human", "value": user_input})
    
    # Generate response
    response = generate_response(conversation_history)
    
    # Append bot response to history
    conversation_history.append({"from": "bot", "value": response})
    
    #Print bot's response
    print("Bot:", response)