MCPcopy Create free account
hub / github.com/Tiiny-AI/PowerInfer / llama_kv_cache_init

Function llama_kv_cache_init

llama.cpp:1614–1677  ·  view source on GitHub ↗

kv cache helpers

Source from the content-addressed store, hash-verified

1612// kv cache helpers
1613//
1614static bool llama_kv_cache_init(
1615 const struct llama_hparams & hparams,
1616 struct llama_kv_cache & cache,
1617 ggml_type wtype,
1618 uint32_t n_ctx,
1619 int n_gpu_layers) {
1620 const uint32_t n_embd = hparams.n_embd_gqa();
1621 const uint32_t n_layer = hparams.n_layer;
1622
1623 const int64_t n_mem = n_layer*n_ctx;
1624 const int64_t n_elements = n_embd*n_mem;
1625
1626 cache.has_shift = false;
1627
1628 cache.head = 0;
1629 cache.size = n_ctx;
1630
1631 cache.cells.clear();
1632 cache.cells.resize(n_ctx);
1633
1634 cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*ggml_tensor_overhead());
1635 memset(cache.buf.data, 0, cache.buf.size);
1636
1637 struct ggml_init_params params;
1638 params.mem_size = cache.buf.size;
1639 params.mem_buffer = cache.buf.data;
1640 params.no_alloc = false;
1641
1642 cache.ctx = ggml_init(params);
1643
1644 if (!cache.ctx) {
1645 LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
1646 return false;
1647 }
1648
1649 cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
1650 cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
1651 ggml_set_name(cache.k, "cache_k");
1652 ggml_set_name(cache.v, "cache_v");
1653
1654 (void) n_gpu_layers;
1655
1656#ifdef GGML_USE_CUBLAS
1657 if (ggml_cublas_loaded()) {
1658 size_t vram_kv_cache = 0;
1659
1660 if (n_gpu_layers > (int)n_layer + 1) {
1661 ggml_cuda_assign_buffers_no_scratch(cache.v);
1662 LLAMA_LOG_INFO("%s: offloading v cache to GPU\n", __func__);
1663 vram_kv_cache += ggml_nbytes(cache.v);
1664 }
1665 if (n_gpu_layers > (int)n_layer + 2) {
1666 ggml_cuda_assign_buffers_no_scratch(cache.k);
1667 LLAMA_LOG_INFO("%s: offloading k cache to GPU\n", __func__);
1668 vram_kv_cache += ggml_nbytes(cache.k);
1669 }
1670 if (vram_kv_cache > 0) {
1671 LLAMA_LOG_INFO("%s: VRAM kv self = %.2f MB\n", __func__, vram_kv_cache / 1024.0 / 1024.0);

Callers 1

Calls 9

ggml_type_sizeFunction · 0.70
ggml_tensor_overheadFunction · 0.70
ggml_initFunction · 0.70
ggml_new_tensor_1dFunction · 0.70
ggml_set_nameFunction · 0.70
ggml_nbytesFunction · 0.70
n_embd_gqaMethod · 0.45
clearMethod · 0.45
resizeMethod · 0.45

Tested by

no test coverage detected