gritlm results match

This commit is contained in:
Douglas Hanley 2024-03-03 23:59:28 -06:00
parent 4be8fb18ed
commit e79195fc53
2 changed files with 19 additions and 15 deletions

View File

@ -38,11 +38,14 @@ static std::vector<std::vector<float>> encode(llama_context* ctx, const std::vec
// testing with and without EOS - unexpected embeddings in both cases - GritLM seems to have EOS = ""
std::string input_string = instruction + sentences[i];
// std::string input_string = sentences[i];
auto inputs = llama_tokenize(mdl, input_string, true, false);
// https://github.com/ContextualAI/gritlm/blob/92025b16534712b31b3c4aaaf069350e222bd5f8/gritlm/gritlm.py#L116
// inputs.push_back(llama_token_eos(mdl));
// we want to ignore instruction tokens for mean pooling
auto inputs_instruct = llama_tokenize(mdl, instruction, true, false);
int n_inst = inputs_instruct.size();
// debug tokens - these are matching as referenced in their sample so doesn't appear to be a token issue
std::for_each(inputs.begin(), inputs.end(), [&ctx](llama_token t) {
std::printf("[%u:%s]", t, llama_token_to_piece(ctx, t).c_str());
@ -68,7 +71,7 @@ static std::vector<std::vector<float>> encode(llama_context* ctx, const std::vec
std::vector<float> emb_unorm(n_embd, 0.0f);
// sum up all token embeddings
for (int k = 0; k < n_toks; k++) {
for (int k = n_inst; k < n_toks; k++) {
float * emb = llama_get_embeddings_ith(ctx, k);
for (int j = 0; j < n_embd; j++) {
emb_unorm[j] += emb[j];
@ -76,8 +79,9 @@ static std::vector<std::vector<float>> encode(llama_context* ctx, const std::vec
}
// divide by number of tokens (mean pooling)
int n_sent = n_toks - n_inst;
for (int j = 0; j < n_embd; j++) {
emb_unorm[j] /= n_toks;
emb_unorm[j] /= n_sent;
}
auto emb_norm = std::vector<float>(emb_unorm.size());
@ -97,12 +101,13 @@ static std::vector<std::vector<float>> encode(llama_context* ctx, const std::vec
return result;
}
// ./embeddings -m ggml-gritlm-7b-q8_0.gguf -ngl 33
// ./gritlm -m ggml-gritlm-7b-q8_0.gguf -ngl 99
int main(int argc, char* argv[])
{
gpt_params params;
if (!gpt_params_parse(argc, argv, params))
if (!gpt_params_parse(argc, argv, params)) {
return 1;
}
auto mparams = llama_model_params_from_gpt_params(params);
auto cparams = llama_context_params_from_gpt_params(params);
@ -116,7 +121,7 @@ int main(int argc, char* argv[])
return true;
};
cparams.embedding = true;
// cparams.do_pooling = false;
cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
llama_backend_init();
@ -127,15 +132,14 @@ int main(int argc, char* argv[])
// ### Embedding/Representation ### taken sample from here:
// https://github.com/ContextualAI/gritlm?tab=readme-ov-file#basic
{
auto instruction = std::string{ "Given a scientific paper title, retrieve the paper's abstract" };
std::string instruction = "Given a scientific paper title, retrieve the paper's abstract";
auto queries = std::vector<std::string>{
// "hello world",
std::vector<std::string> queries = {
"Bitcoin: A Peer-to-Peer Electronic Cash System",
"Generative Representational Instruction Tuning",
};
auto documents = std::vector<std::string>{
std::vector<std::string> documents = {
"A purely peer-to-peer version of electronic cash would allow online payments to be sent directly from one party to another without going through a financial institution. Digital signatures provide part of the solution, but the main benefits are lost if a trusted third party is still required to prevent double-spending. We propose a solution to the double-spending problem using a peer-to-peer network. The network timestamps transactions by hashing them into an ongoing chain of hash-based proof-of-work, forming a record that cannot be changed without redoing the proof-of-work. The longest chain not only serves as proof of the sequence of events witnessed, but proof that it came from the largest pool of CPU power. As long as a majority of CPU power is controlled by nodes that are not cooperating to attack the network, they'll generate the longest chain and outpace attackers. The network itself requires minimal structure. Messages are broadcast on a best effort basis, and nodes can leave and rejoin the network at will, accepting the longest proof-of-work chain as proof of what happened while they were gone.",
"All text-based language problems can be reduced to either generation or embedding. Current models only perform well at one or the other. We introduce generative representational instruction tuning (GRIT) whereby a large language model is trained to handle both generative and embedding tasks by distinguishing between them through instructions. Compared to other open models, our resulting GritLM 7B sets a new state of the art on the Massive Text Embedding Benchmark (MTEB) and outperforms all models up to its size on a range of generative tasks. By scaling up further, GritLM 8X7B outperforms all open generative language models that we tried while still being among the best embedding models. Notably, we find that GRIT matches training on only generative or embedding data, thus we can unify both at no performance loss. Among other benefits, the unification via GRIT speeds up Retrieval-Augmented Generation (RAG) by > 60% for long documents, by no longer requiring separate retrieval and generation models. Models, code, etc. are freely available at https://github.com/ContextualAI/gritlm.",
};
@ -148,10 +152,10 @@ int main(int argc, char* argv[])
auto d_rep = encode(ctx, documents, gritlm_instruction(""));
auto q_rep = encode(ctx, queries, gritlm_instruction(instruction));
auto cosine_sim_q0_d0 = 1 - cosine_similarity(q_rep[0], d_rep[0]);
auto cosine_sim_q0_d1 = 1 - cosine_similarity(q_rep[0], d_rep[1]);
auto cosine_sim_q1_d0 = 1 - cosine_similarity(q_rep[1], d_rep[0]);
auto cosine_sim_q1_d1 = 1 - cosine_similarity(q_rep[1], d_rep[1]);
auto cosine_sim_q0_d0 = cosine_similarity(q_rep[0], d_rep[0]);
auto cosine_sim_q0_d1 = cosine_similarity(q_rep[0], d_rep[1]);
auto cosine_sim_q1_d0 = cosine_similarity(q_rep[1], d_rep[0]);
auto cosine_sim_q1_d1 = cosine_similarity(q_rep[1], d_rep[1]);
std::printf("Cosine similarity between \"%.50s\" and \"%.50s\" is: %.3f\n", queries[0].c_str(), documents[0].c_str(), cosine_sim_q0_d0);
std::printf("Cosine similarity between \"%.50s\" and \"%.50s\" is: %.3f\n", queries[0].c_str(), documents[1].c_str(), cosine_sim_q0_d1);

View File

@ -1684,7 +1684,6 @@ struct llama_cparams {
bool embeddings;
bool offload_kqv;
enum llama_pooling_type pooling_type;
ggml_backend_sched_eval_callback cb_eval;
@ -12145,6 +12144,7 @@ struct llama_context * llama_new_context_with_model(
cparams.embeddings = params.embeddings;
cparams.offload_kqv = params.offload_kqv;
cparams.pooling_type = params.pooling_type;
cparams.causal_attn = !params.embedding;
cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;