跳转至

gemma3

1 概述

1.1 背景介绍

gemma3是google团队开源的大语言模型,起开源项目地址为:

https://github.com/google-deepmind/gemma

模型下载地址为:

https://huggingface.co/google/gemma-3-1b-it

2 模型转换

2.1 offline模型转换

模型转换参考SGS_IPU_Toolchain路径下的doc/SDK_Doc_Release/M60/module/LLMConverter/llm_index.html,里面记录详细的大模型转换过程

2.2 offline模型

转换后模型拆分为

  • decoder_model_fixed.sim_sgsimg.img

  • norm_head_fixed.sim_sgsimg.img

  • token_embedding_weight.npy

  • local_cos_weight.npy

  • local_sin_weight.npy

  • global_cos_weight.npy

  • global_sin_weight.npy

一般大模型的head和embedding的权重是共享的,所以转换模型会是tie_embedding模式,参数转换到了token_embedding_weight.npy。

模型名称 模型介绍
decoder_model_fixed.sim_sgsimg.img 模型decoder部分
norm_head_fixed.sim_sgsimg.img 模型 head 部分
token_embedding_weight.npy 模型embedding 部分
local_cos_weight.npy 模型局部位置编码的cos部分的权重
local_sin_weight.npy 模型局部位置编码的sin部分的权重
global_cos_weight.npy 模型位置编码的cos部分的权重
global_sin_weight.npy 模型位置编码的sin部分的权重

2.3 模型实现

  • sdk/verify/opendla/source/llm/modular/gemma3_decoder.cpp

    实现了decoder_model_fixed.sim_sgsimg.img, token_embedding.npy,local_cos_weight.npy,local_sin_weight.npy,global_cos_weight.npy,global_sin_weight.npy的加载,子图和kv_cache内存的管理,实现了decoder模型推理的全流程。

    decoder_model_fixed.sim_sgsimg.img中含有多张prefill 和decode 过程的子图,prefill的子图每次推理的token数一般设为了128,kv_cache对应最大的token_legnth逐渐增大,比如512/1024/2048等。decode的子图每次推理的数量为1,最大的token_legnth和prefill对应。在调用decoder_model_fixed.sim_sgsimg.img模型时,会根据不同的阶段和输入调用不同的子图,具体参考sdk/verify/opendla/source/llm/gemma3/gemma3.cpp

    • 备注:由于gemma3的decoder采用了sliding_window,所以在处理local kv cache时需要特殊处理,ipu内存实现采用的时循环内存管理,prefill过程按照正常流程进行推理,当prefill结束进行decode过程时需要判断当前运行position是否超过sliding window,超过了sliding window 时,选出sliding_window大小的local_kv_cache,然后循环地复用这块buffer. 特别注意u32SlidingOffset的赋值,标志着循环内存的起始位置。
  • sdk/verify/opendla/source/llm/modular/norm_head.cpp

    实现了norm_head_fixed.sim_sgsimg.img 模型的加载和推理流程。

3 板端部署

3.1 程序编译

示例程序编译之前需要先根据板子(nand/nor/emmc, ddr型号等)选择deconfig进行sdk整包编译, 具体可以参考alkaid sdk sigdoc《开发环境搭建》文档。

  • 编译板端qwen3示例。

    $cd sdk/verify/opendla
    $make clean && make source/llm/gemma3 -j8
    
  • 最终生成的可执行文件地址

    sdk/verify/opendla/out/${AARCH}/app/prog_llm_gemma3
    

3.2 运行文件

运行程序时, 需要准备以下几个文件

  • prog_llm_gemma3
  • gemma3 离线模型

3.3 运行说明

  • Usage: ./prog_llm_gemma3 -d gemma3_model_path -p "who are you"(执行文件使用命令)

    • -d 指向转换后的gemma3模型,里面包含转换的模型文件以及对应的json文件
    • -p 指的是提示词,demo现在传的是 "who are you"
  • Typical Output:

    ./prog_llm_gemma3 -d gemma3_model_path -p "who are you"
    
    Assistant:  there! I'm Gemma, a large language model created by the Gemma team at Google DeepMind. I’m an open-weights model, which means I’m openly available for use and research.
    
    I can take text and images as inputs and respond with text.
    
    How can I help you today?