char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
fa88ae936
char/aliceai-t5-moe
1from __future__import annotations 2 3from typing import Callable ,Iterable ,TYPE_CHECKING 4 5if TYPE_CHECKING : 6from torch import Tensor 7 8from .base import ModelBase ,TextModel ,gguf 9 10from .llama import LlamaModel 11 12 13@ ModelBase . register ( "ChameleonForConditionalGeneration" ) 14@ ModelBase . register ( "ChameleonForCausalLM" ) # obsolete 15# [TAG_HF_EXAMPLE_GATED] facebook/chameleon-7b is gated 16# [TAG_HF_EXAMPLE_MISSING] 17class ChameleonModel (TextModel ): 18model_arch = gguf .MODEL_ARCH .CHAMELEON 19 20def set_gguf_parameters (self ): 21super ().set_gguf_parameters () 22self .gguf_writer .add_swin_norm (self .hparams .get ("swin_norm" ,False )) 23 24def set_vocab (self ): 25self ._set_vocab_gpt2 () 26 27@classmethod 28def filter_tensors (cls ,item :tuple [str ,Callable [[],Tensor ]])-> tuple [str ,Callable [[],Tensor ]]| None : 29name ,gen = item 30 31# ignore image tokenizer for now 32# TODO: image support for Chameleon 33if name .startswith ("model.vqmodel" ): 34return None 35 36return super ().filter_tensors (item ) 37 38def modify_tensors (self ,data_torch :Tensor ,name :str ,bid :int | None )-> Iterable [tuple [str ,Tensor ]]: 39n_head = self .hparams ["num_attention_heads" ] 40n_kv_head = self .hparams .get ("num_key_value_heads" ) 41hidden_dim = self .hparams .get ("hidden_size" ) 42 43if name .endswith (("q_proj.weight" ,"q_proj.bias" )): 44data_torch = LlamaModel .permute (data_torch ,n_head ,n_head ) 45if name .endswith (("k_proj.weight" ,"k_proj.bias" )): 46data_torch = LlamaModel .permute (data_torch ,n_head ,n_kv_head ) 47if name .endswith (("q_norm.weight" ,"q_norm.bias" )): 48data_torch = ChameleonModel ._reverse_hf_permute (data_torch ,n_head ,hidden_dim ) 49if name .endswith (("k_norm.weight" ,"k_norm.bias" )): 50data_torch = ChameleonModel ._reverse_hf_permute (data_torch ,n_kv_head ,hidden_dim ) 51 52yield from super ().modify_tensors (data_torch ,name ,bid ) 53 54# see: https://github.com/huggingface/transformers/blob/72fb02c47dbbe1999ae105319f24631cad6e2e00/src/transformers/models/chameleon/convert_chameleon_weights_to_hf.py#L176-L203 55@staticmethod 56def _reverse_hf_permute (data_torch ,n_heads ,hidden_dim ): 57head_dim = hidden_dim // n_heads 58data_torch = data_torch [0 ].view (2 ,head_dim // 2 ).t ().reshape (1 ,- 1 ) 59data_torch = data_torch .repeat_interleave (n_heads ,0 ) 60return data_torch