2023-05-01 09:10:05 -04:00
|
|
|
#include "chatllm.h"
|
2024-06-04 14:47:11 -04:00
|
|
|
|
2024-07-25 10:04:47 -04:00
|
|
|
#include "bravesearch.h"
|
2023-05-04 15:31:41 -04:00
|
|
|
#include "chat.h"
|
2024-03-13 18:23:57 -04:00
|
|
|
#include "chatapi.h"
|
2024-02-05 16:46:16 -05:00
|
|
|
#include "localdocs.h"
|
2023-06-27 11:54:34 -04:00
|
|
|
#include "mysettings.h"
|
2024-06-04 14:47:11 -04:00
|
|
|
#include "network.h"
|
|
|
|
|
|
|
|
#include <QDataStream>
|
|
|
|
#include <QDebug>
|
|
|
|
#include <QFile>
|
|
|
|
#include <QGlobalStatic>
|
2024-07-25 10:04:47 -04:00
|
|
|
#include <QGuiApplication>
|
2024-06-04 14:47:11 -04:00
|
|
|
#include <QIODevice>
|
|
|
|
#include <QJsonDocument>
|
|
|
|
#include <QJsonObject>
|
|
|
|
#include <QMutex>
|
|
|
|
#include <QMutexLocker>
|
|
|
|
#include <QSet>
|
2024-06-24 18:49:23 -04:00
|
|
|
#include <QStringList>
|
2024-06-04 14:47:11 -04:00
|
|
|
#include <QWaitCondition>
|
|
|
|
#include <Qt>
|
|
|
|
#include <QtLogging>
|
2023-05-01 09:10:05 -04:00
|
|
|
|
2024-05-01 16:15:48 -04:00
|
|
|
#include <algorithm>
|
|
|
|
#include <cctype>
|
|
|
|
#include <cmath>
|
|
|
|
#include <cstddef>
|
|
|
|
#include <functional>
|
|
|
|
#include <limits>
|
2024-06-04 14:47:11 -04:00
|
|
|
#include <optional>
|
2024-06-24 18:49:23 -04:00
|
|
|
#include <string_view>
|
2024-05-01 16:15:48 -04:00
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
|
|
|
|
2024-06-24 18:49:23 -04:00
|
|
|
using namespace Qt::Literals::StringLiterals;
|
|
|
|
|
2023-05-01 09:10:05 -04:00
|
|
|
//#define DEBUG
|
2023-05-13 19:05:35 -04:00
|
|
|
//#define DEBUG_MODEL_LOADING
|
2023-05-01 09:10:05 -04:00
|
|
|
|
2024-07-18 21:03:18 -04:00
|
|
|
#define GPTJ_INTERNAL_STATE_VERSION 0 // GPT-J is gone but old chats still use this
|
2023-05-08 17:23:02 -04:00
|
|
|
#define LLAMA_INTERNAL_STATE_VERSION 0
|
|
|
|
|
2023-05-13 19:05:35 -04:00
|
|
|
class LLModelStore {
|
|
|
|
public:
|
|
|
|
static LLModelStore *globalInstance();
|
|
|
|
|
|
|
|
LLModelInfo acquireModel(); // will block until llmodel is ready
|
2024-05-15 14:07:03 -04:00
|
|
|
void releaseModel(LLModelInfo &&info); // must be called when you are done
|
|
|
|
void destroy();
|
2023-05-13 19:05:35 -04:00
|
|
|
|
|
|
|
private:
|
|
|
|
LLModelStore()
|
|
|
|
{
|
|
|
|
// seed with empty model
|
2024-05-15 14:07:03 -04:00
|
|
|
m_availableModel = LLModelInfo();
|
2023-05-13 19:05:35 -04:00
|
|
|
}
|
|
|
|
~LLModelStore() {}
|
2024-05-15 14:07:03 -04:00
|
|
|
std::optional<LLModelInfo> m_availableModel;
|
2023-05-13 19:05:35 -04:00
|
|
|
QMutex m_mutex;
|
|
|
|
QWaitCondition m_condition;
|
|
|
|
friend class MyLLModelStore;
|
|
|
|
};
|
|
|
|
|
|
|
|
class MyLLModelStore : public LLModelStore { };
|
|
|
|
Q_GLOBAL_STATIC(MyLLModelStore, storeInstance)
|
|
|
|
LLModelStore *LLModelStore::globalInstance()
|
|
|
|
{
|
|
|
|
return storeInstance();
|
|
|
|
}
|
|
|
|
|
|
|
|
LLModelInfo LLModelStore::acquireModel()
|
|
|
|
{
|
|
|
|
QMutexLocker locker(&m_mutex);
|
2024-05-15 14:07:03 -04:00
|
|
|
while (!m_availableModel)
|
2023-05-13 19:05:35 -04:00
|
|
|
m_condition.wait(locker.mutex());
|
2024-05-15 14:07:03 -04:00
|
|
|
auto first = std::move(*m_availableModel);
|
|
|
|
m_availableModel.reset();
|
|
|
|
return first;
|
2023-05-13 19:05:35 -04:00
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
void LLModelStore::releaseModel(LLModelInfo &&info)
|
2023-05-13 19:05:35 -04:00
|
|
|
{
|
|
|
|
QMutexLocker locker(&m_mutex);
|
2024-05-15 14:07:03 -04:00
|
|
|
Q_ASSERT(!m_availableModel);
|
|
|
|
m_availableModel = std::move(info);
|
2023-05-13 19:05:35 -04:00
|
|
|
m_condition.wakeAll();
|
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
void LLModelStore::destroy()
|
|
|
|
{
|
|
|
|
QMutexLocker locker(&m_mutex);
|
|
|
|
m_availableModel.reset();
|
|
|
|
}
|
|
|
|
|
2024-06-26 15:26:27 -04:00
|
|
|
void LLModelInfo::resetModel(ChatLLM *cllm, LLModel *model) {
|
|
|
|
this->model.reset(model);
|
|
|
|
fallbackReason.reset();
|
|
|
|
emit cllm->loadedModelInfoChanged();
|
|
|
|
}
|
|
|
|
|
2023-05-13 19:33:19 -04:00
|
|
|
ChatLLM::ChatLLM(Chat *parent, bool isServer)
|
2023-05-01 09:10:05 -04:00
|
|
|
: QObject{nullptr}
|
|
|
|
, m_promptResponseTokens(0)
|
2023-05-11 16:46:25 -04:00
|
|
|
, m_promptTokens(0)
|
2024-08-07 11:25:24 -04:00
|
|
|
, m_restoringFromText(false)
|
2024-02-07 09:37:59 -05:00
|
|
|
, m_shouldBeLoaded(false)
|
|
|
|
, m_forceUnloadModel(false)
|
2024-03-06 12:59:34 -05:00
|
|
|
, m_markedForDeletion(false)
|
2023-06-19 18:26:04 -04:00
|
|
|
, m_stopGenerating(false)
|
2023-06-19 14:34:53 -04:00
|
|
|
, m_timer(nullptr)
|
2023-05-13 19:33:19 -04:00
|
|
|
, m_isServer(isServer)
|
2023-06-27 11:54:34 -04:00
|
|
|
, m_forceMetal(MySettings::globalInstance()->forceMetal())
|
|
|
|
, m_reloadingToChangeVariant(false)
|
2023-07-01 11:34:21 -04:00
|
|
|
, m_processedSystemPrompt(false)
|
2023-10-10 16:43:02 -04:00
|
|
|
, m_restoreStateFromText(false)
|
2024-07-25 10:04:47 -04:00
|
|
|
, m_maybeToolCall(false)
|
2023-05-01 09:10:05 -04:00
|
|
|
{
|
|
|
|
moveToThread(&m_llmThread);
|
2023-06-01 14:13:12 -04:00
|
|
|
connect(this, &ChatLLM::shouldBeLoadedChanged, this, &ChatLLM::handleShouldBeLoadedChanged,
|
|
|
|
Qt::QueuedConnection); // explicitly queued
|
2024-05-15 14:07:03 -04:00
|
|
|
connect(this, &ChatLLM::trySwitchContextRequested, this, &ChatLLM::trySwitchContextOfLoadedModel,
|
2024-02-07 09:37:59 -05:00
|
|
|
Qt::QueuedConnection); // explicitly queued
|
2023-06-19 19:51:28 -04:00
|
|
|
connect(parent, &Chat::idChanged, this, &ChatLLM::handleChatIdChanged);
|
2023-06-19 14:34:53 -04:00
|
|
|
connect(&m_llmThread, &QThread::started, this, &ChatLLM::handleThreadStarted);
|
2023-06-27 11:54:34 -04:00
|
|
|
connect(MySettings::globalInstance(), &MySettings::forceMetalChanged, this, &ChatLLM::handleForceMetalChanged);
|
2023-09-13 10:32:08 -04:00
|
|
|
connect(MySettings::globalInstance(), &MySettings::deviceChanged, this, &ChatLLM::handleDeviceChanged);
|
2023-06-01 14:13:12 -04:00
|
|
|
|
|
|
|
// The following are blocking operations and will block the llm thread
|
|
|
|
connect(this, &ChatLLM::requestRetrieveFromDB, LocalDocs::globalInstance()->database(), &Database::retrieveFromDB,
|
|
|
|
Qt::BlockingQueuedConnection);
|
|
|
|
|
2023-06-19 19:51:28 -04:00
|
|
|
m_llmThread.setObjectName(parent->id());
|
2023-05-01 09:10:05 -04:00
|
|
|
m_llmThread.start();
|
|
|
|
}
|
|
|
|
|
2023-05-12 14:06:03 -04:00
|
|
|
ChatLLM::~ChatLLM()
|
|
|
|
{
|
2024-03-06 16:42:59 -05:00
|
|
|
destroy();
|
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
void ChatLLM::destroy()
|
|
|
|
{
|
2023-07-09 14:42:11 -04:00
|
|
|
m_stopGenerating = true;
|
2023-05-12 14:06:03 -04:00
|
|
|
m_llmThread.quit();
|
|
|
|
m_llmThread.wait();
|
2023-05-13 19:05:35 -04:00
|
|
|
|
|
|
|
// The only time we should have a model loaded here is on shutdown
|
|
|
|
// as we explicitly unload the model in all other circumstances
|
|
|
|
if (isModelLoaded()) {
|
2024-06-26 15:26:27 -04:00
|
|
|
m_llModelInfo.resetModel(this);
|
2023-05-13 19:05:35 -04:00
|
|
|
}
|
2023-05-12 14:06:03 -04:00
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
void ChatLLM::destroyStore()
|
|
|
|
{
|
|
|
|
LLModelStore::globalInstance()->destroy();
|
|
|
|
}
|
|
|
|
|
2023-06-19 14:34:53 -04:00
|
|
|
void ChatLLM::handleThreadStarted()
|
|
|
|
{
|
|
|
|
m_timer = new TokenTimer(this);
|
|
|
|
connect(m_timer, &TokenTimer::report, this, &ChatLLM::reportSpeed);
|
|
|
|
emit threadStarted();
|
|
|
|
}
|
|
|
|
|
2023-06-27 11:54:34 -04:00
|
|
|
void ChatLLM::handleForceMetalChanged(bool forceMetal)
|
|
|
|
{
|
2024-05-15 15:27:50 -04:00
|
|
|
#if defined(Q_OS_MAC) && defined(__aarch64__)
|
2023-06-27 11:54:34 -04:00
|
|
|
m_forceMetal = forceMetal;
|
|
|
|
if (isModelLoaded() && m_shouldBeLoaded) {
|
|
|
|
m_reloadingToChangeVariant = true;
|
|
|
|
unloadModel();
|
|
|
|
reloadModel();
|
|
|
|
m_reloadingToChangeVariant = false;
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
2023-09-13 10:32:08 -04:00
|
|
|
void ChatLLM::handleDeviceChanged()
|
|
|
|
{
|
|
|
|
if (isModelLoaded() && m_shouldBeLoaded) {
|
|
|
|
m_reloadingToChangeVariant = true;
|
|
|
|
unloadModel();
|
|
|
|
reloadModel();
|
|
|
|
m_reloadingToChangeVariant = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-04 15:31:41 -04:00
|
|
|
bool ChatLLM::loadDefaultModel()
|
2023-05-01 09:10:05 -04:00
|
|
|
{
|
2023-06-22 15:44:49 -04:00
|
|
|
ModelInfo defaultModel = ModelList::globalInstance()->defaultModelInfo();
|
2023-07-01 11:34:21 -04:00
|
|
|
if (defaultModel.filename().isEmpty()) {
|
2024-06-24 18:49:23 -04:00
|
|
|
emit modelLoadingError(u"Could not find any model to load"_qs);
|
2023-05-01 09:10:05 -04:00
|
|
|
return false;
|
|
|
|
}
|
2023-06-22 15:44:49 -04:00
|
|
|
return loadModel(defaultModel);
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
void ChatLLM::trySwitchContextOfLoadedModel(const ModelInfo &modelInfo)
|
2024-02-07 09:37:59 -05:00
|
|
|
{
|
|
|
|
// We're trying to see if the store already has the model fully loaded that we wish to use
|
|
|
|
// and if so we just acquire it from the store and switch the context and return true. If the
|
|
|
|
// store doesn't have it or we're already loaded or in any other case just return false.
|
|
|
|
|
|
|
|
// If we're already loaded or a server or we're reloading to change the variant/device or the
|
|
|
|
// modelInfo is empty, then this should fail
|
2024-05-15 14:07:03 -04:00
|
|
|
if (
|
|
|
|
isModelLoaded() || m_isServer || m_reloadingToChangeVariant || modelInfo.name().isEmpty() || !m_shouldBeLoaded
|
|
|
|
) {
|
|
|
|
emit trySwitchContextOfLoadedModelCompleted(0);
|
|
|
|
return;
|
2024-02-07 09:37:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
QString filePath = modelInfo.dirpath + modelInfo.filename();
|
|
|
|
QFileInfo fileInfo(filePath);
|
|
|
|
|
2024-06-26 15:26:27 -04:00
|
|
|
acquireModel();
|
2024-02-07 09:37:59 -05:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "acquired model from store" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2024-02-07 09:37:59 -05:00
|
|
|
#endif
|
|
|
|
|
|
|
|
// The store gave us no already loaded model, the wrong type of model, then give it back to the
|
|
|
|
// store and fail
|
2024-05-15 14:07:03 -04:00
|
|
|
if (!m_llModelInfo.model || m_llModelInfo.fileInfo != fileInfo || !m_shouldBeLoaded) {
|
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
|
|
|
emit trySwitchContextOfLoadedModelCompleted(0);
|
|
|
|
return;
|
2024-02-07 09:37:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "store had our model" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2024-02-07 09:37:59 -05:00
|
|
|
#endif
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
emit trySwitchContextOfLoadedModelCompleted(2);
|
2024-02-07 09:37:59 -05:00
|
|
|
|
|
|
|
// Restore, signal and process
|
|
|
|
restoreState();
|
|
|
|
emit modelLoadingPercentageChanged(1.0f);
|
2024-05-15 14:07:03 -04:00
|
|
|
emit trySwitchContextOfLoadedModelCompleted(0);
|
2024-02-07 09:37:59 -05:00
|
|
|
processSystemPrompt();
|
|
|
|
}
|
|
|
|
|
2023-06-22 15:44:49 -04:00
|
|
|
bool ChatLLM::loadModel(const ModelInfo &modelInfo)
|
2023-05-01 09:10:05 -04:00
|
|
|
{
|
2023-05-13 19:05:35 -04:00
|
|
|
// This is a complicated method because N different possible threads are interested in the outcome
|
|
|
|
// of this method. Why? Because we have a main/gui thread trying to monitor the state of N different
|
|
|
|
// possible chat threads all vying for a single resource - the currently loaded model - as the user
|
|
|
|
// switches back and forth between chats. It is important for our main/gui thread to never block
|
|
|
|
// but simultaneously always have up2date information with regards to which chat has the model loaded
|
|
|
|
// and what the type and name of that model is. I've tried to comment extensively in this method
|
|
|
|
// to provide an overview of what we're doing here.
|
|
|
|
|
|
|
|
// We're already loaded with this model
|
2023-06-22 15:44:49 -04:00
|
|
|
if (isModelLoaded() && this->modelInfo() == modelInfo)
|
2023-05-01 09:10:05 -04:00
|
|
|
return true;
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
// reset status
|
|
|
|
emit modelLoadingPercentageChanged(std::numeric_limits<float>::min()); // small non-zero positive value
|
|
|
|
emit modelLoadingError("");
|
|
|
|
m_pristineLoadedState = false;
|
|
|
|
|
2023-07-01 11:34:21 -04:00
|
|
|
QString filePath = modelInfo.dirpath + modelInfo.filename();
|
2023-05-13 19:05:35 -04:00
|
|
|
QFileInfo fileInfo(filePath);
|
|
|
|
|
|
|
|
// We have a live model, but it isn't the one we want
|
|
|
|
bool alreadyAcquired = isModelLoaded();
|
|
|
|
if (alreadyAcquired) {
|
2023-05-30 18:17:59 -04:00
|
|
|
resetContext();
|
2023-05-13 19:05:35 -04:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "already acquired model deleted" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-13 19:05:35 -04:00
|
|
|
#endif
|
2024-06-26 15:26:27 -04:00
|
|
|
m_llModelInfo.resetModel(this);
|
2023-05-13 19:33:19 -04:00
|
|
|
} else if (!m_isServer) {
|
2023-05-13 19:05:35 -04:00
|
|
|
// This is a blocking call that tries to retrieve the model we need from the model store.
|
|
|
|
// If it succeeds, then we just have to restore state. If the store has never had a model
|
|
|
|
// returned to it, then the modelInfo.model pointer should be null which will happen on startup
|
2024-06-26 15:26:27 -04:00
|
|
|
acquireModel();
|
2023-05-13 19:05:35 -04:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "acquired model from store" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-13 19:05:35 -04:00
|
|
|
#endif
|
|
|
|
// At this point it is possible that while we were blocked waiting to acquire the model from the
|
|
|
|
// store, that our state was changed to not be loaded. If this is the case, release the model
|
|
|
|
// back into the store and quit loading
|
|
|
|
if (!m_shouldBeLoaded) {
|
2023-05-13 19:33:19 -04:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "no longer need model" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-13 19:33:19 -04:00
|
|
|
#endif
|
2024-05-15 14:07:03 -04:00
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
2024-02-07 09:37:59 -05:00
|
|
|
emit modelLoadingPercentageChanged(0.0f);
|
2023-05-13 19:05:35 -04:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the store just gave us exactly the model we were looking for
|
2023-06-27 11:54:34 -04:00
|
|
|
if (m_llModelInfo.model && m_llModelInfo.fileInfo == fileInfo && !m_reloadingToChangeVariant) {
|
2023-05-13 19:05:35 -04:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "store had our model" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-13 19:05:35 -04:00
|
|
|
#endif
|
|
|
|
restoreState();
|
2024-02-07 09:37:59 -05:00
|
|
|
emit modelLoadingPercentageChanged(1.0f);
|
2023-07-09 14:52:08 -04:00
|
|
|
setModelInfo(modelInfo);
|
2023-07-01 11:34:21 -04:00
|
|
|
Q_ASSERT(!m_modelInfo.filename().isEmpty());
|
|
|
|
if (m_modelInfo.filename().isEmpty())
|
2024-06-24 18:49:23 -04:00
|
|
|
emit modelLoadingError(u"Modelinfo is left null for %1"_s.arg(modelInfo.filename()));
|
2023-07-01 11:34:21 -04:00
|
|
|
else
|
|
|
|
processSystemPrompt();
|
2023-05-13 19:05:35 -04:00
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
// Release the memory since we have to switch to a different model.
|
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "deleting model" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-13 19:05:35 -04:00
|
|
|
#endif
|
2024-06-26 15:26:27 -04:00
|
|
|
m_llModelInfo.resetModel(this);
|
2023-05-13 19:05:35 -04:00
|
|
|
}
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
2023-05-13 19:05:35 -04:00
|
|
|
// Guarantee we've released the previous models memory
|
2023-06-22 15:44:49 -04:00
|
|
|
Q_ASSERT(!m_llModelInfo.model);
|
2023-05-13 19:05:35 -04:00
|
|
|
|
|
|
|
// Store the file info in the modelInfo in case we have an error loading
|
2023-06-22 15:44:49 -04:00
|
|
|
m_llModelInfo.fileInfo = fileInfo;
|
2023-05-01 09:10:05 -04:00
|
|
|
|
2023-05-13 19:05:35 -04:00
|
|
|
if (fileInfo.exists()) {
|
2024-04-25 13:16:52 -04:00
|
|
|
QVariantMap modelLoadProps;
|
2024-03-13 18:23:57 -04:00
|
|
|
if (modelInfo.isOnline) {
|
2023-05-14 20:12:15 -04:00
|
|
|
QString apiKey;
|
2024-07-25 10:02:52 -04:00
|
|
|
QString requestUrl;
|
2024-03-13 18:23:57 -04:00
|
|
|
QString modelName;
|
2023-05-14 20:12:15 -04:00
|
|
|
{
|
|
|
|
QFile file(filePath);
|
2024-04-18 14:51:13 -04:00
|
|
|
bool success = file.open(QIODeviceBase::ReadOnly);
|
|
|
|
(void)success;
|
|
|
|
Q_ASSERT(success);
|
|
|
|
QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
|
2024-03-13 18:23:57 -04:00
|
|
|
QJsonObject obj = doc.object();
|
|
|
|
apiKey = obj["apiKey"].toString();
|
|
|
|
modelName = obj["modelName"].toString();
|
2024-07-25 10:02:52 -04:00
|
|
|
if (modelInfo.isCompatibleApi) {
|
|
|
|
QString baseUrl(obj["baseUrl"].toString());
|
|
|
|
QUrl apiUrl(QUrl::fromUserInput(baseUrl));
|
|
|
|
if (!Network::isHttpUrlValid(apiUrl)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
QString currentPath(apiUrl.path());
|
|
|
|
QString suffixPath("%1/chat/completions");
|
|
|
|
apiUrl.setPath(suffixPath.arg(currentPath));
|
|
|
|
requestUrl = apiUrl.toString();
|
|
|
|
} else {
|
|
|
|
requestUrl = modelInfo.url();
|
|
|
|
}
|
2023-05-14 20:12:15 -04:00
|
|
|
}
|
2024-03-13 18:23:57 -04:00
|
|
|
m_llModelType = LLModelType::API_;
|
|
|
|
ChatAPI *model = new ChatAPI();
|
|
|
|
model->setModelName(modelName);
|
2024-07-25 10:02:52 -04:00
|
|
|
model->setRequestURL(requestUrl);
|
2023-05-14 20:12:15 -04:00
|
|
|
model->setAPIKey(apiKey);
|
2024-06-26 15:26:27 -04:00
|
|
|
m_llModelInfo.resetModel(this, model);
|
2024-06-28 12:57:57 -04:00
|
|
|
} else if (!loadNewModel(modelInfo, modelLoadProps)) {
|
|
|
|
return false; // m_shouldBeLoaded became false
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
2023-05-13 19:05:35 -04:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "new model" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-13 19:05:35 -04:00
|
|
|
#endif
|
2023-05-07 11:24:07 -04:00
|
|
|
restoreState();
|
|
|
|
#if defined(DEBUG)
|
2023-06-19 19:51:28 -04:00
|
|
|
qDebug() << "modelLoadedChanged" << m_llmThread.objectName();
|
2023-05-13 19:05:35 -04:00
|
|
|
fflush(stdout);
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2024-02-07 09:37:59 -05:00
|
|
|
emit modelLoadingPercentageChanged(isModelLoaded() ? 1.0f : 0.0f);
|
2024-06-26 15:26:27 -04:00
|
|
|
emit loadedModelInfoChanged();
|
2023-05-01 09:10:05 -04:00
|
|
|
|
2024-04-25 13:16:52 -04:00
|
|
|
modelLoadProps.insert("requestedDevice", MySettings::globalInstance()->device());
|
|
|
|
modelLoadProps.insert("model", modelInfo.filename());
|
|
|
|
Network::globalInstance()->trackChatEvent("model_load", modelLoadProps);
|
2023-05-04 15:31:41 -04:00
|
|
|
} else {
|
2023-05-13 19:33:19 -04:00
|
|
|
if (!m_isServer)
|
2024-05-15 14:07:03 -04:00
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo)); // release back into the store
|
2024-06-26 15:26:27 -04:00
|
|
|
resetModel();
|
2024-06-24 18:49:23 -04:00
|
|
|
emit modelLoadingError(u"Could not find file for model %1"_s.arg(modelInfo.filename()));
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
2023-09-21 12:41:48 -04:00
|
|
|
if (m_llModelInfo.model) {
|
2023-06-22 15:44:49 -04:00
|
|
|
setModelInfo(modelInfo);
|
2023-09-21 12:41:48 -04:00
|
|
|
processSystemPrompt();
|
|
|
|
}
|
2024-05-15 14:07:03 -04:00
|
|
|
return bool(m_llModelInfo.model);
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
2024-06-28 12:57:57 -04:00
|
|
|
/* Returns false if the model should no longer be loaded (!m_shouldBeLoaded).
|
|
|
|
* Otherwise returns true, even on error. */
|
|
|
|
bool ChatLLM::loadNewModel(const ModelInfo &modelInfo, QVariantMap &modelLoadProps)
|
|
|
|
{
|
|
|
|
QElapsedTimer modelLoadTimer;
|
|
|
|
modelLoadTimer.start();
|
|
|
|
|
|
|
|
QString requestedDevice = MySettings::globalInstance()->device();
|
|
|
|
int n_ctx = MySettings::globalInstance()->modelContextLength(modelInfo);
|
|
|
|
m_ctx.n_ctx = n_ctx;
|
|
|
|
int ngl = MySettings::globalInstance()->modelGpuLayers(modelInfo);
|
|
|
|
|
|
|
|
std::string backend = "auto";
|
|
|
|
#ifdef Q_OS_MAC
|
|
|
|
if (requestedDevice == "CPU") {
|
|
|
|
backend = "cpu";
|
|
|
|
} else if (m_forceMetal) {
|
|
|
|
#ifdef __aarch64__
|
|
|
|
backend = "metal";
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
#else // !defined(Q_OS_MAC)
|
|
|
|
if (requestedDevice.startsWith("CUDA: "))
|
|
|
|
backend = "cuda";
|
|
|
|
#endif
|
|
|
|
|
|
|
|
QString filePath = modelInfo.dirpath + modelInfo.filename();
|
|
|
|
|
|
|
|
auto construct = [this, &filePath, &modelInfo, &modelLoadProps, n_ctx](std::string const &backend) {
|
|
|
|
QString constructError;
|
|
|
|
m_llModelInfo.resetModel(this);
|
|
|
|
try {
|
|
|
|
auto *model = LLModel::Implementation::construct(filePath.toStdString(), backend, n_ctx);
|
|
|
|
m_llModelInfo.resetModel(this, model);
|
|
|
|
} catch (const LLModel::MissingImplementationError &e) {
|
|
|
|
modelLoadProps.insert("error", "missing_model_impl");
|
|
|
|
constructError = e.what();
|
|
|
|
} catch (const LLModel::UnsupportedModelError &e) {
|
|
|
|
modelLoadProps.insert("error", "unsupported_model_file");
|
|
|
|
constructError = e.what();
|
|
|
|
} catch (const LLModel::BadArchError &e) {
|
|
|
|
constructError = e.what();
|
|
|
|
modelLoadProps.insert("error", "unsupported_model_arch");
|
|
|
|
modelLoadProps.insert("model_arch", QString::fromStdString(e.arch()));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!m_llModelInfo.model) {
|
|
|
|
if (!m_isServer)
|
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
|
|
|
resetModel();
|
|
|
|
emit modelLoadingError(u"Error loading %1: %2"_s.arg(modelInfo.filename(), constructError));
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
m_llModelInfo.model->setProgressCallback([this](float progress) -> bool {
|
|
|
|
progress = std::max(progress, std::numeric_limits<float>::min()); // keep progress above zero
|
|
|
|
emit modelLoadingPercentageChanged(progress);
|
|
|
|
return m_shouldBeLoaded;
|
|
|
|
});
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
|
|
|
if (!construct(backend))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
if (m_llModelInfo.model->isModelBlacklisted(filePath.toStdString())) {
|
|
|
|
static QSet<QString> warned;
|
|
|
|
auto fname = modelInfo.filename();
|
|
|
|
if (!warned.contains(fname)) {
|
|
|
|
emit modelLoadingWarning(
|
|
|
|
u"%1 is known to be broken. Please get a replacement via the download dialog."_s.arg(fname)
|
|
|
|
);
|
|
|
|
warned.insert(fname); // don't warn again until restart
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
auto approxDeviceMemGB = [](const LLModel::GPUDevice *dev) {
|
|
|
|
float memGB = dev->heapSize / float(1024 * 1024 * 1024);
|
|
|
|
return std::floor(memGB * 10.f) / 10.f; // truncate to 1 decimal place
|
|
|
|
};
|
|
|
|
|
|
|
|
std::vector<LLModel::GPUDevice> availableDevices;
|
|
|
|
const LLModel::GPUDevice *defaultDevice = nullptr;
|
|
|
|
{
|
|
|
|
const size_t requiredMemory = m_llModelInfo.model->requiredMem(filePath.toStdString(), n_ctx, ngl);
|
|
|
|
availableDevices = m_llModelInfo.model->availableGPUDevices(requiredMemory);
|
|
|
|
// Pick the best device
|
|
|
|
// NB: relies on the fact that Kompute devices are listed first
|
|
|
|
if (!availableDevices.empty() && availableDevices.front().type == 2 /*a discrete gpu*/) {
|
|
|
|
defaultDevice = &availableDevices.front();
|
|
|
|
float memGB = defaultDevice->heapSize / float(1024 * 1024 * 1024);
|
|
|
|
memGB = std::floor(memGB * 10.f) / 10.f; // truncate to 1 decimal place
|
|
|
|
modelLoadProps.insert("default_device", QString::fromStdString(defaultDevice->name));
|
|
|
|
modelLoadProps.insert("default_device_mem", approxDeviceMemGB(defaultDevice));
|
|
|
|
modelLoadProps.insert("default_device_backend", QString::fromStdString(defaultDevice->backendName()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bool actualDeviceIsCPU = true;
|
|
|
|
|
|
|
|
#if defined(Q_OS_MAC) && defined(__aarch64__)
|
|
|
|
if (m_llModelInfo.model->implementation().buildVariant() == "metal")
|
|
|
|
actualDeviceIsCPU = false;
|
|
|
|
#else
|
|
|
|
if (requestedDevice != "CPU") {
|
|
|
|
const auto *device = defaultDevice;
|
|
|
|
if (requestedDevice != "Auto") {
|
|
|
|
// Use the selected device
|
|
|
|
for (const LLModel::GPUDevice &d : availableDevices) {
|
|
|
|
if (QString::fromStdString(d.selectionName()) == requestedDevice) {
|
|
|
|
device = &d;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
std::string unavail_reason;
|
|
|
|
if (!device) {
|
|
|
|
// GPU not available
|
|
|
|
} else if (!m_llModelInfo.model->initializeGPUDevice(device->index, &unavail_reason)) {
|
|
|
|
m_llModelInfo.fallbackReason = QString::fromStdString(unavail_reason);
|
|
|
|
} else {
|
|
|
|
actualDeviceIsCPU = false;
|
|
|
|
modelLoadProps.insert("requested_device_mem", approxDeviceMemGB(device));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
|
|
|
bool success = m_llModelInfo.model->loadModel(filePath.toStdString(), n_ctx, ngl);
|
|
|
|
|
|
|
|
if (!m_shouldBeLoaded) {
|
|
|
|
m_llModelInfo.resetModel(this);
|
|
|
|
if (!m_isServer)
|
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
|
|
|
resetModel();
|
|
|
|
emit modelLoadingPercentageChanged(0.0f);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (actualDeviceIsCPU) {
|
|
|
|
// we asked llama.cpp to use the CPU
|
|
|
|
} else if (!success) {
|
|
|
|
// llama_init_from_file returned nullptr
|
|
|
|
m_llModelInfo.fallbackReason = "GPU loading failed (out of VRAM?)";
|
|
|
|
modelLoadProps.insert("cpu_fallback_reason", "gpu_load_failed");
|
|
|
|
|
|
|
|
// For CUDA, make sure we don't use the GPU at all - ngl=0 still offloads matmuls
|
|
|
|
if (backend == "cuda" && !construct("auto"))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
success = m_llModelInfo.model->loadModel(filePath.toStdString(), n_ctx, 0);
|
|
|
|
|
|
|
|
if (!m_shouldBeLoaded) {
|
|
|
|
m_llModelInfo.resetModel(this);
|
|
|
|
if (!m_isServer)
|
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
|
|
|
resetModel();
|
|
|
|
emit modelLoadingPercentageChanged(0.0f);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
} else if (!m_llModelInfo.model->usingGPUDevice()) {
|
|
|
|
// ggml_vk_init was not called in llama.cpp
|
|
|
|
// We might have had to fallback to CPU after load if the model is not possible to accelerate
|
|
|
|
// for instance if the quantization method is not supported on Vulkan yet
|
|
|
|
m_llModelInfo.fallbackReason = "model or quant has no GPU support";
|
|
|
|
modelLoadProps.insert("cpu_fallback_reason", "gpu_unsupported_model");
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!success) {
|
|
|
|
m_llModelInfo.resetModel(this);
|
|
|
|
if (!m_isServer)
|
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
|
|
|
resetModel();
|
|
|
|
emit modelLoadingError(u"Could not load model due to invalid model file for %1"_s.arg(modelInfo.filename()));
|
|
|
|
modelLoadProps.insert("error", "loadmodel_failed");
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (m_llModelInfo.model->implementation().modelType()[0]) {
|
|
|
|
case 'L': m_llModelType = LLModelType::LLAMA_; break;
|
|
|
|
default:
|
|
|
|
{
|
|
|
|
m_llModelInfo.resetModel(this);
|
|
|
|
if (!m_isServer)
|
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
|
|
|
resetModel();
|
|
|
|
emit modelLoadingError(u"Could not determine model type for %1"_s.arg(modelInfo.filename()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
modelLoadProps.insert("$duration", modelLoadTimer.elapsed() / 1000.);
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
2023-05-01 09:10:05 -04:00
|
|
|
bool ChatLLM::isModelLoaded() const
|
|
|
|
{
|
2023-06-22 15:44:49 -04:00
|
|
|
return m_llModelInfo.model && m_llModelInfo.model->isModelLoaded();
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
2024-06-24 18:49:23 -04:00
|
|
|
std::string remove_leading_whitespace(const std::string& input)
|
|
|
|
{
|
2023-10-28 16:53:42 -04:00
|
|
|
auto first_non_whitespace = std::find_if(input.begin(), input.end(), [](unsigned char c) {
|
|
|
|
return !std::isspace(c);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (first_non_whitespace == input.end())
|
|
|
|
return std::string();
|
|
|
|
|
|
|
|
return std::string(first_non_whitespace, input.end());
|
|
|
|
}
|
|
|
|
|
2024-06-24 18:49:23 -04:00
|
|
|
std::string trim_whitespace(const std::string& input)
|
|
|
|
{
|
2023-10-28 16:53:42 -04:00
|
|
|
auto first_non_whitespace = std::find_if(input.begin(), input.end(), [](unsigned char c) {
|
|
|
|
return !std::isspace(c);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (first_non_whitespace == input.end())
|
|
|
|
return std::string();
|
|
|
|
|
|
|
|
auto last_non_whitespace = std::find_if(input.rbegin(), input.rend(), [](unsigned char c) {
|
|
|
|
return !std::isspace(c);
|
|
|
|
}).base();
|
|
|
|
|
|
|
|
return std::string(first_non_whitespace, last_non_whitespace);
|
|
|
|
}
|
|
|
|
|
2024-08-01 10:46:36 -04:00
|
|
|
// FIXME(jared): we don't actually have to re-decode the prompt to generate a new response
|
2023-05-01 09:10:05 -04:00
|
|
|
void ChatLLM::regenerateResponse()
|
|
|
|
{
|
2023-05-15 14:08:08 -04:00
|
|
|
// ChatGPT uses a different semantic meaning for n_past than local models. For ChatGPT, the meaning
|
|
|
|
// of n_past is of the number of prompt/response pairs, rather than for total tokens.
|
2024-03-13 18:23:57 -04:00
|
|
|
if (m_llModelType == LLModelType::API_)
|
2023-05-15 14:08:08 -04:00
|
|
|
m_ctx.n_past -= 1;
|
|
|
|
else
|
|
|
|
m_ctx.n_past -= m_promptResponseTokens;
|
2023-05-01 09:10:05 -04:00
|
|
|
m_ctx.n_past = std::max(0, m_ctx.n_past);
|
2023-10-03 12:42:31 -04:00
|
|
|
m_ctx.tokens.erase(m_ctx.tokens.end() - m_promptResponseTokens, m_ctx.tokens.end());
|
2023-05-01 09:10:05 -04:00
|
|
|
m_promptResponseTokens = 0;
|
2023-05-11 16:46:25 -04:00
|
|
|
m_promptTokens = 0;
|
2023-05-01 09:10:05 -04:00
|
|
|
m_response = std::string();
|
2023-06-20 16:14:30 -04:00
|
|
|
emit responseChanged(QString::fromStdString(m_response));
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::resetResponse()
|
|
|
|
{
|
2023-05-11 16:46:25 -04:00
|
|
|
m_promptTokens = 0;
|
2023-05-01 09:10:05 -04:00
|
|
|
m_promptResponseTokens = 0;
|
|
|
|
m_response = std::string();
|
2023-06-20 16:14:30 -04:00
|
|
|
emit responseChanged(QString::fromStdString(m_response));
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::resetContext()
|
|
|
|
{
|
2024-02-27 13:46:47 -05:00
|
|
|
resetResponse();
|
2023-07-01 11:34:21 -04:00
|
|
|
m_processedSystemPrompt = false;
|
2023-05-01 09:10:05 -04:00
|
|
|
m_ctx = LLModel::PromptContext();
|
|
|
|
}
|
|
|
|
|
|
|
|
QString ChatLLM::response() const
|
|
|
|
{
|
|
|
|
return QString::fromStdString(remove_leading_whitespace(m_response));
|
|
|
|
}
|
|
|
|
|
2023-06-22 15:44:49 -04:00
|
|
|
ModelInfo ChatLLM::modelInfo() const
|
2023-05-01 09:10:05 -04:00
|
|
|
{
|
2023-06-22 15:44:49 -04:00
|
|
|
return m_modelInfo;
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
2023-06-22 15:44:49 -04:00
|
|
|
void ChatLLM::setModelInfo(const ModelInfo &modelInfo)
|
2023-05-01 09:10:05 -04:00
|
|
|
{
|
2023-06-22 15:44:49 -04:00
|
|
|
m_modelInfo = modelInfo;
|
|
|
|
emit modelInfoChanged(modelInfo);
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
2024-06-26 15:26:27 -04:00
|
|
|
void ChatLLM::acquireModel() {
|
|
|
|
m_llModelInfo = LLModelStore::globalInstance()->acquireModel();
|
|
|
|
emit loadedModelInfoChanged();
|
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::resetModel() {
|
|
|
|
m_llModelInfo = {};
|
|
|
|
emit loadedModelInfoChanged();
|
|
|
|
}
|
|
|
|
|
2023-06-22 15:44:49 -04:00
|
|
|
void ChatLLM::modelChangeRequested(const ModelInfo &modelInfo)
|
2023-05-01 09:10:05 -04:00
|
|
|
{
|
2024-02-07 09:37:59 -05:00
|
|
|
m_shouldBeLoaded = true;
|
2023-06-22 15:44:49 -04:00
|
|
|
loadModel(modelInfo);
|
2023-05-01 09:10:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
bool ChatLLM::handlePrompt(int32_t token)
|
|
|
|
{
|
2023-06-19 18:23:05 -04:00
|
|
|
// m_promptResponseTokens is related to last prompt/response not
|
2023-05-01 09:10:05 -04:00
|
|
|
// the entire context window which we can reset on regenerate prompt
|
2023-05-07 11:24:07 -04:00
|
|
|
#if defined(DEBUG)
|
2023-06-19 19:51:28 -04:00
|
|
|
qDebug() << "prompt process" << m_llmThread.objectName() << token;
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2023-05-11 16:46:25 -04:00
|
|
|
++m_promptTokens;
|
2023-05-01 09:10:05 -04:00
|
|
|
++m_promptResponseTokens;
|
2023-08-30 09:43:56 -04:00
|
|
|
m_timer->start();
|
2023-05-01 09:10:05 -04:00
|
|
|
return !m_stopGenerating;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool ChatLLM::handleResponse(int32_t token, const std::string &response)
|
|
|
|
{
|
|
|
|
#if defined(DEBUG)
|
|
|
|
printf("%s", response.c_str());
|
|
|
|
fflush(stdout);
|
|
|
|
#endif
|
|
|
|
|
|
|
|
// check for error
|
|
|
|
if (token < 0) {
|
|
|
|
m_response.append(response);
|
2023-10-28 16:53:42 -04:00
|
|
|
emit responseChanged(QString::fromStdString(remove_leading_whitespace(m_response)));
|
2023-05-01 09:10:05 -04:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-07-25 10:04:47 -04:00
|
|
|
// Only valid for llama 3.1 instruct
|
|
|
|
if (m_modelInfo.filename().startsWith("Meta-Llama-3.1-8B-Instruct")) {
|
|
|
|
// Based on https://llama.meta.com/docs/model-cards-and-prompt-formats/llama3_1/#built-in-python-based-tool-calling
|
|
|
|
// For brave_search and wolfram_alpha ipython is always used
|
|
|
|
|
|
|
|
// <|python_tag|>
|
|
|
|
// brave_search.call(query="...")
|
|
|
|
// <|eom_id|>
|
|
|
|
const int eom_id = 128008;
|
|
|
|
const int python_tag = 128010;
|
|
|
|
|
|
|
|
// If we have a built-in tool call, then it should be the first token
|
|
|
|
const bool isFirstResponseToken = m_promptResponseTokens == m_promptTokens;
|
|
|
|
Q_ASSERT(token != python_tag || isFirstResponseToken);
|
|
|
|
if (isFirstResponseToken && token == python_tag) {
|
|
|
|
m_maybeToolCall = true;
|
|
|
|
++m_promptResponseTokens;
|
|
|
|
return !m_stopGenerating;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for end of built-in tool call
|
|
|
|
Q_ASSERT(token != eom_id || !m_maybeToolCall);
|
|
|
|
if (token == eom_id) {
|
|
|
|
++m_promptResponseTokens;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-19 18:23:05 -04:00
|
|
|
// m_promptResponseTokens is related to last prompt/response not
|
2023-05-01 09:10:05 -04:00
|
|
|
// the entire context window which we can reset on regenerate prompt
|
|
|
|
++m_promptResponseTokens;
|
2023-06-19 14:34:53 -04:00
|
|
|
m_timer->inc();
|
2023-05-01 09:10:05 -04:00
|
|
|
Q_ASSERT(!response.empty());
|
|
|
|
m_response.append(response);
|
2024-07-25 10:04:47 -04:00
|
|
|
|
|
|
|
if (!m_maybeToolCall)
|
|
|
|
emit responseChanged(QString::fromStdString(remove_leading_whitespace(m_response)));
|
|
|
|
|
2023-05-01 09:10:05 -04:00
|
|
|
return !m_stopGenerating;
|
|
|
|
}
|
|
|
|
|
2023-07-01 11:34:21 -04:00
|
|
|
bool ChatLLM::prompt(const QList<QString> &collectionList, const QString &prompt)
|
|
|
|
{
|
2023-10-28 16:39:25 -04:00
|
|
|
if (m_restoreStateFromText) {
|
|
|
|
Q_ASSERT(m_state.isEmpty());
|
|
|
|
processRestoreStateFromText();
|
|
|
|
}
|
|
|
|
|
2023-07-01 11:34:21 -04:00
|
|
|
if (!m_processedSystemPrompt)
|
|
|
|
processSystemPrompt();
|
|
|
|
const QString promptTemplate = MySettings::globalInstance()->modelPromptTemplate(m_modelInfo);
|
|
|
|
const int32_t n_predict = MySettings::globalInstance()->modelMaxLength(m_modelInfo);
|
|
|
|
const int32_t top_k = MySettings::globalInstance()->modelTopK(m_modelInfo);
|
|
|
|
const float top_p = MySettings::globalInstance()->modelTopP(m_modelInfo);
|
2024-02-24 17:51:34 -05:00
|
|
|
const float min_p = MySettings::globalInstance()->modelMinP(m_modelInfo);
|
2023-07-01 11:34:21 -04:00
|
|
|
const float temp = MySettings::globalInstance()->modelTemperature(m_modelInfo);
|
|
|
|
const int32_t n_batch = MySettings::globalInstance()->modelPromptBatchSize(m_modelInfo);
|
|
|
|
const float repeat_penalty = MySettings::globalInstance()->modelRepeatPenalty(m_modelInfo);
|
|
|
|
const int32_t repeat_penalty_tokens = MySettings::globalInstance()->modelRepeatPenaltyTokens(m_modelInfo);
|
2024-02-24 17:51:34 -05:00
|
|
|
return promptInternal(collectionList, prompt, promptTemplate, n_predict, top_k, top_p, min_p, temp, n_batch,
|
2023-07-01 11:34:21 -04:00
|
|
|
repeat_penalty, repeat_penalty_tokens);
|
|
|
|
}
|
2023-05-01 09:10:05 -04:00
|
|
|
|
2023-07-01 11:34:21 -04:00
|
|
|
bool ChatLLM::promptInternal(const QList<QString> &collectionList, const QString &prompt, const QString &promptTemplate,
|
2024-07-25 10:04:47 -04:00
|
|
|
int32_t n_predict, int32_t top_k, float top_p, float min_p, float temp, int32_t n_batch, float repeat_penalty,
|
2024-07-27 11:43:32 -04:00
|
|
|
int32_t repeat_penalty_tokens, bool isToolCallResponse)
|
2023-05-01 09:10:05 -04:00
|
|
|
{
|
|
|
|
if (!isModelLoaded())
|
|
|
|
return false;
|
|
|
|
|
2024-07-25 10:04:47 -04:00
|
|
|
QList<SourceExcerpt> databaseResults;
|
2023-06-28 20:42:40 -04:00
|
|
|
const int retrievalSize = MySettings::globalInstance()->localDocsRetrievalSize();
|
2024-07-27 11:43:32 -04:00
|
|
|
if (!collectionList.isEmpty() && !isToolCallResponse) {
|
2023-12-04 12:58:40 -05:00
|
|
|
emit requestRetrieveFromDB(collectionList, prompt, retrievalSize, &databaseResults); // blocks
|
2024-07-25 10:04:47 -04:00
|
|
|
emit sourceExcerptsChanged(databaseResults);
|
2023-12-04 12:58:40 -05:00
|
|
|
}
|
2023-06-01 14:13:12 -04:00
|
|
|
|
|
|
|
// Augment the prompt template with the results if any
|
2024-06-24 18:49:23 -04:00
|
|
|
QString docsContext;
|
|
|
|
if (!databaseResults.isEmpty()) {
|
|
|
|
QStringList results;
|
2024-07-25 10:04:47 -04:00
|
|
|
for (const SourceExcerpt &info : databaseResults)
|
2024-07-10 15:45:20 -04:00
|
|
|
results << u"Collection: %1\nPath: %2\nExcerpt: %3"_s.arg(info.collection, info.path, info.text);
|
2024-06-24 18:49:23 -04:00
|
|
|
|
|
|
|
// FIXME(jared): use a Jinja prompt template instead of hardcoded Alpaca-style localdocs template
|
|
|
|
docsContext = u"### Context:\n%1\n\n"_s.arg(results.join("\n\n"));
|
|
|
|
}
|
2023-05-01 09:10:05 -04:00
|
|
|
|
2023-07-01 11:34:21 -04:00
|
|
|
int n_threads = MySettings::globalInstance()->threadCount();
|
|
|
|
|
2023-05-01 09:10:05 -04:00
|
|
|
m_stopGenerating = false;
|
|
|
|
auto promptFunc = std::bind(&ChatLLM::handlePrompt, this, std::placeholders::_1);
|
|
|
|
auto responseFunc = std::bind(&ChatLLM::handleResponse, this, std::placeholders::_1,
|
|
|
|
std::placeholders::_2);
|
2023-05-20 20:04:36 -04:00
|
|
|
emit promptProcessing();
|
2023-05-01 09:10:05 -04:00
|
|
|
m_ctx.n_predict = n_predict;
|
|
|
|
m_ctx.top_k = top_k;
|
|
|
|
m_ctx.top_p = top_p;
|
2024-02-24 17:51:34 -05:00
|
|
|
m_ctx.min_p = min_p;
|
2023-05-01 09:10:05 -04:00
|
|
|
m_ctx.temp = temp;
|
|
|
|
m_ctx.n_batch = n_batch;
|
|
|
|
m_ctx.repeat_penalty = repeat_penalty;
|
|
|
|
m_ctx.repeat_last_n = repeat_penalty_tokens;
|
2023-06-22 15:44:49 -04:00
|
|
|
m_llModelInfo.model->setThreadCount(n_threads);
|
2023-05-20 20:03:59 -04:00
|
|
|
#if defined(DEBUG)
|
2024-02-21 15:45:32 -05:00
|
|
|
printf("%s", qPrintable(prompt));
|
2023-05-01 09:10:05 -04:00
|
|
|
fflush(stdout);
|
2023-05-20 20:03:59 -04:00
|
|
|
#endif
|
2024-04-25 13:16:52 -04:00
|
|
|
QElapsedTimer totalTime;
|
|
|
|
totalTime.start();
|
2023-06-19 14:34:53 -04:00
|
|
|
m_timer->start();
|
2024-02-21 15:45:32 -05:00
|
|
|
if (!docsContext.isEmpty()) {
|
|
|
|
auto old_n_predict = std::exchange(m_ctx.n_predict, 0); // decode localdocs context without a response
|
2024-08-07 11:25:24 -04:00
|
|
|
m_llModelInfo.model->prompt(docsContext.toStdString(), "%1", promptFunc, responseFunc,
|
|
|
|
/*allowContextShift*/ true, m_ctx);
|
2024-02-21 15:45:32 -05:00
|
|
|
m_ctx.n_predict = old_n_predict; // now we are ready for a response
|
|
|
|
}
|
2024-08-07 11:25:24 -04:00
|
|
|
m_llModelInfo.model->prompt(prompt.toStdString(), promptTemplate.toStdString(), promptFunc, responseFunc,
|
|
|
|
/*allowContextShift*/ true, m_ctx);
|
2023-05-20 20:03:59 -04:00
|
|
|
#if defined(DEBUG)
|
2023-05-01 09:10:05 -04:00
|
|
|
printf("\n");
|
|
|
|
fflush(stdout);
|
2023-05-20 20:03:59 -04:00
|
|
|
#endif
|
2023-06-19 14:34:53 -04:00
|
|
|
m_timer->stop();
|
2024-04-25 13:16:52 -04:00
|
|
|
qint64 elapsed = totalTime.elapsed();
|
2023-05-01 09:10:05 -04:00
|
|
|
std::string trimmed = trim_whitespace(m_response);
|
2024-07-25 10:04:47 -04:00
|
|
|
if (m_maybeToolCall) {
|
|
|
|
m_maybeToolCall = false;
|
|
|
|
m_ctx.n_past = std::max(0, m_ctx.n_past);
|
|
|
|
m_ctx.tokens.erase(m_ctx.tokens.end() - m_promptResponseTokens, m_ctx.tokens.end());
|
|
|
|
m_promptResponseTokens = 0;
|
|
|
|
m_promptTokens = 0;
|
|
|
|
m_response = std::string();
|
|
|
|
return toolCallInternal(QString::fromStdString(trimmed), n_predict, top_k, top_p, min_p, temp,
|
|
|
|
n_batch, repeat_penalty, repeat_penalty_tokens);
|
|
|
|
} else {
|
|
|
|
if (trimmed != m_response) {
|
|
|
|
m_response = trimmed;
|
|
|
|
emit responseChanged(QString::fromStdString(m_response));
|
|
|
|
}
|
2024-07-10 15:45:20 -04:00
|
|
|
|
2024-07-25 10:04:47 -04:00
|
|
|
SuggestionMode mode = MySettings::globalInstance()->suggestionMode();
|
2024-07-27 11:43:32 -04:00
|
|
|
if (mode == SuggestionMode::On || (mode == SuggestionMode::SourceExcerptsOnly && (!databaseResults.isEmpty() || isToolCallResponse)))
|
2024-07-25 10:04:47 -04:00
|
|
|
generateQuestions(elapsed);
|
|
|
|
else
|
|
|
|
emit responseStopped(elapsed);
|
|
|
|
}
|
2024-07-10 15:45:20 -04:00
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
m_pristineLoadedState = false;
|
2023-05-01 09:10:05 -04:00
|
|
|
return true;
|
|
|
|
}
|
2023-05-01 20:27:07 -04:00
|
|
|
|
2024-07-25 10:04:47 -04:00
|
|
|
bool ChatLLM::toolCallInternal(const QString &toolCall, int32_t n_predict, int32_t top_k, float top_p,
|
|
|
|
float min_p, float temp, int32_t n_batch, float repeat_penalty, int32_t repeat_penalty_tokens)
|
|
|
|
{
|
|
|
|
Q_ASSERT(m_modelInfo.filename().startsWith("Meta-Llama-3.1-8B-Instruct"));
|
|
|
|
emit toolCalled(tr("searching web..."));
|
|
|
|
|
|
|
|
// Based on https://llama.meta.com/docs/model-cards-and-prompt-formats/llama3_1/#built-in-python-based-tool-calling
|
|
|
|
// For brave_search and wolfram_alpha ipython is always used
|
|
|
|
|
|
|
|
static QRegularExpression re(R"(brave_search\.call\(query=\"([^\"]+)\"\))");
|
|
|
|
QRegularExpressionMatch match = re.match(toolCall);
|
|
|
|
|
2024-07-27 11:11:41 -04:00
|
|
|
QString promptTemplate("<|start_header_id|>ipython<|end_header_id|>\n\n%1<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n%2");
|
2024-07-25 10:04:47 -04:00
|
|
|
QString query;
|
|
|
|
if (match.hasMatch()) {
|
|
|
|
query = match.captured(1);
|
|
|
|
} else {
|
|
|
|
qWarning() << "WARNING: Could not find the tool for " << toolCall;
|
2024-07-27 11:11:41 -04:00
|
|
|
return promptInternal(QList<QString>()/*collectionList*/, QString() /*prompt*/, promptTemplate,
|
2024-07-27 11:43:32 -04:00
|
|
|
n_predict, top_k, top_p, min_p, temp, n_batch, repeat_penalty, repeat_penalty_tokens, true /*isToolCallResponse*/);
|
2024-07-25 10:04:47 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const QString apiKey = MySettings::globalInstance()->braveSearchAPIKey();
|
|
|
|
Q_ASSERT(apiKey != "");
|
|
|
|
|
|
|
|
BraveSearch brave;
|
|
|
|
const QPair<QString, QList<SourceExcerpt>> braveResponse = brave.search(apiKey, query, 2 /*topK*/, 2000 /*msecs to timeout*/);
|
|
|
|
|
|
|
|
emit sourceExcerptsChanged(braveResponse.second);
|
|
|
|
|
2024-07-27 11:11:41 -04:00
|
|
|
return promptInternal(QList<QString>()/*collectionList*/, braveResponse.first, promptTemplate,
|
2024-07-27 11:43:32 -04:00
|
|
|
n_predict, top_k, top_p, min_p, temp, n_batch, repeat_penalty, repeat_penalty_tokens, true /*isToolCallResponse*/);
|
2024-07-25 10:04:47 -04:00
|
|
|
}
|
|
|
|
|
2023-05-13 19:05:35 -04:00
|
|
|
void ChatLLM::setShouldBeLoaded(bool b)
|
2023-05-01 20:27:07 -04:00
|
|
|
{
|
2023-05-13 19:05:35 -04:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "setShouldBeLoaded" << m_llmThread.objectName() << b << m_llModelInfo.model.get();
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2023-05-13 19:05:35 -04:00
|
|
|
m_shouldBeLoaded = b; // atomic
|
|
|
|
emit shouldBeLoadedChanged();
|
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
void ChatLLM::requestTrySwitchContext()
|
2024-02-07 09:37:59 -05:00
|
|
|
{
|
2024-05-15 14:07:03 -04:00
|
|
|
m_shouldBeLoaded = true; // atomic
|
|
|
|
emit trySwitchContextRequested(modelInfo());
|
2024-02-07 09:37:59 -05:00
|
|
|
}
|
|
|
|
|
2023-05-13 19:05:35 -04:00
|
|
|
void ChatLLM::handleShouldBeLoadedChanged()
|
|
|
|
{
|
|
|
|
if (m_shouldBeLoaded)
|
|
|
|
reloadModel();
|
|
|
|
else
|
|
|
|
unloadModel();
|
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::unloadModel()
|
|
|
|
{
|
2023-05-15 18:48:24 -04:00
|
|
|
if (!isModelLoaded() || m_isServer)
|
2023-05-13 19:05:35 -04:00
|
|
|
return;
|
|
|
|
|
2024-02-21 16:05:49 -05:00
|
|
|
if (!m_forceUnloadModel || !m_shouldBeLoaded)
|
|
|
|
emit modelLoadingPercentageChanged(0.0f);
|
|
|
|
else
|
|
|
|
emit modelLoadingPercentageChanged(std::numeric_limits<float>::min()); // small non-zero positive value
|
|
|
|
|
2024-03-06 12:59:34 -05:00
|
|
|
if (!m_markedForDeletion)
|
|
|
|
saveState();
|
|
|
|
|
2023-05-13 19:05:35 -04:00
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "unloadModel" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-13 19:05:35 -04:00
|
|
|
#endif
|
2024-02-07 09:37:59 -05:00
|
|
|
|
|
|
|
if (m_forceUnloadModel) {
|
2024-06-26 15:26:27 -04:00
|
|
|
m_llModelInfo.resetModel(this);
|
2024-02-07 09:37:59 -05:00
|
|
|
m_forceUnloadModel = false;
|
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
LLModelStore::globalInstance()->releaseModel(std::move(m_llModelInfo));
|
|
|
|
m_pristineLoadedState = false;
|
2023-05-01 20:27:07 -04:00
|
|
|
}
|
|
|
|
|
2023-05-13 19:05:35 -04:00
|
|
|
void ChatLLM::reloadModel()
|
2023-05-01 20:27:07 -04:00
|
|
|
{
|
2024-02-07 09:37:59 -05:00
|
|
|
if (isModelLoaded() && m_forceUnloadModel)
|
|
|
|
unloadModel(); // we unload first if we are forcing an unload
|
|
|
|
|
2023-05-15 18:48:24 -04:00
|
|
|
if (isModelLoaded() || m_isServer)
|
2023-05-13 19:05:35 -04:00
|
|
|
return;
|
|
|
|
|
|
|
|
#if defined(DEBUG_MODEL_LOADING)
|
2024-05-15 14:07:03 -04:00
|
|
|
qDebug() << "reloadModel" << m_llmThread.objectName() << m_llModelInfo.model.get();
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2023-06-22 15:44:49 -04:00
|
|
|
const ModelInfo m = modelInfo();
|
2023-07-01 11:34:21 -04:00
|
|
|
if (m.name().isEmpty())
|
2023-05-04 15:31:41 -04:00
|
|
|
loadDefaultModel();
|
2023-06-20 16:14:30 -04:00
|
|
|
else
|
|
|
|
loadModel(m);
|
2023-05-01 20:27:07 -04:00
|
|
|
}
|
2023-05-02 11:19:17 -04:00
|
|
|
|
|
|
|
void ChatLLM::generateName()
|
|
|
|
{
|
|
|
|
Q_ASSERT(isModelLoaded());
|
|
|
|
if (!isModelLoaded())
|
|
|
|
return;
|
|
|
|
|
2024-07-10 15:45:20 -04:00
|
|
|
const QString chatNamePrompt = MySettings::globalInstance()->modelChatNamePrompt(m_modelInfo);
|
|
|
|
if (chatNamePrompt.trimmed().isEmpty()) {
|
|
|
|
qWarning() << "ChatLLM: not generating chat name because prompt is empty";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-05-09 09:38:19 -04:00
|
|
|
auto promptTemplate = MySettings::globalInstance()->modelPromptTemplate(m_modelInfo);
|
2023-05-02 11:19:17 -04:00
|
|
|
auto promptFunc = std::bind(&ChatLLM::handleNamePrompt, this, std::placeholders::_1);
|
2024-04-15 11:39:48 -04:00
|
|
|
auto responseFunc = std::bind(&ChatLLM::handleNameResponse, this, std::placeholders::_1, std::placeholders::_2);
|
2023-05-02 11:19:17 -04:00
|
|
|
LLModel::PromptContext ctx = m_ctx;
|
2024-07-10 15:45:20 -04:00
|
|
|
m_llModelInfo.model->prompt(chatNamePrompt.toStdString(), promptTemplate.toStdString(),
|
2024-08-07 11:25:24 -04:00
|
|
|
promptFunc, responseFunc, /*allowContextShift*/ false, ctx);
|
2023-05-02 11:19:17 -04:00
|
|
|
std::string trimmed = trim_whitespace(m_nameResponse);
|
|
|
|
if (trimmed != m_nameResponse) {
|
|
|
|
m_nameResponse = trimmed;
|
2023-06-20 16:14:30 -04:00
|
|
|
emit generatedNameChanged(QString::fromStdString(m_nameResponse));
|
2023-05-02 11:19:17 -04:00
|
|
|
}
|
2024-05-15 14:07:03 -04:00
|
|
|
m_pristineLoadedState = false;
|
2023-05-02 11:19:17 -04:00
|
|
|
}
|
|
|
|
|
2023-06-19 19:51:28 -04:00
|
|
|
void ChatLLM::handleChatIdChanged(const QString &id)
|
2023-05-04 15:31:41 -04:00
|
|
|
{
|
2023-06-19 19:51:28 -04:00
|
|
|
m_llmThread.setObjectName(id);
|
|
|
|
}
|
|
|
|
|
2023-05-02 11:19:17 -04:00
|
|
|
bool ChatLLM::handleNamePrompt(int32_t token)
|
|
|
|
{
|
2023-07-11 12:37:21 -04:00
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "name prompt" << m_llmThread.objectName() << token;
|
|
|
|
#endif
|
2023-05-02 11:19:17 -04:00
|
|
|
Q_UNUSED(token);
|
2023-07-09 14:42:11 -04:00
|
|
|
return !m_stopGenerating;
|
2023-05-02 11:19:17 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
bool ChatLLM::handleNameResponse(int32_t token, const std::string &response)
|
|
|
|
{
|
2023-07-11 12:37:21 -04:00
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "name response" << m_llmThread.objectName() << token << response;
|
|
|
|
#endif
|
2023-05-02 11:19:17 -04:00
|
|
|
Q_UNUSED(token);
|
2023-05-08 12:02:31 -04:00
|
|
|
|
2023-05-02 11:19:17 -04:00
|
|
|
m_nameResponse.append(response);
|
2023-06-20 16:14:30 -04:00
|
|
|
emit generatedNameChanged(QString::fromStdString(m_nameResponse));
|
2023-05-08 12:02:31 -04:00
|
|
|
QString gen = QString::fromStdString(m_nameResponse).simplified();
|
|
|
|
QStringList words = gen.split(' ', Qt::SkipEmptyParts);
|
|
|
|
return words.size() <= 3;
|
2023-05-02 11:19:17 -04:00
|
|
|
}
|
|
|
|
|
2024-07-10 15:45:20 -04:00
|
|
|
bool ChatLLM::handleQuestionPrompt(int32_t token)
|
|
|
|
{
|
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "question prompt" << m_llmThread.objectName() << token;
|
|
|
|
#endif
|
|
|
|
Q_UNUSED(token);
|
|
|
|
return !m_stopGenerating;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool ChatLLM::handleQuestionResponse(int32_t token, const std::string &response)
|
|
|
|
{
|
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "question response" << m_llmThread.objectName() << token << response;
|
|
|
|
#endif
|
|
|
|
Q_UNUSED(token);
|
|
|
|
|
|
|
|
// add token to buffer
|
|
|
|
m_questionResponse.append(response);
|
|
|
|
|
|
|
|
// match whole question sentences
|
2024-07-23 17:01:46 -04:00
|
|
|
// FIXME: This only works with response by the model in english which is not ideal for a multi-language
|
|
|
|
// model.
|
2024-07-10 15:45:20 -04:00
|
|
|
static const QRegularExpression reQuestion(R"(\b(What|Where|How|Why|When|Who|Which|Whose|Whom)\b[^?]*\?)");
|
|
|
|
|
|
|
|
// extract all questions from response
|
|
|
|
int lastMatchEnd = -1;
|
|
|
|
for (const auto &match : reQuestion.globalMatch(m_questionResponse)) {
|
|
|
|
lastMatchEnd = match.capturedEnd();
|
|
|
|
emit generatedQuestionFinished(match.captured());
|
|
|
|
}
|
|
|
|
|
|
|
|
// remove processed input from buffer
|
|
|
|
if (lastMatchEnd != -1)
|
|
|
|
m_questionResponse.erase(m_questionResponse.cbegin(), m_questionResponse.cbegin() + lastMatchEnd);
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::generateQuestions(qint64 elapsed)
|
|
|
|
{
|
|
|
|
Q_ASSERT(isModelLoaded());
|
|
|
|
if (!isModelLoaded()) {
|
|
|
|
emit responseStopped(elapsed);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const std::string suggestedFollowUpPrompt = MySettings::globalInstance()->modelSuggestedFollowUpPrompt(m_modelInfo).toStdString();
|
|
|
|
if (QString::fromStdString(suggestedFollowUpPrompt).trimmed().isEmpty()) {
|
|
|
|
emit responseStopped(elapsed);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
emit generatingQuestions();
|
|
|
|
m_questionResponse.clear();
|
|
|
|
auto promptTemplate = MySettings::globalInstance()->modelPromptTemplate(m_modelInfo);
|
|
|
|
auto promptFunc = std::bind(&ChatLLM::handleQuestionPrompt, this, std::placeholders::_1);
|
|
|
|
auto responseFunc = std::bind(&ChatLLM::handleQuestionResponse, this, std::placeholders::_1, std::placeholders::_2);
|
|
|
|
LLModel::PromptContext ctx = m_ctx;
|
|
|
|
QElapsedTimer totalTime;
|
|
|
|
totalTime.start();
|
2024-08-07 11:25:24 -04:00
|
|
|
m_llModelInfo.model->prompt(suggestedFollowUpPrompt, promptTemplate.toStdString(), promptFunc, responseFunc,
|
|
|
|
/*allowContextShift*/ false, ctx);
|
2024-07-10 15:45:20 -04:00
|
|
|
elapsed += totalTime.elapsed();
|
|
|
|
emit responseStopped(elapsed);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-07-01 11:34:21 -04:00
|
|
|
bool ChatLLM::handleSystemPrompt(int32_t token)
|
|
|
|
{
|
2023-07-11 12:37:21 -04:00
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "system prompt" << m_llmThread.objectName() << token << m_stopGenerating;
|
|
|
|
#endif
|
2023-07-01 11:34:21 -04:00
|
|
|
Q_UNUSED(token);
|
2023-07-09 14:42:11 -04:00
|
|
|
return !m_stopGenerating;
|
2023-07-01 11:34:21 -04:00
|
|
|
}
|
|
|
|
|
2023-10-10 16:43:02 -04:00
|
|
|
bool ChatLLM::handleRestoreStateFromTextPrompt(int32_t token)
|
|
|
|
{
|
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "restore state from text prompt" << m_llmThread.objectName() << token << m_stopGenerating;
|
|
|
|
#endif
|
|
|
|
Q_UNUSED(token);
|
|
|
|
return !m_stopGenerating;
|
|
|
|
}
|
|
|
|
|
2023-12-16 17:58:15 -05:00
|
|
|
// this function serialized the cached model state to disk.
|
|
|
|
// we want to also serialize n_ctx, and read it at load time.
|
2023-10-10 16:43:02 -04:00
|
|
|
bool ChatLLM::serialize(QDataStream &stream, int version, bool serializeKV)
|
2023-05-04 15:31:41 -04:00
|
|
|
{
|
2023-05-08 17:23:02 -04:00
|
|
|
if (version > 1) {
|
2023-06-22 15:44:49 -04:00
|
|
|
stream << m_llModelType;
|
|
|
|
switch (m_llModelType) {
|
2024-07-18 21:03:18 -04:00
|
|
|
case GPTJ_: stream << GPTJ_INTERNAL_STATE_VERSION; break;
|
2023-05-08 17:23:02 -04:00
|
|
|
case LLAMA_: stream << LLAMA_INTERNAL_STATE_VERSION; break;
|
|
|
|
default: Q_UNREACHABLE();
|
|
|
|
}
|
|
|
|
}
|
2023-05-04 15:31:41 -04:00
|
|
|
stream << response();
|
|
|
|
stream << generatedName();
|
|
|
|
stream << m_promptResponseTokens;
|
2023-10-10 16:43:02 -04:00
|
|
|
|
|
|
|
if (!serializeKV) {
|
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "serialize" << m_llmThread.objectName() << m_state.size();
|
|
|
|
#endif
|
|
|
|
return stream.status() == QDataStream::Ok;
|
|
|
|
}
|
|
|
|
|
2023-06-19 18:23:05 -04:00
|
|
|
if (version <= 3) {
|
2023-10-11 11:31:34 -04:00
|
|
|
int responseLogits = 0;
|
2023-06-19 18:23:05 -04:00
|
|
|
stream << responseLogits;
|
|
|
|
}
|
2023-05-04 15:31:41 -04:00
|
|
|
stream << m_ctx.n_past;
|
2024-01-22 10:01:31 -05:00
|
|
|
if (version >= 7) {
|
2023-12-16 17:58:15 -05:00
|
|
|
stream << m_ctx.n_ctx;
|
|
|
|
}
|
2023-05-04 15:31:41 -04:00
|
|
|
stream << quint64(m_ctx.tokens.size());
|
|
|
|
stream.writeRawData(reinterpret_cast<const char*>(m_ctx.tokens.data()), m_ctx.tokens.size() * sizeof(int));
|
|
|
|
saveState();
|
2023-05-05 20:11:24 -04:00
|
|
|
QByteArray compressed = qCompress(m_state);
|
|
|
|
stream << compressed;
|
2023-05-07 11:24:07 -04:00
|
|
|
#if defined(DEBUG)
|
2023-06-19 19:51:28 -04:00
|
|
|
qDebug() << "serialize" << m_llmThread.objectName() << m_state.size();
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2023-05-04 15:31:41 -04:00
|
|
|
return stream.status() == QDataStream::Ok;
|
|
|
|
}
|
|
|
|
|
2023-10-10 16:43:02 -04:00
|
|
|
bool ChatLLM::deserialize(QDataStream &stream, int version, bool deserializeKV, bool discardKV)
|
2023-05-04 15:31:41 -04:00
|
|
|
{
|
2023-05-08 17:23:02 -04:00
|
|
|
if (version > 1) {
|
|
|
|
int internalStateVersion;
|
2023-06-22 15:44:49 -04:00
|
|
|
stream >> m_llModelType;
|
2023-05-08 17:23:02 -04:00
|
|
|
stream >> internalStateVersion; // for future use
|
|
|
|
}
|
2023-05-04 15:31:41 -04:00
|
|
|
QString response;
|
|
|
|
stream >> response;
|
|
|
|
m_response = response.toStdString();
|
|
|
|
QString nameResponse;
|
|
|
|
stream >> nameResponse;
|
|
|
|
m_nameResponse = nameResponse.toStdString();
|
|
|
|
stream >> m_promptResponseTokens;
|
2023-10-10 16:43:02 -04:00
|
|
|
|
|
|
|
// If we do not deserialize the KV or it is discarded, then we need to restore the state from the
|
|
|
|
// text only. This will be a costly operation, but the chat has to be restored from the text archive
|
|
|
|
// alone.
|
2024-05-15 14:07:03 -04:00
|
|
|
if (!deserializeKV || discardKV) {
|
|
|
|
m_restoreStateFromText = true;
|
|
|
|
m_pristineLoadedState = true;
|
|
|
|
}
|
2023-10-10 16:43:02 -04:00
|
|
|
|
|
|
|
if (!deserializeKV) {
|
|
|
|
#if defined(DEBUG)
|
|
|
|
qDebug() << "deserialize" << m_llmThread.objectName();
|
|
|
|
#endif
|
|
|
|
return stream.status() == QDataStream::Ok;
|
|
|
|
}
|
|
|
|
|
2023-06-19 18:23:05 -04:00
|
|
|
if (version <= 3) {
|
|
|
|
int responseLogits;
|
|
|
|
stream >> responseLogits;
|
|
|
|
}
|
2023-10-10 16:43:02 -04:00
|
|
|
|
|
|
|
int32_t n_past;
|
|
|
|
stream >> n_past;
|
|
|
|
if (!discardKV) m_ctx.n_past = n_past;
|
|
|
|
|
2024-01-22 10:01:31 -05:00
|
|
|
if (version >= 7) {
|
2023-12-16 17:58:15 -05:00
|
|
|
uint32_t n_ctx;
|
|
|
|
stream >> n_ctx;
|
|
|
|
if (!discardKV) m_ctx.n_ctx = n_ctx;
|
|
|
|
}
|
|
|
|
|
2024-07-17 16:07:37 -04:00
|
|
|
if (version < 9) {
|
|
|
|
quint64 logitsSize;
|
|
|
|
stream >> logitsSize;
|
2023-10-10 16:43:02 -04:00
|
|
|
stream.skipRawData(logitsSize * sizeof(float));
|
|
|
|
}
|
|
|
|
|
2023-05-04 15:31:41 -04:00
|
|
|
quint64 tokensSize;
|
|
|
|
stream >> tokensSize;
|
2023-10-10 16:43:02 -04:00
|
|
|
if (!discardKV) {
|
|
|
|
m_ctx.tokens.resize(tokensSize);
|
|
|
|
stream.readRawData(reinterpret_cast<char*>(m_ctx.tokens.data()), tokensSize * sizeof(int));
|
|
|
|
} else {
|
|
|
|
stream.skipRawData(tokensSize * sizeof(int));
|
|
|
|
}
|
|
|
|
|
2023-05-08 05:52:57 -04:00
|
|
|
if (version > 0) {
|
|
|
|
QByteArray compressed;
|
|
|
|
stream >> compressed;
|
2023-10-10 16:43:02 -04:00
|
|
|
if (!discardKV)
|
|
|
|
m_state = qUncompress(compressed);
|
2023-05-08 05:52:57 -04:00
|
|
|
} else {
|
2023-12-12 11:45:03 -05:00
|
|
|
if (!discardKV) {
|
2023-10-10 16:43:02 -04:00
|
|
|
stream >> m_state;
|
2023-12-12 11:45:03 -05:00
|
|
|
} else {
|
2023-10-10 16:43:02 -04:00
|
|
|
QByteArray state;
|
2023-12-12 11:45:03 -05:00
|
|
|
stream >> state;
|
2023-10-10 16:43:02 -04:00
|
|
|
}
|
2023-05-08 05:52:57 -04:00
|
|
|
}
|
2023-10-10 16:43:02 -04:00
|
|
|
|
2023-05-07 11:24:07 -04:00
|
|
|
#if defined(DEBUG)
|
2023-06-19 19:51:28 -04:00
|
|
|
qDebug() << "deserialize" << m_llmThread.objectName();
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2023-05-04 15:31:41 -04:00
|
|
|
return stream.status() == QDataStream::Ok;
|
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::saveState()
|
|
|
|
{
|
2024-05-15 14:07:03 -04:00
|
|
|
if (!isModelLoaded() || m_pristineLoadedState)
|
2023-05-04 15:31:41 -04:00
|
|
|
return;
|
|
|
|
|
2024-03-13 18:23:57 -04:00
|
|
|
if (m_llModelType == LLModelType::API_) {
|
2023-05-15 18:36:41 -04:00
|
|
|
m_state.clear();
|
|
|
|
QDataStream stream(&m_state, QIODeviceBase::WriteOnly);
|
2024-02-05 04:37:59 -05:00
|
|
|
stream.setVersion(QDataStream::Qt_6_4);
|
2024-05-15 14:07:03 -04:00
|
|
|
ChatAPI *chatAPI = static_cast<ChatAPI*>(m_llModelInfo.model.get());
|
2024-03-13 18:23:57 -04:00
|
|
|
stream << chatAPI->context();
|
2023-05-15 18:36:41 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-06-22 15:44:49 -04:00
|
|
|
const size_t stateSize = m_llModelInfo.model->stateSize();
|
2023-05-04 15:31:41 -04:00
|
|
|
m_state.resize(stateSize);
|
2023-05-07 11:24:07 -04:00
|
|
|
#if defined(DEBUG)
|
2023-06-19 19:51:28 -04:00
|
|
|
qDebug() << "saveState" << m_llmThread.objectName() << "size:" << m_state.size();
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2023-06-22 15:44:49 -04:00
|
|
|
m_llModelInfo.model->saveState(static_cast<uint8_t*>(reinterpret_cast<void*>(m_state.data())));
|
2023-05-04 15:31:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::restoreState()
|
|
|
|
{
|
2023-10-10 16:43:02 -04:00
|
|
|
if (!isModelLoaded())
|
2023-05-04 15:31:41 -04:00
|
|
|
return;
|
|
|
|
|
2024-03-13 18:23:57 -04:00
|
|
|
if (m_llModelType == LLModelType::API_) {
|
2023-05-15 18:36:41 -04:00
|
|
|
QDataStream stream(&m_state, QIODeviceBase::ReadOnly);
|
2024-02-05 04:37:59 -05:00
|
|
|
stream.setVersion(QDataStream::Qt_6_4);
|
2024-05-15 14:07:03 -04:00
|
|
|
ChatAPI *chatAPI = static_cast<ChatAPI*>(m_llModelInfo.model.get());
|
2023-05-15 18:36:41 -04:00
|
|
|
QList<QString> context;
|
|
|
|
stream >> context;
|
2024-03-13 18:23:57 -04:00
|
|
|
chatAPI->setContext(context);
|
2023-05-15 18:36:41 -04:00
|
|
|
m_state.clear();
|
2023-12-12 11:45:03 -05:00
|
|
|
m_state.squeeze();
|
2023-05-15 18:36:41 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-05-07 11:24:07 -04:00
|
|
|
#if defined(DEBUG)
|
2023-06-19 19:51:28 -04:00
|
|
|
qDebug() << "restoreState" << m_llmThread.objectName() << "size:" << m_state.size();
|
2023-05-07 11:24:07 -04:00
|
|
|
#endif
|
2023-10-10 16:43:02 -04:00
|
|
|
|
|
|
|
if (m_state.isEmpty())
|
|
|
|
return;
|
|
|
|
|
2023-12-12 11:45:03 -05:00
|
|
|
if (m_llModelInfo.model->stateSize() == m_state.size()) {
|
|
|
|
m_llModelInfo.model->restoreState(static_cast<const uint8_t*>(reinterpret_cast<void*>(m_state.data())));
|
|
|
|
m_processedSystemPrompt = true;
|
2024-05-15 14:07:03 -04:00
|
|
|
m_pristineLoadedState = true;
|
2023-12-12 11:45:03 -05:00
|
|
|
} else {
|
2024-03-06 17:14:54 -05:00
|
|
|
qWarning() << "restoring state from text because" << m_llModelInfo.model->stateSize() << "!=" << m_state.size();
|
2023-12-12 11:45:03 -05:00
|
|
|
m_restoreStateFromText = true;
|
|
|
|
}
|
|
|
|
|
2024-05-15 14:07:03 -04:00
|
|
|
// free local state copy unless unload is pending
|
|
|
|
if (m_shouldBeLoaded) {
|
|
|
|
m_state.clear();
|
|
|
|
m_state.squeeze();
|
|
|
|
m_pristineLoadedState = false;
|
|
|
|
}
|
2023-05-04 15:31:41 -04:00
|
|
|
}
|
2023-07-01 11:34:21 -04:00
|
|
|
|
|
|
|
void ChatLLM::processSystemPrompt()
|
|
|
|
{
|
|
|
|
Q_ASSERT(isModelLoaded());
|
2023-11-21 10:42:12 -05:00
|
|
|
if (!isModelLoaded() || m_processedSystemPrompt || m_restoreStateFromText || m_isServer)
|
2023-07-01 11:34:21 -04:00
|
|
|
return;
|
|
|
|
|
2023-07-12 14:27:48 -04:00
|
|
|
const std::string systemPrompt = MySettings::globalInstance()->modelSystemPrompt(m_modelInfo).toStdString();
|
2023-07-12 14:30:11 -04:00
|
|
|
if (QString::fromStdString(systemPrompt).trimmed().isEmpty()) {
|
2023-07-12 14:27:48 -04:00
|
|
|
m_processedSystemPrompt = true;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-10-10 16:43:02 -04:00
|
|
|
// Start with a whole new context
|
2023-07-09 14:42:11 -04:00
|
|
|
m_stopGenerating = false;
|
2023-10-10 16:43:02 -04:00
|
|
|
m_ctx = LLModel::PromptContext();
|
|
|
|
|
2023-07-01 11:34:21 -04:00
|
|
|
auto promptFunc = std::bind(&ChatLLM::handleSystemPrompt, this, std::placeholders::_1);
|
|
|
|
|
|
|
|
const int32_t n_predict = MySettings::globalInstance()->modelMaxLength(m_modelInfo);
|
|
|
|
const int32_t top_k = MySettings::globalInstance()->modelTopK(m_modelInfo);
|
|
|
|
const float top_p = MySettings::globalInstance()->modelTopP(m_modelInfo);
|
2024-02-24 17:51:34 -05:00
|
|
|
const float min_p = MySettings::globalInstance()->modelMinP(m_modelInfo);
|
2023-07-01 11:34:21 -04:00
|
|
|
const float temp = MySettings::globalInstance()->modelTemperature(m_modelInfo);
|
|
|
|
const int32_t n_batch = MySettings::globalInstance()->modelPromptBatchSize(m_modelInfo);
|
|
|
|
const float repeat_penalty = MySettings::globalInstance()->modelRepeatPenalty(m_modelInfo);
|
|
|
|
const int32_t repeat_penalty_tokens = MySettings::globalInstance()->modelRepeatPenaltyTokens(m_modelInfo);
|
|
|
|
int n_threads = MySettings::globalInstance()->threadCount();
|
|
|
|
m_ctx.n_predict = n_predict;
|
|
|
|
m_ctx.top_k = top_k;
|
|
|
|
m_ctx.top_p = top_p;
|
2024-02-24 17:51:34 -05:00
|
|
|
m_ctx.min_p = min_p;
|
2023-07-01 11:34:21 -04:00
|
|
|
m_ctx.temp = temp;
|
|
|
|
m_ctx.n_batch = n_batch;
|
|
|
|
m_ctx.repeat_penalty = repeat_penalty;
|
|
|
|
m_ctx.repeat_last_n = repeat_penalty_tokens;
|
|
|
|
m_llModelInfo.model->setThreadCount(n_threads);
|
|
|
|
#if defined(DEBUG)
|
|
|
|
printf("%s", qPrintable(QString::fromStdString(systemPrompt)));
|
|
|
|
fflush(stdout);
|
|
|
|
#endif
|
2024-02-21 15:45:32 -05:00
|
|
|
auto old_n_predict = std::exchange(m_ctx.n_predict, 0); // decode system prompt without a response
|
2024-04-15 11:39:48 -04:00
|
|
|
// use "%1%2" and not "%1" to avoid implicit whitespace
|
2024-08-07 11:25:24 -04:00
|
|
|
m_llModelInfo.model->prompt(systemPrompt, "%1%2", promptFunc, nullptr, /*allowContextShift*/ true, m_ctx, true);
|
2024-02-21 15:45:32 -05:00
|
|
|
m_ctx.n_predict = old_n_predict;
|
2023-07-01 11:34:21 -04:00
|
|
|
#if defined(DEBUG)
|
|
|
|
printf("\n");
|
|
|
|
fflush(stdout);
|
|
|
|
#endif
|
2023-10-10 16:43:02 -04:00
|
|
|
|
2023-11-21 10:42:12 -05:00
|
|
|
m_processedSystemPrompt = m_stopGenerating == false;
|
2024-05-15 14:07:03 -04:00
|
|
|
m_pristineLoadedState = false;
|
2023-10-10 16:43:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
void ChatLLM::processRestoreStateFromText()
|
|
|
|
{
|
|
|
|
Q_ASSERT(isModelLoaded());
|
|
|
|
if (!isModelLoaded() || !m_restoreStateFromText || m_isServer)
|
|
|
|
return;
|
|
|
|
|
2024-08-07 11:25:24 -04:00
|
|
|
m_restoringFromText = true;
|
|
|
|
emit restoringFromTextChanged();
|
2023-10-10 16:43:02 -04:00
|
|
|
|
|
|
|
m_stopGenerating = false;
|
|
|
|
m_ctx = LLModel::PromptContext();
|
|
|
|
|
|
|
|
auto promptFunc = std::bind(&ChatLLM::handleRestoreStateFromTextPrompt, this, std::placeholders::_1);
|
|
|
|
|
|
|
|
const QString promptTemplate = MySettings::globalInstance()->modelPromptTemplate(m_modelInfo);
|
|
|
|
const int32_t n_predict = MySettings::globalInstance()->modelMaxLength(m_modelInfo);
|
|
|
|
const int32_t top_k = MySettings::globalInstance()->modelTopK(m_modelInfo);
|
|
|
|
const float top_p = MySettings::globalInstance()->modelTopP(m_modelInfo);
|
2024-02-24 17:51:34 -05:00
|
|
|
const float min_p = MySettings::globalInstance()->modelMinP(m_modelInfo);
|
2023-10-10 16:43:02 -04:00
|
|
|
const float temp = MySettings::globalInstance()->modelTemperature(m_modelInfo);
|
|
|
|
const int32_t n_batch = MySettings::globalInstance()->modelPromptBatchSize(m_modelInfo);
|
|
|
|
const float repeat_penalty = MySettings::globalInstance()->modelRepeatPenalty(m_modelInfo);
|
|
|
|
const int32_t repeat_penalty_tokens = MySettings::globalInstance()->modelRepeatPenaltyTokens(m_modelInfo);
|
|
|
|
int n_threads = MySettings::globalInstance()->threadCount();
|
|
|
|
m_ctx.n_predict = n_predict;
|
|
|
|
m_ctx.top_k = top_k;
|
|
|
|
m_ctx.top_p = top_p;
|
2024-02-24 17:51:34 -05:00
|
|
|
m_ctx.min_p = min_p;
|
2023-10-10 16:43:02 -04:00
|
|
|
m_ctx.temp = temp;
|
|
|
|
m_ctx.n_batch = n_batch;
|
|
|
|
m_ctx.repeat_penalty = repeat_penalty;
|
|
|
|
m_ctx.repeat_last_n = repeat_penalty_tokens;
|
|
|
|
m_llModelInfo.model->setThreadCount(n_threads);
|
2024-02-21 15:45:32 -05:00
|
|
|
|
|
|
|
auto it = m_stateFromText.begin();
|
|
|
|
while (it < m_stateFromText.end()) {
|
|
|
|
auto &prompt = *it++;
|
|
|
|
Q_ASSERT(prompt.first == "Prompt: ");
|
|
|
|
Q_ASSERT(it < m_stateFromText.end());
|
|
|
|
|
|
|
|
auto &response = *it++;
|
|
|
|
Q_ASSERT(response.first != "Prompt: ");
|
|
|
|
auto responseText = response.second.toStdString();
|
|
|
|
|
|
|
|
m_llModelInfo.model->prompt(prompt.second.toStdString(), promptTemplate.toStdString(), promptFunc, nullptr,
|
2024-08-07 11:25:24 -04:00
|
|
|
/*allowContextShift*/ true, m_ctx, false, &responseText);
|
2023-10-10 16:43:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!m_stopGenerating) {
|
|
|
|
m_restoreStateFromText = false;
|
|
|
|
m_stateFromText.clear();
|
|
|
|
}
|
|
|
|
|
2024-08-07 11:25:24 -04:00
|
|
|
m_restoringFromText = false;
|
|
|
|
emit restoringFromTextChanged();
|
2024-05-15 14:07:03 -04:00
|
|
|
|
|
|
|
m_pristineLoadedState = false;
|
2023-09-29 13:53:43 -04:00
|
|
|
}
|