4.1.8. 模型权重复用
对于大语言模型(如Qwen等)或者一个模型多个实例,如果模型内每个权重(weight)都分配一块设备内存来存放权重值,可能会导致内存消耗较大。为了节省内存空间,并且更有效地访问内存,TCIM支持通过weight manager共享存放权重的设备内存。当一个模型内同时并行执行多个任务,或者多个模型具有相同的权重并且部署在同一个的设备上时,可设置共享同一个存放权重的设备内存(weight memory)。
用户可在加载模型时,指定使用与其他模型相同的weight manager,来共享同一个weight memory。
注意
当调用接口创建 WeightManager 对象后,该对象并没有被立刻实例化,而是在加载模型时才实例化。这种延迟实例化机制可以减少不必要的资源占用,并确保weight manager在实际需要时才分配资源,从而提升内存和计算效率。
使用步骤如下:
创建Module对象。
调用
tcim::Module::WeightManager::CreateWeightManager(C++)或tcim_lite.runtime.WeightManager(Python)创建weight manager。创建
tcim::Module::Option(C++)或tcim_lite.runtime.Option(Python)对象用于设置模型配置相关的参数,如weight manager。调用
Module::LoadModel(C++)或tcim_lite.runtime.load(Python)加载模型。
下面示例展示了如何使用共享weight memory。示例仅展示了关键步骤的代码,仅供参考,不可以直接拷贝运行:
C++示例如下:
// Create Module objects: module_wm_1 and module_wm_2
auto module_wm_1 = std::make_shared<tcim::Module>();
auto module_wm_2 = std::make_shared<tcim::Module>();
{
// Create a weight manager
auto weight_manager = tcim::Module::WeightManager::CreateWeightManager(0);
// Create a Option object to set configurations for loading models
tcim::Module::Option option(weight_manager);
// Load model with the weight manager
module_wm_1->LoadModel("tcim_resnet50.hmm", option);
module_wm_2->LoadModel("tcim_resnet50.hmm", option);
// After loading the models, the option and weight manger could be released.
}
module_wm_1.reset();
//The weights will released here
module_wm_2.reset();
Python示例如下:
import tcim_lite as tcim
# Create a weight manager
weight_manager = tcim.runtime.WeightManager(0)
# Create a Option object to set configurations for loading models
option = tcim.runtime.Option(wm)
# Load models with the same weight manager
module_1 = tcim.runtime.load("tcim_resnet50.hmm", option = option)
module_2 = tcim.runtime.load("tcim_resnet50.hmm", option = option)
# After loading the models, the weight manger can be released.
del weight_manager
...
4.1.8.1. 使用限制
WeightManager 实例不支持同时加载一个模型并在其上推理另一个模型。