File size: 8,390 Bytes
7a17876
 
 
 
7cd6401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
---
license: apache-2.0
pipeline_tag: text-generation
library_name: transformers
---

# AMD-135m


## Introduction
AMD-Llama-135m is a language model trained on AMD MI250 GPUs. Based on LLaMA2 model architecture, this model can be smoothly loaded as LlamaForCausalLM with huggingface transformers. Furthermore, we use the same tokenizer as LLaMA2, enabling it to be a draft model of speculative decoding for LLaMA2 and CodeLlama.

```python
import sys
import os
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QPushButton,
                             QLineEdit, QTextEdit, QVBoxLayout, QHBoxLayout,
                             QFileDialog, QProgressBar, QMessageBox, QMenu)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from llama_cpp import Llama


class Worker(QThread):
    finished = pyqtSignal(str)
    progress = pyqtSignal(int, int)  # Pass total tokens as well

    def __init__(self, model, messages, max_tokens):
        super().__init__()
        self.model = model
        self.messages = messages
        self.max_tokens = max_tokens

    def run(self):
        try:
            response = self.model.create_chat_completion(
                messages=self.messages,
                max_tokens=self.max_tokens,
                temperature=0.7,
                stream=True
            )

            total_tokens = 0
            full_response = ""
            for chunk in response:
                if "choices" in chunk:
                    content = chunk["choices"][0]["delta"].get("content", "")
                    full_response += content
                    total_tokens += 1  # Assume each chunk is 1 token (adjust if needed)
                    self.progress.emit(total_tokens, self.max_tokens)
            self.finished.emit(full_response)
        except Exception as e:
            self.finished.emit(f"Error generating response: {str(e)}")


class ChatbotGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Chatbot GUI")
        self.resize(800, 600)

        self.model = None
        self.messages = [
            {"role": "system", "content": "You are a helpful AI assistant."}
        ]

        self.initUI()

    def initUI(self):
        # Model loading section
        model_label = QLabel("Model: No model loaded")
        load_button = QPushButton("Load GGUF Model")
        load_button.clicked.connect(self.load_model)

        model_layout = QHBoxLayout()
        model_layout.addWidget(model_label)
        model_layout.addWidget(load_button)

        # Chat display
        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        self.chat_display.setContextMenuPolicy(Qt.CustomContextMenu)
        self.chat_display.customContextMenuRequested.connect(self.show_context_menu)

        # User input
        self.user_input = QLineEdit()
        self.user_input.returnPressed.connect(self.send_message)
        send_button = QPushButton("Send")
        send_button.clicked.connect(self.send_message)

        input_layout = QHBoxLayout()
        input_layout.addWidget(self.user_input)
        input_layout.addWidget(send_button)

        # Progress bar
        self.progress_bar = QProgressBar()
        self.progress_bar.hide()

        # Clear conversation button
        clear_button = QPushButton("Clear Conversation")
        clear_button.clicked.connect(self.clear_conversation)

        # Main layout
        main_layout = QVBoxLayout()
        main_layout.addLayout(model_layout)
        main_layout.addWidget(self.chat_display)
        main_layout.addWidget(self.progress_bar)
        main_layout.addLayout(input_layout)
        main_layout.addWidget(clear_button)

        self.setLayout(main_layout)

    def load_model(self):
        model_path, _ = QFileDialog.getOpenFileName(self, "Load GGUF Model", "", "GGUF Files (*.gguf)")
        if model_path:
            try:
                self.model = Llama(model_path=model_path, n_ctx=2048, n_gpu_layers=-1)
                model_name = os.path.basename(model_path)
                self.layout().itemAt(0).itemAt(0).widget().setText(f"Model: {model_name}")
                QMessageBox.information(self, "Success", "Model loaded successfully!")
            except Exception as e:
                error_message = f"Error loading model: {str(e)}"
                QMessageBox.critical(self, "Error", error_message)

    def send_message(self):
        user_message = self.user_input.text()
        if user_message and self.model:
            self.messages.append({"role": "user", "content": user_message})
            self.update_chat_display(f"You: {user_message}")
            self.user_input.clear()

            max_tokens = 500  # Set your desired max tokens here
            self.progress_bar.show()
            self.progress_bar.setRange(0, max_tokens)
            self.progress_bar.setValue(0)

            self.worker = Worker(self.model, self.messages, max_tokens)
            self.worker.finished.connect(self.on_response_finished)
            self.worker.progress.connect(self.on_response_progress)
            self.worker.start()

    def on_response_finished(self, assistant_message):
        self.progress_bar.hide()
        self.messages.append({"role": "assistant", "content": assistant_message})
        self.update_chat_display(f"Assistant: {assistant_message}")

        # Python Code Download (Check for triple backticks)
        if assistant_message.startswith("```python") and assistant_message.endswith("```"):
            self.offer_code_download(assistant_message)

    def on_response_progress(self, current_tokens, total_tokens):
        self.progress_bar.setValue(current_tokens)

    def offer_code_download(self, code):
        reply = QMessageBox.question(self, "Download Code", 
                                     "The assistant generated Python code. Do you want to download it?",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            file_path, _ = QFileDialog.getSaveFileName(self, "Save Python Code", "code.py", "Python Files (*.py)")
            if file_path:
                try:
                    with open(file_path, "w") as f:
                        f.write(code.strip("```python").strip("```"))
                    QMessageBox.information(self, "Success", "Code saved successfully!")
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Error saving code: {str(e)}")

    def update_chat_display(self, message):
        self.chat_display.append(message + "\n")
        self.chat_display.verticalScrollBar().setValue(self.chat_display.verticalScrollBar().maximum())

    def clear_conversation(self):
        self.messages = [
            {"role": "system", "content": "You are a helpful AI assistant."}
        ]
        self.chat_display.clear()

    def show_context_menu(self, point):
        menu = QMenu(self)
        copy_action = menu.addAction("Copy")
        copy_action.triggered.connect(self.copy_text)
        menu.exec_(self.chat_display.mapToGlobal(point))

    def copy_text(self):
        cursor = self.chat_display.textCursor()
        if cursor.hasSelection():
            text = cursor.selectedText()
            QApplication.clipboard().setText(text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    gui = ChatbotGUI()
    gui.show()
    sys.exit(app.exec_())
```

## Training and finetuning cost
It takes 6 days to pretrain AMD-Llama-135m on 4 MI250 nodes each of which has 4 MI250 GPUs (8 virtual GPU cards, 64G memory for each). 
It takes 4 days to finetune AMD-Llama-135m-code on 4 MI250 GPUs. 
It takes 11T disk space to store raw and processed SlimPajama, project gutenberg and Starcoder datasets.

#### License
Copyright (c) 2018-2024 Advanced Micro Devices, Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.