| 1642 | } |
| 1643 | |
| 1644 | void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const { |
| 1645 | GGML_UNUSED(flags); |
| 1646 | |
| 1647 | io.write(&n_stream, sizeof(n_stream)); |
| 1648 | |
| 1649 | for (uint32_t s = 0; s < n_stream; ++s) { |
| 1650 | cell_ranges_t cr { s, {} }; |
| 1651 | |
| 1652 | uint32_t cell_count = 0; |
| 1653 | |
| 1654 | const auto & cells = v_cells[s]; |
| 1655 | |
| 1656 | // Count the number of cells with the specified seq_id |
| 1657 | // Find all the ranges of cells with this seq id (or all, when -1) |
| 1658 | uint32_t cell_range_begin = cells.size(); |
| 1659 | |
| 1660 | for (uint32_t i = 0; i < cells.size(); ++i) { |
| 1661 | if (!cells.is_empty(i) && (seq_id == -1 || cells.seq_has(i, seq_id))) { |
| 1662 | ++cell_count; |
| 1663 | if (cell_range_begin == cells.size()) { |
| 1664 | cell_range_begin = i; |
| 1665 | } |
| 1666 | } else { |
| 1667 | if (cell_range_begin != cells.size()) { |
| 1668 | cr.data.emplace_back(cell_range_begin, i); |
| 1669 | cell_range_begin = cells.size(); |
| 1670 | } |
| 1671 | } |
| 1672 | } |
| 1673 | |
| 1674 | if (cell_range_begin != cells.size()) { |
| 1675 | cr.data.emplace_back(cell_range_begin, cells.size()); |
| 1676 | } |
| 1677 | |
| 1678 | // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count |
| 1679 | uint32_t cell_count_check = 0; |
| 1680 | for (const auto & range : cr.data) { |
| 1681 | cell_count_check += range.second - range.first; |
| 1682 | } |
| 1683 | GGML_ASSERT(cell_count == cell_count_check); |
| 1684 | |
| 1685 | io.write(&cell_count, sizeof(cell_count)); |
| 1686 | |
| 1687 | // skip empty streams |
| 1688 | if (cell_count == 0) { |
| 1689 | continue; |
| 1690 | } |
| 1691 | |
| 1692 | state_write_meta(io, cr, seq_id); |
| 1693 | state_write_data(io, cr); |
| 1694 | } |
| 1695 | } |
| 1696 | |
| 1697 | void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { |
| 1698 | GGML_UNUSED(flags); |
no test coverage detected