llama-batch.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #pragma once
  2. #include "llama.h"
  3. #include <array>
  4. #include <vector>
  5. // very similar to llama_batch,
  6. // but has more metadata about sequences
  7. struct llama_ubatch {
  8. bool equal_seqs;
  9. // TODO: whole_seqs for embeddings?
  10. uint32_t n_tokens; // total tokens (n_seq_tokens * n_seqs)
  11. uint32_t n_seq_tokens; // tokens per sequence
  12. uint32_t n_seqs;
  13. llama_token * token; // [n_tokens]
  14. float * embd; // [n_embd, n_tokens]
  15. llama_pos * pos; // [n_tokens]
  16. int32_t * n_seq_id; // [n_seqs]
  17. llama_seq_id ** seq_id; // [n_seqs]
  18. int8_t * output; // [n_tokens]
  19. };
  20. struct llama_sbatch_seq {
  21. int32_t n_seq_id;
  22. llama_seq_id * seq_id;
  23. size_t offset;
  24. size_t length;
  25. };
  26. // sequence-length-aware batch splitting
  27. struct llama_sbatch {
  28. // tokens left in this batch
  29. size_t n_tokens;
  30. size_t n_embd;
  31. bool logits_all; // TODO: remove once lctx.logits_all is removed too
  32. // sorted indices into the batch
  33. std::vector<size_t> ids;
  34. // batch indices of the output
  35. std::vector<size_t> out_ids;
  36. std::vector<llama_sbatch_seq> seq;
  37. const llama_batch * batch = nullptr;
  38. // buffers for the ubatch
  39. std::vector<llama_token> ubatch_token;
  40. std::vector<float> ubatch_embd;
  41. std::vector<llama_pos> ubatch_pos;
  42. std::vector<int32_t> ubatch_n_seq_id;
  43. std::vector<llama_seq_id *> ubatch_seq_id;
  44. std::vector<int8_t> ubatch_output;
  45. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false);
  46. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length);
  47. // simple split, unknown number of sequences of unequal lengths
  48. llama_ubatch split_simple(size_t n_ubatch);
  49. // make batches of equal-length sequences
  50. llama_ubatch split_equal(size_t n_ubatch);
  51. // sequence-wise split
  52. llama_ubatch split_seq(size_t n_ubatch);
  53. void from_batch(const llama_batch & batch, size_t n_embd, bool simple_split = false, bool logits_all = false);
  54. };
  55. // temporary allocate memory for the input batch if needed
  56. struct llama_batch_allocr {
  57. struct llama_batch batch;
  58. std::array<llama_seq_id, 1> seq_id_0 = { 0 }; // default sequence id
  59. std::vector<llama_pos> pos;
  60. std::vector<int32_t> n_seq_id;
  61. std::vector<llama_seq_id *> seq_id;
  62. std::vector<int8_t> logits;
  63. // optionally fulfill the batch returned by llama_batch_get_one
  64. llama_batch_allocr(struct llama_batch in_batch, llama_pos p0);
  65. };