llama-batch.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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] // TODO: remove, should belong to only 1 sequence
  17. llama_seq_id ** seq_id; // [n_seqs] // TODO: become llama_seq_id * seq_id;
  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. // sorted indices into the batch
  32. std::vector<int64_t> ids;
  33. // batch indices of the output
  34. std::vector<int64_t> out_ids;
  35. std::vector<llama_sbatch_seq> seq;
  36. const llama_batch * batch = nullptr;
  37. // buffers for the ubatches
  38. // TODO: very hacky, this needs a complete rework
  39. struct ubatch_data {
  40. std::vector<llama_token> token;
  41. std::vector<float> embd;
  42. std::vector<llama_pos> pos;
  43. std::vector<int32_t> n_seq_id;
  44. std::vector<llama_seq_id *> seq_id;
  45. std::vector<int8_t> output;
  46. };
  47. std::vector<ubatch_data> udatas;
  48. llama_ubatch reserve_ubatch(size_t n_ubatch, bool has_embd = false);
  49. void add_seq_to_ubatch(llama_ubatch & ubatch, llama_sbatch_seq & seq, size_t length);
  50. // simple split, unknown number of sequences of unequal lengths
  51. llama_ubatch split_simple(size_t n_ubatch);
  52. // make batches of equal-length sequences
  53. llama_ubatch split_equal(size_t n_ubatch);
  54. // sequence-wise split
  55. llama_ubatch split_seq(size_t n_ubatch);
  56. llama_sbatch() = default;
  57. llama_sbatch(const llama_batch & batch, size_t n_embd, bool simple_split = false);
  58. };
  59. // temporary allocate memory for the input batch if needed
  60. struct llama_batch_allocr {
  61. struct llama_batch batch;
  62. std::array<llama_seq_id, 1> seq_id_0 = { 0 }; // default sequence id
  63. std::vector<llama_pos> pos;
  64. std::vector<int32_t> n_seq_id;
  65. std::vector<llama_seq_id *> seq_id;
  66. std::vector<int8_t> logits;
  67. // optionally fulfill the batch returned by llama_batch_get_one
  68. llama_batch_allocr(struct llama_batch in_batch, llama_pos p0);
  69. };