Skip to content

Commit d034784

Browse files
committed
llama : fix embeddings
ggml-ci
1 parent a0fc626 commit d034784

File tree

6 files changed

+127
-62
lines changed

6 files changed

+127
-62
lines changed

common/common.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1299,7 +1299,7 @@ struct llama_context_params llama_context_params_from_gpt_params(const gpt_param
12991299
cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
13001300
cparams.seed = params.seed;
13011301
cparams.logits_all = params.logits_all;
1302-
cparams.embedding = params.embedding;
1302+
cparams.embeddings = params.embedding;
13031303
cparams.rope_scaling_type = params.rope_scaling_type;
13041304
cparams.rope_freq_base = params.rope_freq_base;
13051305
cparams.rope_freq_scale = params.rope_freq_scale;

examples/embedding/embedding.cpp

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ static std::vector<std::string> split_lines(const std::string & s) {
1919

2020
static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id) {
2121
for (size_t i = 0; i < tokens.size(); i++) {
22-
llama_batch_add(batch, tokens[i], i, { seq_id }, false);
22+
llama_batch_add(batch, tokens[i], i, { seq_id }, i == tokens.size() - 1);
2323
}
2424
}
2525

@@ -45,9 +45,13 @@ static void batch_decode(llama_context * ctx, llama_batch & batch, float * outpu
4545
}
4646

4747
// normalize on copy
48-
for (int k = 0; k < n_seq; k++) {
49-
float * emb = llama_get_embeddings_ith(ctx, k);
50-
float * out = output + k * n_embd;
48+
for (int i = 0; i < batch.n_tokens; i++) {
49+
if (!batch.logits[i]) {
50+
continue;
51+
}
52+
53+
float * emb = llama_get_embeddings_ith(ctx, i);
54+
float * out = output + batch.seq_id[i][0] * n_embd;
5155
normalize(emb, out, n_embd);
5256
}
5357
}
@@ -145,6 +149,7 @@ int main(int argc, char ** argv) {
145149
for (int k = 0; k < n_prompts; k++) {
146150
// clamp to n_batch tokens
147151
auto & inp = inputs[k];
152+
148153
const uint64_t n_toks = inp.size();
149154

150155
// encode if at capacity

examples/server-embd.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import asyncio
2+
import requests
3+
import numpy as np
4+
5+
n = 8
6+
7+
result = []
8+
9+
async def requests_post_async(*args, **kwargs):
10+
return await asyncio.to_thread(requests.post, *args, **kwargs)
11+
12+
async def main():
13+
model_url = "http://127.0.0.1:6900"
14+
responses: list[requests.Response] = await asyncio.gather(*[requests_post_async(
15+
url= f"{model_url}/embedding",
16+
json= {"content": str(i)*32}
17+
) for i in range(n)])
18+
19+
for response in responses:
20+
embedding = response.json()["embedding"]
21+
print(embedding[-8:])
22+
result.append(embedding)
23+
24+
asyncio.run(main())
25+
26+
# compute cosine similarity
27+
28+
for i in range(n-1):
29+
for j in range(i+1, n):
30+
embedding1 = np.array(result[i])
31+
embedding2 = np.array(result[j])
32+
similarity = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))
33+
print(f"Similarity between {i} and {j}: {similarity:.2f}")
34+

examples/server/server.cpp

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1210,7 +1210,7 @@ struct llama_server_context
12101210
queue_results.send(res);
12111211
}
12121212

1213-
void send_embedding(server_slot &slot)
1213+
void send_embedding(server_slot & slot, const llama_batch & batch)
12141214
{
12151215
task_result res;
12161216
res.id = slot.task_id;
@@ -1219,6 +1219,7 @@ struct llama_server_context
12191219
res.stop = true;
12201220

12211221
const int n_embd = llama_n_embd(model);
1222+
12221223
if (!params.embedding)
12231224
{
12241225
LOG_WARNING("embedding disabled", {{"params.embedding", params.embedding}});
@@ -1229,12 +1230,19 @@ struct llama_server_context
12291230
}
12301231
else
12311232
{
1232-
const float *data = llama_get_embeddings(ctx);
1233-
std::vector<float> embedding(data, data + n_embd);
1234-
res.result_json = json
1235-
{
1236-
{"embedding", embedding},
1237-
};
1233+
for (int i = 0; i < batch.n_tokens; ++i) {
1234+
if (!batch.logits[i] || batch.seq_id[i][0] != slot.id) {
1235+
continue;
1236+
}
1237+
1238+
const float * data = llama_get_embeddings_ith(ctx, i);
1239+
std::vector<float> embedding(data, data + n_embd);
1240+
1241+
res.result_json = json
1242+
{
1243+
{"embedding", embedding },
1244+
};
1245+
}
12381246
}
12391247
queue_results.send(res);
12401248
}
@@ -1845,7 +1853,7 @@ struct llama_server_context
18451853
ga_i += ga_w/ga_n;
18461854
}
18471855
}
1848-
llama_batch_add(batch, prefix_tokens[slot.n_past], system_tokens.size() + slot_npast, {slot.id }, false);
1856+
llama_batch_add(batch, prefix_tokens[slot.n_past], system_tokens.size() + slot_npast, { slot.id }, false);
18491857
slot_npast++;
18501858
}
18511859

@@ -1881,7 +1889,7 @@ struct llama_server_context
18811889

18821890
for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch)
18831891
{
1884-
const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
1892+
const int32_t n_tokens = std::min(n_batch, batch.n_tokens - i);
18851893

18861894
for (auto & slot : slots)
18871895
{
@@ -1954,7 +1962,7 @@ struct llama_server_context
19541962
// prompt evaluated for embedding
19551963
if (slot.embedding)
19561964
{
1957-
send_embedding(slot);
1965+
send_embedding(slot, batch_view);
19581966
slot.release();
19591967
slot.i_batch = -1;
19601968
continue;
@@ -2330,7 +2338,6 @@ static void server_params_parse(int argc, char **argv, server_params &sparams,
23302338
break;
23312339
}
23322340
params.n_batch = std::stoi(argv[i]);
2333-
params.n_batch = std::min(512, params.n_batch);
23342341
}
23352342
else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
23362343
{

0 commit comments

Comments
 (0)