Skip to content

Commit 1b09d09

Browse files
committed
create append_pooling operation; allow to specify attention_type; add last token pooling; update examples
1 parent 1e37436 commit 1b09d09

File tree

7 files changed

+177
-75
lines changed

7 files changed

+177
-75
lines changed

common/common.cpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,18 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
528528
/**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
529529
else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
530530
else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
531+
else if (value == "last") { params.pooling_type = LLAMA_POOLING_TYPE_LAST; }
532+
else { invalid_param = true; }
533+
return true;
534+
}
535+
if (arg == "--attention") {
536+
if (++i >= argc) {
537+
invalid_param = true;
538+
return true;
539+
}
540+
std::string value(argv[i]);
541+
/**/ if (value == "causal") { params.attention_type = LLAMA_ATTENTION_TYPE_CAUSAL; }
542+
else if (value == "non-causal") { params.attention_type = LLAMA_ATTENTION_TYPE_NONCAUSAL; }
531543
else { invalid_param = true; }
532544
return true;
533545
}
@@ -1443,8 +1455,10 @@ void gpt_params_print_usage(int /*argc*/, char ** argv, const gpt_params & param
14431455
printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
14441456
printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
14451457
printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
1446-
printf(" --pooling {none,mean,cls}\n");
1458+
printf(" --pooling {none,mean,cls,last}\n");
14471459
printf(" pooling type for embeddings, use model default if unspecified\n");
1460+
printf(" --attn-type {causal,non-causal}\n");
1461+
printf(" attention type for generation, use model default if unspecified\n");
14481462
printf(" -dt N, --defrag-thold N\n");
14491463
printf(" KV cache defragmentation threshold (default: %.1f, < 0 - disabled)\n", params.defrag_thold);
14501464
printf(" --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
@@ -2042,6 +2056,7 @@ struct llama_context_params llama_context_params_from_gpt_params(const gpt_param
20422056
cparams.yarn_beta_slow = params.yarn_beta_slow;
20432057
cparams.yarn_orig_ctx = params.yarn_orig_ctx;
20442058
cparams.pooling_type = params.pooling_type;
2059+
cparams.attention_type = params.attention_type;
20452060
cparams.defrag_thold = params.defrag_thold;
20462061
cparams.cb_eval = params.cb_eval;
20472062
cparams.cb_eval_user_data = params.cb_eval_user_data;

common/common.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ struct gpt_params {
9595

9696
enum llama_rope_scaling_type rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
9797
enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_UNSPECIFIED; // pooling type for embeddings
98+
enum llama_attention_type attention_type = LLAMA_ATTENTION_TYPE_UNSPECIFIED; // attention type
9899

99100
// // sampling parameters
100101
struct llama_sampling_params sparams;

examples/embedding/embedding.cpp

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,25 @@ static std::vector<std::string> split_lines(const std::string & s) {
1717
return lines;
1818
}
1919

20-
static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id) {
21-
for (size_t i = 0; i < tokens.size(); i++) {
22-
llama_batch_add(batch, tokens[i], i, { seq_id }, i == tokens.size() - 1);
20+
static bool needs_logit(enum llama_pooling_type pooling_type, int pos, int n_tokens) {
21+
switch (pooling_type) {
22+
case LLAMA_POOLING_TYPE_MEAN:
23+
case LLAMA_POOLING_TYPE_NONE:
24+
return true;
25+
case LLAMA_POOLING_TYPE_CLS:
26+
return pos == 0;
27+
case LLAMA_POOLING_TYPE_LAST:
28+
return pos == n_tokens - 1;
29+
default:
30+
GGML_ASSERT(false && "unsupported pooling type");
31+
}
32+
}
33+
34+
static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id, enum llama_pooling_type pooling_type) {
35+
int n_tokens = tokens.size();
36+
for (size_t i = 0; i < n_tokens; i++) {
37+
bool logit = needs_logit(pooling_type, i, n_tokens);
38+
llama_batch_add(batch, tokens[i], i, { seq_id }, logit);
2339
}
2440
}
2541

@@ -40,13 +56,7 @@ static void batch_decode(llama_context * ctx, llama_batch & batch, float * outpu
4056

4157
// try to get sequence embeddings - supported only when pooling_type is not NONE
4258
const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
43-
if (embd == NULL) {
44-
embd = llama_get_embeddings_ith(ctx, i);
45-
if (embd == NULL) {
46-
fprintf(stderr, "%s: failed to get embeddings for token %d\n", __func__, i);
47-
continue;
48-
}
49-
}
59+
GGML_ASSERT(embd != NULL && "failed to get sequence embeddings");
5060

5161
float * out = output + batch.seq_id[i][0] * n_embd;
5262
//TODO: I would also add a parameter here to enable normalization or not.
@@ -99,6 +109,12 @@ int main(int argc, char ** argv) {
99109
const int n_ctx_train = llama_n_ctx_train(model);
100110
const int n_ctx = llama_n_ctx(ctx);
101111

112+
const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
113+
if (pooling_type == LLAMA_POOLING_TYPE_NONE) {
114+
fprintf(stderr, "%s: error: pooling type NONE not supported\n", __func__);
115+
return 1;
116+
}
117+
102118
if (n_ctx > n_ctx_train) {
103119
fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
104120
__func__, n_ctx_train, n_ctx);
@@ -178,7 +194,7 @@ int main(int argc, char ** argv) {
178194
}
179195

180196
// add to batch
181-
batch_add_seq(batch, inp, s);
197+
batch_add_seq(batch, inp, s, pooling_type);
182198
s += 1;
183199
}
184200

examples/gritlm/gritlm.cpp

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ static std::vector<std::vector<float>> encode(llama_context * ctx, const std::ve
4444

4545
// clear previous kv_cache values (irrelevant for embeddings)
4646
llama_kv_cache_clear(ctx);
47-
llama_set_causal_attn(ctx, false);
4847

4948
// run model
5049
llama_decode(ctx, batch);
@@ -98,7 +97,6 @@ static std::string generate(llama_context * ctx, const std::string & prompt, boo
9897
llama_token eos_token = llama_token_eos(mdl);
9998

10099
llama_kv_cache_clear(ctx);
101-
llama_set_causal_attn(ctx, true);
102100
llama_batch bat = llama_batch_init(llama_n_batch(ctx), 0, 1);
103101

104102
std::vector<llama_token> inputs = llama_tokenize(mdl, prompt, false, true);
@@ -164,9 +162,14 @@ int main(int argc, char * argv[]) {
164162

165163
llama_model * mdl = llama_load_model_from_file(params.model.c_str(), mparams);
166164

167-
// create new context - set to embedding mode
165+
// create generation context
166+
llama_context * ctx_gen = llama_new_context_with_model(mdl, cparams);
167+
168+
// create embedding context
168169
cparams.embeddings = true;
169-
llama_context * ctx = llama_new_context_with_model(mdl, cparams);
170+
cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
171+
cparams.attention_type = LLAMA_ATTENTION_TYPE_NONCAUSAL;
172+
llama_context * ctx_emb = llama_new_context_with_model(mdl, cparams);
170173

171174
// ### Embedding/Representation ###
172175
// samples taken from: https://github.com/ContextualAI/gritlm#basic
@@ -184,8 +187,8 @@ int main(int argc, char * argv[]) {
184187
};
185188

186189
// No need to add instruction for retrieval documents
187-
const std::vector<std::vector<float>> d_rep = encode(ctx, documents, gritlm_instruction(""));
188-
const std::vector<std::vector<float>> q_rep = encode(ctx, queries, gritlm_instruction(instruction));
190+
const std::vector<std::vector<float>> d_rep = encode(ctx_emb, documents, gritlm_instruction(""));
191+
const std::vector<std::vector<float>> q_rep = encode(ctx_emb, queries, gritlm_instruction(instruction));
189192

190193
const int n_embd = llama_n_embd(mdl);
191194

@@ -204,10 +207,11 @@ int main(int argc, char * argv[]) {
204207
// GritLM models are not finetuned with system prompts, as you can just include system-like instructions together with your user instruction
205208
{
206209
const std::string prompt = "<|user|>\nPlease write me a poem about my recent hike of Mt. Fuji at midnight in the style of Shakespeare.\n<|assistant|>\n";
207-
std::string response = generate(ctx, prompt, true);
210+
std::string response = generate(ctx_gen, prompt, true);
208211
}
209212

210-
llama_free(ctx);
213+
llama_free(ctx_gen);
214+
llama_free(ctx_emb);
211215
llama_free_model(mdl);
212216
llama_backend_free();
213217

examples/retrieval/retrieval.cpp

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,25 @@ static std::vector<chunk> chunk_file(const std::string & filename, int chunk_siz
133133
return chunks;
134134
}
135135

136-
static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id) {
136+
static bool needs_logit(enum llama_pooling_type pooling_type, int pos, int n_tokens) {
137+
switch (pooling_type) {
138+
case LLAMA_POOLING_TYPE_MEAN:
139+
case LLAMA_POOLING_TYPE_NONE:
140+
return true;
141+
case LLAMA_POOLING_TYPE_CLS:
142+
return pos == 0;
143+
case LLAMA_POOLING_TYPE_LAST:
144+
return pos == n_tokens - 1;
145+
default:
146+
GGML_ASSERT(false && "unsupported pooling type");
147+
}
148+
}
149+
150+
static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id, enum llama_pooling_type pooling_type) {
151+
int n_tokens = tokens.size();
137152
for (size_t i = 0; i < tokens.size(); i++) {
138-
llama_batch_add(batch, tokens[i], i, { seq_id }, i == tokens.size() - 1);
153+
bool logit = needs_logit(pooling_type, i, n_tokens);
154+
llama_batch_add(batch, tokens[i], i, { seq_id }, logit);
139155
}
140156
}
141157

@@ -217,6 +233,7 @@ int main(int argc, char ** argv) {
217233

218234
const int n_ctx_train = llama_n_ctx_train(model);
219235
const int n_ctx = llama_n_ctx(ctx);
236+
const enum llama_pooling_type pooling_type = llama_pooling_type(ctx);
220237

221238
if (n_ctx > n_ctx_train) {
222239
fprintf(stderr, "%s: warning: model was trained on only %d context tokens (%d specified)\n",
@@ -288,7 +305,7 @@ int main(int argc, char ** argv) {
288305
}
289306

290307
// add to batch
291-
batch_add_seq(batch, inp, s);
308+
batch_add_seq(batch, inp, s, pooling_type);
292309
s += 1;
293310
}
294311

@@ -311,7 +328,7 @@ int main(int argc, char ** argv) {
311328
std::vector<int32_t> query_tokens = llama_tokenize(ctx, query, true);
312329

313330
struct llama_batch query_batch = llama_batch_init(n_batch, 0, 1);
314-
batch_add_seq(query_batch, query_tokens, 0);
331+
batch_add_seq(query_batch, query_tokens, 0, pooling_type);
315332

316333
std::vector<float> query_emb(n_embd, 0);
317334
batch_decode(ctx, query_batch, query_emb.data(), 1, n_embd);

0 commit comments

Comments
 (0)