llama

Форк
0
/
simple.cpp 
169 строк · 4.5 Кб
1
#include "arg.h"
2
#include "common.h"
3
#include "log.h"
4
#include "llama.h"
5

6
#include <vector>
7

8
static void print_usage(int, char ** argv) {
9
    LOG("\nexample usage:\n");
10
    LOG("\n    %s -m model.gguf -p \"Hello my name is\" -n 32\n", argv[0]);
11
    LOG("\n");
12
}
13

14
int main(int argc, char ** argv) {
15
    gpt_params params;
16

17
    params.prompt = "Hello my name is";
18
    params.n_predict = 32;
19

20
    if (!gpt_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON, print_usage)) {
21
        return 1;
22
    }
23

24
    gpt_init();
25

26
    // total length of the sequence including the prompt
27
    const int n_predict = params.n_predict;
28

29
    // init LLM
30

31
    llama_backend_init();
32
    llama_numa_init(params.numa);
33

34
    // initialize the model
35

36
    llama_model_params model_params = llama_model_params_from_gpt_params(params);
37

38
    llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);
39

40
    if (model == NULL) {
41
        fprintf(stderr , "%s: error: unable to load model\n" , __func__);
42
        return 1;
43
    }
44

45
    // initialize the context
46

47
    llama_context_params ctx_params = llama_context_params_from_gpt_params(params);
48

49
    llama_context * ctx = llama_new_context_with_model(model, ctx_params);
50

51
    if (ctx == NULL) {
52
        fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
53
        return 1;
54
    }
55

56
    auto sparams = llama_sampler_chain_default_params();
57

58
    sparams.no_perf = false;
59

60
    llama_sampler * smpl = llama_sampler_chain_init(sparams);
61

62
    llama_sampler_chain_add(smpl, llama_sampler_init_greedy());
63

64
    // tokenize the prompt
65

66
    std::vector<llama_token> tokens_list;
67
    tokens_list = ::llama_tokenize(ctx, params.prompt, true);
68

69
    const int n_ctx    = llama_n_ctx(ctx);
70
    const int n_kv_req = tokens_list.size() + (n_predict - tokens_list.size());
71

72
    LOG("\n");
73
    LOG_INF("%s: n_predict = %d, n_ctx = %d, n_kv_req = %d\n", __func__, n_predict, n_ctx, n_kv_req);
74

75
    // make sure the KV cache is big enough to hold all the prompt and generated tokens
76
    if (n_kv_req > n_ctx) {
77
        LOG_ERR("%s: error: n_kv_req > n_ctx, the required KV cache size is not big enough\n", __func__);
78
        LOG_ERR("%s:        either reduce n_predict or increase n_ctx\n", __func__);
79
        return 1;
80
    }
81

82
    // print the prompt token-by-token
83

84
    LOG("\n");
85

86
    for (auto id : tokens_list) {
87
        LOG("%s", llama_token_to_piece(ctx, id).c_str());
88
    }
89

90
    // create a llama_batch with size 512
91
    // we use this object to submit token data for decoding
92

93
    llama_batch batch = llama_batch_init(512, 0, 1);
94

95
    // evaluate the initial prompt
96
    for (size_t i = 0; i < tokens_list.size(); i++) {
97
        llama_batch_add(batch, tokens_list[i], i, { 0 }, false);
98
    }
99

100
    // llama_decode will output logits only for the last token of the prompt
101
    batch.logits[batch.n_tokens - 1] = true;
102

103
    if (llama_decode(ctx, batch) != 0) {
104
        LOG("%s: llama_decode() failed\n", __func__);
105
        return 1;
106
    }
107

108
    // main loop
109

110
    int n_cur    = batch.n_tokens;
111
    int n_decode = 0;
112

113
    const auto t_main_start = ggml_time_us();
114

115
    while (n_cur <= n_predict) {
116
        // sample the next token
117
        {
118
            const llama_token new_token_id = llama_sampler_sample(smpl, ctx, -1);
119

120
            // is it an end of generation?
121
            if (llama_token_is_eog(model, new_token_id) || n_cur == n_predict) {
122
                LOG("\n");
123

124
                break;
125
            }
126

127
            LOG("%s", llama_token_to_piece(ctx, new_token_id).c_str());
128
            fflush(stdout);
129

130
            // prepare the next batch
131
            llama_batch_clear(batch);
132

133
            // push this new token for next evaluation
134
            llama_batch_add(batch, new_token_id, n_cur, { 0 }, true);
135

136
            n_decode += 1;
137
        }
138

139
        n_cur += 1;
140

141
        // evaluate the current batch with the transformer model
142
        if (llama_decode(ctx, batch)) {
143
            LOG_ERR("%s : failed to eval, return code %d\n", __func__, 1);
144
            return 1;
145
        }
146
    }
147

148
    LOG("\n");
149

150
    const auto t_main_end = ggml_time_us();
151

152
    LOG_INF("%s: decoded %d tokens in %.2f s, speed: %.2f t/s\n",
153
            __func__, n_decode, (t_main_end - t_main_start) / 1000000.0f, n_decode / ((t_main_end - t_main_start) / 1000000.0f));
154

155
    LOG("\n");
156
    llama_perf_sampler_print(smpl);
157
    llama_perf_context_print(ctx);
158

159
    LOG("\n");
160

161
    llama_batch_free(batch);
162
    llama_sampler_free(smpl);
163
    llama_free(ctx);
164
    llama_free_model(model);
165

166
    llama_backend_free();
167

168
    return 0;
169
}
170

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.