main.cpp 6.6 KB
Newer Older
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
216
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <chrono>
#include <string>
#include <cstdio>
#include <cstdint>
#ifdef USE_CUDA
#include <cuda_runtime.h>
#endif
#include <stdlib.h>
#include "chatglm.h"
#include "chatglm_c.h"

//static int multi_round_flag = 0;

static double GetSpan(std::chrono::system_clock::time_point time1, std::chrono::system_clock::time_point time2) {
    auto duration = std::chrono::duration_cast<std::chrono::microseconds> (time2 - time1);
    return double(duration.count()) * std::chrono::microseconds::period::num / std::chrono::microseconds::period::den;
};


std::map <std::string, int> modelDict = {
        {"chatglm", 0}, {"chatglm—c", 1}
};

struct RunConfig {
    int model = 0; // 模型类型, 0 chatglm-c++,1 chatglm-c
    std::string path = "chatglm-6b-int8.bin"; // 模型文件路径
    int device = 0;
    int multi_round_flag = 0;
//	int threads = 4; // 使用的线程数
//	bool lowMemMode = false; // 是否使用低内存模式
};

void Usage() {
    std::cout << "Usage:" << std::endl;
    std::cout << "[-h|--help]:                  显示帮助" << std::endl;
    std::cout << "<-p|--path> <args>:           模型文件的路径" << std::endl;
    std::cout << "<-m|--model> <args>:          接口类型,默认为0,可以设置为0(chatglm c++接口),1(chatglm c接口)" << std::endl;
    std::cout << "<-d|--device> <args>:         推理使用的DCU设备号" << std::endl;
    std::cout << "<-r|--multi-round> <args>:    是否启用多轮方式对话,默认为0,可以设置为0(单轮对话),1(多轮对话)" << std::endl;
}

void ParseArgs(int argc, char **argv, RunConfig &config) {
    std::vector <std::string> sargv;
    for (int i = 0; i < argc; i++) {
        sargv.push_back(std::string(argv[i]));
    }
    for (int i = 1; i < argc; i++) {
        if (sargv[i] == "-h" || sargv[i] == "--help") {
            Usage();
            exit(0);
        }
        else if (sargv[i] == "-m" || sargv[i] == "--model") {
            if (modelDict.find(sargv[i + 1]) != modelDict.end()) {
                config.model = modelDict[sargv[++i]];
            } else {
                config.model = atoi(sargv[++i].c_str());
            }
        }
        else if (sargv[i] == "-p" || sargv[i] == "--path") {
            config.path = sargv[++i];
        }
        else if (sargv[i] == "-d" || sargv[i] == "--device") {
            config.device = atoi(sargv[++i].c_str());
        }
        else if (sargv[i] == "-r" || sargv[i] == "--multi-round") {
            config.multi_round_flag = atoi(sargv[++i].c_str());
        }
        else {
            Usage();
            exit(-1);
        }
    }
}

bool fileExists(const std::string& filename) {
    std::ifstream file(filename);
    return file.good();
}

//获取utf-8字符个数(utf-8下,英文字符一个站位一个字节,中文字符一个站位3个字节)
static int getUtf8LetterNumber(const char *s)
{
    int i = 0, j = 0;
    while (s[i])
    {

        if ((s[i] & 0xc0) != 0x80) j++;
        i++;
    }
    return j;
}

int chat_history(fastllm::ChatGLMModel* chatGlm, const char* input_Str) {
    static int sRound = 0;
    static std::string history;
    static int tokens = 0;
    std::string ret = "";
    std::string input(input_Str);
    if (input == "reset") {
        history = "";
        sRound = 0;
        return 0;
    }
    history += ("[Round " + std::to_string(sRound++) + "]\n问:" + input);
    if(getUtf8LetterNumber(history.c_str()) > 2048)
    {
        history = "";
        sRound = 0;
    }
    tokens = 0;
    auto prompt = sRound > 1 ? history : input;
    auto st = std::chrono::system_clock::now();

    ret = chatGlm->Response((prompt), [](int index, const char* content) {
        if (index == 0) {
            printf("ChatGLM:%s", content);
            tokens += 1;
        }
        if (index > 0) {
            printf("%s", content);
            tokens += 1;
        }
        if (index == -1) {
            printf("\n");
        }

    });

    float spend = GetSpan(st, std::chrono::system_clock::now());
    //字数统计
    int str_len = getUtf8LetterNumber(ret.c_str());
    printf("word_count = %d, token_count = %d, spend = %fs, word/s = %f, tokens/s = %f: .\n", str_len, tokens, spend, str_len/spend, tokens/spend);

    history += ("\n答:" + ret + "\n");

    return ret.length();
}

int main(int argc, char **argv) {
    RunConfig config;
    ParseArgs(argc, argv, config);
    if(!fileExists(config.path)){
        printf("model path is not exist!\n");
        return -1;
    }

    if (config.model == 0) {
#ifdef USE_CUDA
        cudaSetDevice(config.device);
#endif
        fastllm::ChatGLMModel chatGlm;
        chatGlm.LoadFromFile(config.path);
        chatGlm.WarmUp();
        static int tokens = 0;
        while (true) {
            printf("用户: ");
            std::string input;
            std::getline(std::cin, input);
            if (input == "stop") {
                break;
            }
            if(0 == config.multi_round_flag){
                tokens = 0;
                auto st = std::chrono::system_clock::now();
                std::string ret = chatGlm.Response((input), [](int index, const char* content) {
                    if (index == 0) {
                        printf("ChatGLM:%s", content);
                        tokens += 1;
                    }
                    if (index > 0) {
                        printf("%s", content);
                        tokens += 1;
                    }
                    if (index == -1) {
                        printf("\n");
                    }
                });

                float spend = GetSpan(st, std::chrono::system_clock::now());
                //字数统计
                int str_len = getUtf8LetterNumber(ret.c_str());
                printf("word_count = %d, token_count = %d, spend = %fs, word/s = %f, tokens/s = %f: .\n", str_len, tokens, spend, str_len/spend, tokens/spend);
            }
            else{
                chat_history(&chatGlm, input.c_str());
            }
        }
    } else if (config.model == 1) {
        void* modelEngine = NULL;
        initLLMEngine(modelEngine, config.path.c_str(), config.device);
        char *output = NULL;

        while (true) {
            printf("用户: ");
            std::string input;
            std::getline(std::cin, input);
            //input = "晚上睡不着怎么办";
            if (input == "stop") {
                break;
            }
            chat(modelEngine, input.c_str(), output);

            printf("ChatGLM:%s\n", output);
        }
        releaseLLMEngine(modelEngine);
    }
    else {
        Usage();
        exit(-1);
    }
    return 0;
}